Compare commits

..
922 Commits
Author SHA1 Message Date
Brues d7103de564 feat(spell): count set bonuses in GetSpellBonusHealing
Set-bonus spells are applied server-side as auras the client never sees
as buffs or known spells, so the derived healing sum missed them —
Lawbringer (3) is "Increase Healing 31" (9317), Judgement (3) is 57
(18037). Add a pass that counts the equipped members of each set from
the item record's set id (OFF_ITEMSTATS_ITEM_SET), reads ItemSet.dbc's
bonus spells and member thresholds, and runs every met bonus through
the same aura decoder — the rule the item tooltip's set-bonus lines use
at 0x52DFB9.

The Ironclad (aura 199) armor conversion stays on
UNIT_FIELD_RESISTANCES[0]: the server's SpellBaseHealingBonusDone uses
GetArmor(), the full total, even though the talent text says "Armor
from items".

Refs #135
2026-11-09 11:28:51 -06:00
Brues c00eb24a8d fix(event): refuse glue's event table and re-validate cached claim slots
CGGameUI::Initialize (0x0048FE00) calls RegisterScriptFunctions — where
our LoadScriptFunctions hook enables claim writes — and only then
SetScriptEventTable(0xBE1198, 0x225), which builds the in-game table.
Between the two the live table at [0xCEEF68] is still glue's 26-entry
one. A third-party DLL that registers a frame from its own
LoadScriptFunctions hook fires our Frame::RegisterEvent (0x00702140)
hook in that window: Grow enlarged the glue table (26 -> 142), the
reservations claimed slots 26..125 in it, the engine freed that buffer
and built the real table, and every cached slot stayed non-negative —
never retried, invisible to IsEventValid, and a Fire would have
signalled whatever engine event sat at that id.

Two guards, both read off the engine's own build:

- GameTableInstalled: the in-game build always passes 0x225 names and
  the other DLLs' SetEventCount clamps only enlarge, so a table smaller
  than EVENT_NAME_TABLE_STATIC_COUNT is glue's. Claim and Grow refuse it.
- Stale: each reservation keeps the SStrDup'd pointer it wrote; when the
  live entry at its slot no longer holds that pointer (or name), the
  table was rebuilt behind us and every slot is forgotten and re-claimed
  before the original RegisterEvent populates any chain.

Fixes #134
2026-11-09 11:05:32 -06:00
Brues b65c9e0319 fix(spell): never auto-unshift out of Spirit of Redemption
3.3.5's and 4.4.2's SpellShapeshiftForm.dbc give Spirit of Redemption
(form 32) flags 0x4100, which include SHAPESHIFT_FORM_FLAG_NO_AUTO_UNSHIFT
(0x100). So the later clients' CGUnit_C::CanAutoUnshift refuses it, and no
cast, interaction or item use cancels it. 1.12's row has flags 0, so with
autoUnshift on, our CanAutoUnshift allowed it. A priest in Spirit of
Redemption who cast a NOT_SHAPESHIFT spell, right-clicked an NPC or object,
used an item or opened the flight map sent CMSG_CANCEL_AURA for it.

The later-client flags that 1.12's rows lack now sit in one table:
CAN_INTERACT on the druid forms and Ghost Wolf (read only while
autoUnshift is on, as before), and NO_AUTO_UNSHIFT on form 32, which
CanAutoUnshift reads unconditionally, as 4.3.4 does. With it, every
autoUnshift site leaves Spirit of Redemption on and keeps 1.12's own
refusal.

The comment on FormCanInteract also records why a locked object still
unshifts. It opens by a spell (Opening 6478 for chests and barrels), and
the server's CheckCast form test refuses that spell on 1.12's spell data,
which keeps SPELL_ATTR_NOT_SHAPESHIFT (3.3.5 dropped it).
2026-11-08 11:29:09 -06:00
Brues de033896b1 feat(spell): let autoUnshift talk and use objects in the druid forms
1.12's SpellShapeshiftForm.dbc gives SHAPESHIFT_FORM_FLAG_CAN_INTERACT
(0x8) only to Shadowform. 3.3.5 and 4.4.2 also give it to Cat, Travel,
Aquatic, Bear, Dire Bear and Ghost Wolf, and Turtle's id 11 (Swift
Travel Form) has it there too. So in the later clients, these forms pass
the NPC right-click gate (CGPlayer_C::HandleOnRightClick, 0x005F0130)
and the game-object use check (0x005F3130) as they are. The form cancel
that comes before the range check almost never runs.

In 1.12, autoUnshift cancelled every druid form at that gate, even when
the NPC was out of interact range. With autoUnshift on, the redirected
IsShapeShifted calls at both gates and at CanInteractNow (0x00606880)
now read a form in that set as able to interact. They report "not
shifted", so the engine's own 0x8 test that follows does not refuse it,
and the cursor shows the NPC's service icon. The cancel stays for a form
that cannot interact in either client.

Neither vmangos nor tortoise-wow tests the form on an NPC or object
interaction. CanInteractWithNPC and the use handlers have no form check;
the only one is item use. So the client gates are the only refusal.
2026-11-07 20:46:48 -06:00
MrbcatandBrues dc8d4caf12 fix(loot): skip corpses that stay lootable after LootAllCorpses (#133)
* fix(loot): skip corpses that stay lootable after LootAllCorpses

A corpse whose remaining loot this player can never take keeps
UNIT_DYNFLAG_LOOTABLE set: quest items for quests they don't have,
condition-gated loot, and the like. The per-corpse re-check still
passes, so a caller that runs C_Loot.LootAllCorpses from a timer
re-opens the same corpse on every walk and re-sends the refused
CMSG_LOOT_ITEM, which never clears.

Loot mode now remembers every corpse it opened and released. Later
walks skip a remembered corpse while it is still visible and
lootable; the entry is dropped once the corpse stops being lootable or
leaves the object manager. A corpse that merely left render range is
dropped too, so it gets one retry when the player comes back.
ScanNearbyLoot stays read-only and keeps reporting the corpse.

1.12 has no per-slot "cannot loot" flag (GetLootSlotInfo has no
`locked` return), so one refused request per corpse is unavoidable;
this only stops it from repeating on every walk.

* docs(loot): describe the LootAllCorpses corpse skip

Explain why a corpse that stays lootable after the walk is skipped by
later walks, and when the skip entry is dropped.

* fix(loot): skip only corpses that open empty in LootAllCorpses

The previous change remembered every corpse the loot walk opened. The
most common reason a corpse stays UNIT_DYNFLAG_LOOTABLE is full bags,
so those corpses were never looted again by the walk, even after the
player freed bag space. Rolls and master-loot assignments in progress
had the same problem.

The server never sends a player a loot slot that player cannot take:
another member's quest item and condition-gated loot are left out of
SMSG_LOOT_RESPONSE, while the corpse stays lootable for as long as any
loot remains. So the stuck corpse opens to an EMPTY window, with no
coin and no populated VAR_LOOT_SLOTS entry. Loot mode now remembers a
corpse only when the scraped window is empty. A window with anything
in it (full bags, a roll, a master-loot slot) is retried.

An entry is forgotten:
- on the first world tick where its unit is gone or no longer
  lootable. This replaces the prune at walk start, which missed a
  corpse that left view and came back, and a creature that respawned
  with the same GUID and died again, between two walks;
- all at once on QUEST_LOG_UPDATE (event 0x134, observed through the
  shared FUN_FIRE_EVENT_NO_ARGS interceptor and never swallowed),
  because quest items are per-player loot and a quest change can put
  an item into a window that was empty.

The memory moves out of the per-walk ScanCtx into its own vector. The
API reference now describes the skip as a contract only.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-11-06 23:25:23 -06:00
Brues 20069f3815 docs(api): sort the reference's sections alphabetically
Seven sections were out of place in the body: ChatBubbles (after Mount),
Bindings (after Focus), APIDocumentation, CVar, MerchantFrame, NamePlate
and PvP. The contents list shared the last four. Both are now in the same
case-insensitive order, with one blank line between contents groups
(DeathInfo and Sound had none). The ClassicAPI namespace section had no
contents entry; it has one now.

The PVP_TIMER_UPDATE entry moves from the PvP section to Events, between
PLAYER_SWING_RANGE_UPDATE and QUEST_ACCEPTED. It now names the PvP timer
and links the two timer functions, and the PvP section links to it.
2026-11-06 17:35:16 -06:00
Brues f2fa112f0a feat(mount): add C_MountJournal.GetMountFromSpell and GetMountInfoExtraByID
1.12.1 has no mount table, so a mount's ID is the ID of the spell that
summons it: GetMountFromSpell(458) returns 458. A spell is a mount when
one of its effects applies SPELL_AURA_MOUNTED (78); Spell.dbc is read
directly, so mounts the player has not learned resolve too. On Turtle
every mount item carries spell 46499 "Add Mount to Collection" instead of
its mount spell (the server maps item to spell from its own table), so
only the mount spell gives a mount ID.

GetMountInfoExtraByID returns the nine retail values. The display ID is
the one the server mounts the player on: the mount aura's misc value is a
creature entry, and the client's creature cache holds that creature's
display (SMSG_CREATURE_QUERY_RESPONSE carries the template's first
display, and every mount creature has exactly one). An uncached creature
returns nil and starts the cache load through the new
Creature::Info::RequestLoad, which C_CreatureInfo.RequestLoadCreatureByID
now uses too; CREATURE_DATA_LOAD_RESULT fires when the data lands.
Verified in game: 23219 (Swift Mistsaber) returns 14332.

Mount type and model scene default to 230 and 4. Seven mounts take
retail's values instead (the six Qiraji battle tanks use scene 44, the
Riding Turtle type 231), each checked by name against Turtle's
Spell.dbc. The seat animation is 91 (Mount), the animation 1.12.1's
world mount plays on the rider.
2026-11-06 17:29:11 -06:00
Brues fca967c827 refactor(spell): test a spell's auras through one HasAuraEffect
Six places asked the same question of a Spell.dbc record: does one of its
three effects apply aura N (EffectApplyAuraName, +0x16C, int32[3])? Each
had its own loop: the combat log's damage-shield lookup, crowd-control
classification and its snare test, tracking-spell detection,
C_SpellBook.GetPlayerSpellsByAura, and the aura-source periodic-damage
gate (which also hard-coded 3 for the effect count).

Spell::Lookup now has FindAuraEffect (the index of the first effect that
applies the aura, or -1, for callers that read that effect's other
columns) and HasAuraEffect on top of it, next to the existing HasEffect.
All six call it. Code that pairs an aura with the same effect's misc
value, amount or effect code (Cancel, Interruptible, BonusDamage,
StatAccum, EffectInfo) keeps its own per-effect reads.
2026-11-06 17:29:02 -06:00
Brues 24404b5a23 fix(swing): report only a held main-hand reset at attack start
SMSG_ATTACKSTART re-fired PLAYER_SWING(MainHand) whenever the main-hand
swing was still running. That was meant for a cast reset recorded before
the attack (held back because no swing was coming yet), but the server
also sends SMSG_ATTACKSTART on a target switch mid-attack. Unit::Attack
then resets only the off-hand timer; the main-hand swing keeps going.
The event carried just the time left in that swing, so listeners read a
nearly finished swing as a fresh, short one.

Each swing type now carries a held flag, set only by a reset recorded
without notify and cleared when that type's PLAYER_SWING fires. The
attack-start path reports the main hand only while it is held.

Fixes brues-code/SuperCleveRoidMacros#11
2026-11-06 12:58:12 -06:00
Brues a106d86969 fix(unit): consult the name cache only when no unit object is held
UnitClassBase and UnitRaceBase now follow stock Script_UnitClass
(0x00518350) and Script_UnitRace (0x00518200) branch for branch.
"player" reads the selected-character record; any other token goes
through GetGUIDFromName + ClntObjMgrObjectPtr(TYPEMASK_UNIT) and reads
the held object's descriptor byte (+0x79 class, +0x78 race). The
NameCache record (+0x140 / +0x138, null callback) is peeked only when
no object is held.

Before, the NameCache was also peeked when a held object's byte was 0.
That never changed a result (creatures are not in the NameCache) but
resolved the token twice and did not match the engine's branch.

The comments and API.md also claimed creatures return nil, that class
IDs run 1-9, and that UnitClass has a third return. None of that is
true: creatures go through the same ChrClasses/ChrRaces lookup as in
UnitClass/UnitRace, Druid is 11, and stock returns exactly two values.
2026-11-06 11:52:58 -06:00
Brues fac3be3a0b refactor(lua): take integer enum and constants entries as arrays
RegisterIntegerEnum and RegisterConstants took their entries with a
count beside them, written as sizeof(t) / sizeof(t[0]), std::size, or
a literal. They now take Game::ArrayRef<EnumIntegerEntry>, as
RegisterFrameMethods does, so the count comes from the array's type.
The documentation recorders RecordEnum and RecordConstants take the
same view.

All 34 call sites pass only the array. The six literal counts were
checked against their arrays first: each was the full length, so every
Enum.* and Constants.* table gets the same entries as before. Five
files that included <iterator> only for std::size drop it.
2026-11-06 11:34:27 -06:00
Brues b49c107778 refactor(lua): take frame-method tables as arrays, not pointer and count
Every RegisterFrameMethods call passed its method table and doc table
with a count beside each: sizeof(t) / sizeof(t[0]), std::size, or a
literal. The literals had to be kept in step with the tables by hand.

Game::ArrayRef<T> is a view over a file-scope array that takes the
count from the array's type, the way Doc::FieldList already did for a
function's arguments and returns. FieldList is now ArrayRef<Field>,
Doc::MethodList is ArrayRef<Method>, and RegisterFrameMethods takes
(context, methods, docs). The table and count still go to the engine's
frame-method iterator (FUN_REGISTER_FRAME_METHODS) unchanged, and to
the documentation recorder.

All 84 call sites pass only the arrays. The 16 literal counts were
checked against their tables first: each was the full length, so every
registry gets the same methods as before.
2026-11-06 11:27:22 -06:00
Brues 53b7f79440 fix(model): release dress builders and stopped effects with their frame
/reload crashed with an access violation in the model release
(0x007103A3, inside FUN_MODEL_INSTANCE_RELEASE 0x007103A0) when
SetDisplayInfo had dressed a few panes.

1.12.1 reloads in two steps. CGGameUI::Shutdown (0x00490BD0) deletes
the CSimpleTop, which destroys every frame. A Model frame's teardown,
DestroyModelFrame (0x0076CA50, from the CSimpleModel and
CGCharacterModelBase destructors), releases the frame's M2 scene at
+0x314, and the scene frees every model in it, even one that something
else still holds a reference on. Only then does CGGameUI::Initialize
(0x0048FBF0) reset the Lua state, which runs FrameScript_Initialize
and our reload cleanups. DisplayInfo's cleanup destroyed each kept
compositor there (FUN_CHARCOMP_DESTROY 0x00476000), and the compositor
released its reference to a model that was already freed. VisualKit's
cleanup detached and released stopped one-shot effects that live in
the same freed scene.

Model::Teardown hooks DestroyModelFrame and runs its subscribers
before the original, while the frame's scene and models are intact,
which is where the engine frees what its own frames hold. DisplayInfo
drops the frame's dress job there, and VisualKit records each stopped
effect's pane (in the done callback's user data) and discards that
pane's effects there. Their reload cleanups keep only the
pointer-keyed state.

The ReloadAutoRegister doc now says that the cleanups run after the
frames are gone, so they may forget pointers but never release an
engine object tied to a frame.
2026-11-06 11:16:47 -06:00
Brues 7b21453469 refactor(model): share the engine model calls across the model modules
The model modules each declared their own pointers to the same 1.12.1
engine functions: the instance gates FUN_MODEL_INSTANCE_LOADED
(0x007103D0) and FUN_MODEL_INSTANCE_READY, AddRef / Release
(0x00710390 / 0x007103A0), FUN_M2SCENE_CREATE_MODEL,
FUN_M2MODEL_PLAY_ANIMATION, the done callback, the item visuals, the
render callback, the M2 data lookup FUN_M2_LOOKUP_INDEX (0x00710310),
and the pane's model, scene, SetModelInstance virtual (vtable +0x90)
and SetDisplay. model/M2.h now holds one typed wrapper for each, and
every module calls through it.

- Game::Lua::ResolvePlayerModel / ResolveDressUpModel join the
  per-type resolvers, replacing four ResolvePane copies and five
  inline ResolveTypedObject calls. Game::Lua::TYPE_NONE replaces the
  local kTypeNone in Rotation and frame/CreateFrame.
- Offsets.h has the full INVTYPE list, 0..28, named by the engine's
  own key table at 0x0083DDB0. It replaces the four scattered
  INVTYPE_* entries and the local copies in DressUp and ItemDisplay,
  and the try-on result switch reads by name.
- DisplayInfo keeps its dress jobs in a map by frame, like the other
  modules, in place of the fixed 8-slot pool and its eviction.
- DressUp names the held lane's bytes (item class, inventory type,
  sheathe type) and detaches a lane in one place.
- ItemDisplay::OwnVisual is the one test for a display's own
  ItemVisuals row (GetItemDescVisual 0x0062EC70), used by SetItem and
  by TryOn's enchant glow. Both own-record panes share
  Pane::DisplayRecord, and the SetDisplayInfo records are cleared on
  /reload as the SetItem records are.
2026-11-06 11:11:18 -06:00
shikuljaandBrues ebfd9d034d feat(localization): complete and correct the Russian locale (#130)
* feat(localization): complete and correct the Russian locale

The Russian locale was 99 keys behind enUS, so a Russian client kept the
English strings for ClassicAPI's own options: the AddOn Options title and
its game-menu button, every page name, header, control label and tooltip,
the AoE Loot binding, and the generic strings the options pages gained
(FOCUS_TOKEN_NOT_FOUND, LUA_ERROR, RELOADUI, PLAYER_LIST_DELIMITER,
SYMBOLIC_NEGATIVE_NUMBER, SYMBOLIC_POSITIVE_NUMBER and the money texture
formats). All 327 keys are now present, in enUS order, so the two files
diff key by key.

Focus follows the client's modern terms — «Взять в фокус», «Сбросить
фокус», «Выбрать фокус» and «Взять цель в фокус» — matching the existing
/фокус and /сбросфокуса aliases. The rest uses the 1.12 Russian client's
vocabulary where it has one (модификация, цель, панель команд, время
восстановления, табличка с именем) and «динамическое выделение» /
«мягкая цель» for action targeting. The money strings keep their |4
plural forms, which GetCoinText expects.

Fixes:

- LARGE_NUMBER_SEPERATOR was "", which turned digit grouping off. It is
  now a space, as in the tooltip's 1 234 567.
- FIRST/SECOND_NUMBER_CAP and their _NO_SPACE twins carry the leading
  space, because Abbreviate concatenates the number and the suffix
  directly.
- EQUIPMENT_MANAGER_ITEMS_MISSING_TOOLTIP printed a slot number where
  the missing count belongs; it now takes the missing count.
- SETTINGS_BIND_KEY_TO_COMMAND_OR_CANCEL was missing a space before
  «или нажмите».
- SET_FRIENDNOTE_LABEL had a |3-5 declension token, which 1.12 renders
  literally.
- ITEM_SLOTS_IGNORED and ITEMS_NOT_IN_INVENTORY had wrong third plural
  forms, ITEM_MOD_HIT_MELEE_RATING_SHORT had a double space, and the flat
  stat labels (Защита, Уклонение, Парирование, Блок) read wrong after a
  signed value, so they use the same «к …» form as the other ITEM_MOD
  labels.

The TOC gains ## Notes-ruRU next to ## Notes.

* fix(localization): restore retail ruRU focus, number and log strings

Follow-up to the Russian locale completion, which had changed several
strings that the retail ruRU client already translates. Each is now
the retail text, or a correction where the new wording was wrong:

- Focus: the FOCUSTARGET / TARGETFOCUS binding labels were swapped
  (FOCUSTARGET runs FocusUnit("target"), TARGETFOCUS runs
  TargetUnit("focus")). All focus strings use retail ruRU's terms
  again: Запомнить цель, Восстановить цель, Отменить запоминание цели,
  Запомненная цель, <фокус отсутствует>.
- EVENTTRACE_LOG_DISCARD is the message logged after the log is
  discarded; it had become an option-style label. Retail: Журнал
  сброшен. EVENTTRACE_BUTTON_DISCARD_FILTER read "cancel all"; retail:
  Сбросить все.
- FIRST/SECOND_NUMBER_CAP and their _NO_SPACE variants go back to
  retail Т / М. AbbreviateNumbers appends the _NO_SPACE suffix
  directly by design ("1.2K"), so " тыс." widened compact numbers.
- LARGE_NUMBER_SEPERATOR goes back to retail "" (as frFR). A plain
  space also let a number wrap across lines. The separate-large-numbers
  tooltip drops its "1 234 567" example, which no longer applies.
- The loose-target option read "whom the soft target follows". The
  normal target is the one that follows, so it is now "обычная цель",
  and the choices name the soft enemy / soft friend.

* fix(localization): pick language rules by locale name, not 4.3.4's index

1.12.1's locale index (VAR_LOCALE_INDEX, 0xC0E080) is the Wow.ini
Language+Country tag's position in the eight-entry name table at
0x8558A4 (enUS koKR frFR deDE zhCN zhTW esES xxYY), stored once at
0x402562 and 0 when nothing matches. It is never 8. The Russian branches
ported from 4.3.4 switched on 4.3.4's own slot numbers (esMX 7, ruRU 8),
so they could never run: a client whose GetLocale() is "ruRU" fell
through to the default plural rule ("5 предмета") and got no ё/е folding
in bag search.

Localization::Locale::Client() reads the same entry Script_GetLocale
(0x48D8B0) pushes, table[index], and Is(code) compares against it. The
language-rule sites now go through it:

- Text::Grammar's plural index (|4 expansion) keys koKR/frFR/zhCN/zhTW
  and ruRU by name.
- Container::Search picks its accent-folding set by name, as a Folding
  value instead of an index switch.
- Localization::Numbers' ClientIsAsian reuses IsAsianLocale on the name.
- AddOns::TocRewrite drops its private copy of the reader, and the
  slot-8 clamp, which guarded an index that cannot occur.

The DBC column reads keep using the index, which is what it is for.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-11-06 10:25:00 -06:00
Brues d825bcbdda fix(spell): stand, dismount and unshift only when the cast is sent
autoStand / autoDismount / autoUnshift ran their actions as soon as the
caster-state check (CheckCasterStateForSpell, 0x006094F0) passed. In the
1.12.1 cast request (TryCastSpell, 0x006E4B60) that check comes before
the target arm (0x006E5250), so a cast that then found no target still
dismounted the player and showed "You have no target" (Charge with
nothing targeted). A targeting cursor the player cancelled did the same.

The caster check now only keeps what its rungs noted, and the actions run
at the send. SendCast (0x006E54F0) builds the cast packet; its five
callers all pass the global pending cast: the arm's two immediate sends
and the object / location / trade-slot binders, which the targeting
cursor's click also runs. The arm's only caller is the cast request,
after the caster check, so every send follows a check of the same cast.
Each action runs only if its state still holds, since the player can
stand, dismount or leave the form while the cursor is up. The send
redirects must all apply before the rungs are patched.

Item use had the same ordering gap. Its form refusal (0x005D914D) comes
before the toggle test, which turns off a use aura that is already up
instead of casting (0x005D9157..0x005D9237). Re-using such an item while
shapeshifted dropped the form as well. The refusal now only notes the
unshift; it runs at the bind-on-use test (0x005D91D3), which every path
past the toggle reaches, and the toggle's cancel call clears it.

Fixes #132
2026-11-06 09:56:14 -06:00
Brues 6b36bb10e6 fix(spell): report GetSpellPowerCost in displayed power units
The engine's cost helper (FUN_006E31B0) answers in stored units, and
1.12.1 stores rage in tenths, so Shield Slam's 20 rage came back as
cost = 200. Divide by the engine's own display divisor
(GetPowerDisplayDivisor, 0x006E7130: [0x0086F978 + 4*type], 1 for a
negative type; table {1, 10, 1, 1, 1000}) before pushing, the same way
the engine and our UnitPower / GetSpellInfo / combat-log paths do.

Every power amount surfaced to Lua now goes through one helper,
Unit::Power::DisplayDivisor, which calls that engine function. That
retires the duplicate FUN_GET_POWER_DISPLAY_DIVISOR offset, the two
local typedef copies, and UnitPower's direct read of the divisor table
(VAR_UNIT_POWER_DIVISOR_TABLE, now removed).

Fixes #129
2026-11-05 08:51:59 -06:00
Brues 6628dcca19 fix(loot): keep LootAllCorpses walking past refused and stale corpses
The walk ignored the server's refusal. A failed CMSG_LOOT ("too far
away", not ours, ...) arrives as SMSG_LOOT_RESPONSE with loot type 0;
CGPlayer_C::ReadLootResponse (0x005EB900) shows the error and clears the
held loot target (+0x1D28) without opening a window, and the release
response (0x005EC090) clears it the same way. The walk only advanced on
the loot controller hook or a 180-frame timeout, so each refusal stalled
it for seconds. It now advances as soon as the held target is no longer
the corpse it sent for.

A send the engine refused dropped the whole queue. LootUnit (0x005DF2A0)
sends nothing while the mover flags & 0x20FF are set (moving, turning,
falling), and the walk treated each refusal as "skip this corpse", so
moving during a walk skipped every corpse left. A refused send now stays
the current corpse and is retried each tick; after 3 s the walk ends.

The queue's range check went stale. Range was tested once when the walk
began, but each corpse costs a round trip and the player can move in
between. With CanAutoInteract set, CanLootNow (0x005EC110) skips its own
reach test, so the request went out and the server refused it. Each
corpse is now checked for existence, DYNFLAG_LOOTABLE and reach right
before its send, and skipped when it fails.

The reach test is CanLootNow's own: both units' +0x1F0 reach plus the
engine's leeway, at least its minimum, with both constants read live
(VAR_MELEE_REACH_LEEWAY / VAR_MELEE_REACH_MIN) instead of local copies.
It and the lootable test move to Loot::Request, shared by
GetNearbyLootableUnits and the walk. The step timeout uses Time::Clock
instead of a frame count.
2026-11-04 20:04:35 -06:00
Brues 55d94c80d6 feat(spell): apply autoStand/autoDismount/autoUnshift to interaction, loot, items, attacks and taxis
The three settings only covered casts. Each 1.12.1 gate that refuses an
action for the player's stand state, mount or form now passes when the
matching setting allows it, and the engine's own action (the stand setter
FUN_005ED430, or CMSG_CANCEL_AURA for the mount / form aura) runs just
before the action is sent. With the settings at 0 nothing changes.

- NPC right-click (0x005F0130): the IsShapeShifted call at 0x005F0150
  cancels a form without SpellShapeshiftForm flag 0x8 instead of showing
  ERR_CANT_INTERACT_SHAPESHIFTED. CanInteractNow (0x00606880), whose only
  caller is the hover cursor, passes the same form, so the NPC's service
  cursor shows.
- Game objects: the use check (vtable slot 6, 0x005F3130), also the hover
  cursor's query, passes the mount (0x005F31A8) and the form (0x005F31E1)
  for an object with no Lock row. The default use's no-spell branch
  (0x005F35DF, before CMSG_GAMEOBJ_USE) and the mailbox and text use slots
  dismount (except at a mailbox, FUN_0047CFF0) and cancel the form. A
  locked object opens by a spell, which the cast path already handles.
- Loot: the GetStandState calls of the unit (0x0060BFB7) and corpse
  (0x005D6C3B) right-clicks stand the player up instead of showing
  ERR_LOOT_NOTSTANDING. The unit loot step's mount read (0x0060BF98)
  passes, and LootUnit dismounts before CMSG_LOOT (0x005DF3B3).
- Item use (0x005D8D00): the ERR_NO_ITEMS_WHILE_SHAPESHIFTED refusal at
  0x005D914D cancels the form and continues. Turtle's exe already skips
  that test; the stock exe reaches it.
- Attack: the mount reads in the attack cursor (0x00482659), the
  right-click attack (0x0060C1B4), StartAttack (0x005ECC06) and both tests
  of the attack resolver (0x00613039, ERR_ATTACK_MOUNTED; 0x00613142)
  pass. StartAttack, after all its tests (0x005ECC56), dismounts when the
  target is in melee reach (Combat::Swing::InMeleeRange). Otherwise it
  returns without attacking and shows ERR_OUT_OF_RANGE, except while
  click-to-move (FUN_0060F900) walks the player there.
- Taxi: after the taxi map opener's TAXIMAP_OPENED tutorial call
  (0x004DBAA2), a map with more than one node stands the player up,
  dismounts and cancels the form, each when its setting is on.

Every site is patched only when it holds the expected stock bytes, which
both the Octo and stock 1.12.1 exes do.
2026-11-04 16:44:44 -06:00
Brues c0b403ba05 feat(model): add PlayerModel:ApplySpellVisualKit
PlayerModel:ApplySpellVisualKit(spellVisualKitID [, oneShot]) shows a
SpellVisualKit's effects on the pane's model.

In the world, 1.12.1 plays a kit on a unit (0x0060EDF0), through effect
objects, spell durations and the unit's own animation, and a pane has
none of these. The engine's own kit on a bare model is the
char-select ghost (0x004727F0), and this is that routine for any kit on
the pane's model:
- Each of the nine effect columns (+0x0C) is created as a model from its
  SpellVisualEffectName file, in the pane's scene. It is attached at
  the column's attachment (20, 34, 19, 21, 22, 17, 23, 24, 25) when the
  model has that attachment (0x00712CB0, 0x00712F70), as in 0x00472780.
  The effects get the frame's light through LightChildren.
- Procedure kind 1 sets the tint (an 0xRRGGBB colour stored as a float,
  scaled by 1/255) and kind 14 the alpha, clamped to 0..1. Both are
  plain stores (0x00710CF0, 0x00710CB0), as the ghost kit makes them.
The kit's animation and sound do not play, which matches retail.

An effect model's sequence plays one time. Without oneShot, each effect
gets the world's loop callback (KitEffectLoopCallback, 0x0060ED00): a
clean end (reason 0) plays the animation again. With oneShot, each
effect gets EffectDoneCallback's test (0x005FBF50) and CEffect::Stop's
model steps (0x006203E0): clear the callback and hide the model, so
its emitters stop and the particles already out finish. A FrameTick
drain, which runs after the strata walk, then mirrors
DrainDyingEffects (0x0061F680). It detaches a stopped effect (0x00713020)
once HasLiveParticles (0x007135C0) is false, or at once when its
model has already dropped it. A model's destructor detaches its
children first (0x0070E3F5), so the drain never reaches a freed parent.

The effects are children of the pane's model, so SetUnit, SetItem or
a hide and show clears them.
2026-11-04 15:32:23 -06:00
Brues f6b98bc3ec fix(dbc): reject negative IDs in DBC::Record
DBC::Record checked the ID against the store's count as a signed int.
A DBC column uses -1 for "none", and -1 passed that check, so the
helper returned records[0xFFFFFFFF]. On 32-bit that wraps to
records[-1], the heap word in front of the index array. A caller that
passed an unchecked column read a garbage "record": an empty
SpellVisualKit effect column gave the pointer 0xF and crashed.

The engine rejects these IDs before it compares with the count: the
char-select ghost kit's effect step tests the ID with a signed jl at
0x00472797, then a jg against the count. Record now compares
unsigned, so it rejects 0, every negative ID, an ID above the count,
and an unloaded store, whose count is -1.

PvP::Arena had its own copy of the lookup with the same signed
compare. It now calls DBC::Record.
2026-11-04 15:32:22 -06:00
Brues 8f4f574174 feat(model): add PlayerModel:SetItem
PlayerModel:SetItem(itemID [, appearanceModID, itemVisualID]) shows one
item's own model in the pane: a weapon, shield, helm, shoulder, quiver or
ammo, with its skin texture and its glow.

A 1.12.1 pane shows whatever its display record names (+0x3F0).
SetDisplay (0x00505CB0) stores the record and builds it when the pane is
visible, the show path (0x00505D49) builds it again, and the SetUnit
helper (0x00505B50) clears it. SetItem gives the pane a record of its
own and passes it to SetDisplay. The AttachDisplayModel (0x00505A70)
co-hook in Model::DisplayInfo then builds the item instead of a
creature. So hide, show, SetUnit, SetDisplayInfo and SetKeepModelOnHide
handle an item with no new hooks.

The model is built from 1.12.1's own steps:
- the item folder by inventory type, from the engine's own
  Item\ObjectComponents\ path strings (0x00838CD8 on);
- model name 0, else name 1, with the texture of the same index;
- for a head item, the helm builder's (0x004799A0) path, with the
  player's race prefix (ChrRaces +0x18) and sex letter (0x00838AB4);
- AttachItemModelFile's (0x004798C0) steps: create the model in the
  pane's scene, load the skin with the item-model status (0x00B424F0)
  and filter 3, bind it as texture type 2 (0x00710EC0), and attach the
  item visuals (0x00479700);
- AttachDisplayModel's install: SetModelInstance (vtable +0x90), the
  pane's done callback (0x005062A0 through 0x00711BB0), Stand, and the
  release of the creation reference.

The display's own ItemVisuals row wins over itemVisualID, the rule
GetItemDescVisual (0x0062EC70) applies to enchants. The visual's child
models get the frame's light and fog callback, now a shared
LightChildren helper, so they are not drawn black. An uncached item is
queued through Item::Data::WarmCache, and each visible pane that still
shows it is built again when the item loads.
2026-11-04 14:21:58 -06:00
Brues 43a989dd56 feat(model): add PlayerModel:FreezeAnimation
FreezeAnimation(animation, variation, frame) holds the model in one
pose of an animation until the pane loads a new model, as SetAnimation
does. frame is the time into the animation in milliseconds, the unit
of M2 sequence times.

The engine's sequence time is start + (ftol(elapsed * speed) + offset)
mod length. So the pane's arm plays the animation through
PlayAnimation (0x007121A0) at speed 0 and writes frame to bone 0's
slot offset (+0xB8, bone states 0x118 bytes each at [model+0x90]).
Speed 0 also puts the end stamp on the start stamp. Update
(0x00719370) would then queue the done callback on the next frame, and
the pane's done callback (0x005062A0) would arm Stand. The arm
therefore sets the slot's done latch (+0xC0), the flag Update itself
sets once it has reported done. A held animation never ends.

SetAnimation and FreezeAnimation now also mark the pane for one re-arm.
A call with the animation that already plays then still starts or ends
a freeze, where the per-paint compare alone would skip it.
2026-11-04 13:52:02 -06:00
Brues 0caddb8fe6 feat(model): add PlayerModel animation, keep-on-hide and unit methods
Adds SetAnimation, SetDoBlend/GetDoBlend, HasAnimation,
SetKeepModelOnHide/GetKeepModelOnHide, CanSetUnit and GetDisplayInfo
to PlayerModel (and so to DressUpModel and TabardModel). SetUnit now
returns whether the unit exists, and SetCreature takes an optional
display ID.

Animation. A 1.12.1 pane rests on Stand: its per-paint UpdateModel
(0x00505C50) arms Stand (PlayAnimation 0x007121A0 with id 0) whenever
key bone -1 plays anything else and no turn is pending. A deadline of 0
counts as passed, so any other animation lasted one frame. SetAnimation
gives the pane a resting animation and variation of its own. With one
set, UpdateModel is hooked to arm that animation in Stand's place, using
the pane's blend setting. Every other pane runs the stock function. The
pane's done callback (0x005062A0) arms Stand when the animation ends,
so the next paint starts it again and it loops. CSimpleModelFFX's
SetModelInstance (0x0076CD30), which every pane model build and hide
goes through, clears it, so a new model rests on Stand again.
SetRotation turns without the shuffle while a resting animation other
than Stand is set. HasAnimation is PlayAnimation's own test on the raw
id: the lookup at shared data +0x24 must give an index below the
sequence count at +0x1C. It is false until the model has loaded.

Keep on hide. The pane's Hide (0x00505CE0) drops its model through
slot 36, and its Show (0x00505D00) builds a new one from the unit or
display record. With keep on, Hide runs only the base hide (0x0076AD50)
and Show runs only the base show (0x0076AE10) while the pane still
holds its model. The model then comes back with its try-ons and
animation. The SetUnit helper (0x00505B50, behind SetUnit, RefreshUnit
and Dress) and SetDisplay (0x00505CB0) only store the new subject while
the pane is hidden, so they drop a kept model first. The next Show then
builds the new one. Off is the default and matches the stock client.

Units and displays. SetUnit runs the engine's method (0x00505D70,
which Turtle patches) unchanged. It then reports whether the GUID it
stored resolves to a unit (type mask 8), the same test the helper uses
before it builds. CanSetUnit is that resolve without the set.
GetDisplayInfo reads the display record's ID, or the unit's
UNIT_FIELD_DISPLAYID (+0x1F4, field 0x7D). SetCreature with a display
ID shows that display through the SetDisplayInfo record.
2026-11-04 13:11:45 -06:00
Brues 8e603a7a0b fix(player): make IsLoggedIn false until PLAYER_LOGIN fires
IsLoggedIn returned whether the player GUID was set. That GUID falls
back to the char-select GUID before the world loads, and on a /reload
the live GUID is already set while the addons load. So IsLoggedIn was
true while every addon's files ran, and EventUtil.ContinueOnPlayerLogin
ran its callback at once instead of waiting for PLAYER_LOGIN. An addon
that hooked another addon this way hooked it before that addon had set
itself up.

1.12.1 fires PLAYER_LOGIN from one place: the enter cascade
(0x004908C0) calls FUN_FIRE_EVENT_NO_ARGS with 0x10E at 0x00490959,
once per interface initializer run (login and reload). Its arm byte
0x00B4E260 cannot answer the question directly: the initializer sets
it after the addons load (0x0049011D) and the cascade clears it after
the fire (0x0049095E). That call is now redirected to set a flag just
before the event goes out, and the FrameScript_Initialize cleanup,
which runs before every /reload and /logout, clears it.

IsLoggedIn is now false on glue and during addon load, and true from
the PLAYER_LOGIN handlers on, through world transfers.
UnitGUID("player") keeps its char-select fallback.
2026-11-04 13:02:26 -06:00
Brues 4726fd7c85 feat(model): add DressUpModel try-on hand, enchant glow, sheathing and auto-dress
TryOn now takes retail's (item [, handSlotName, spellEnchantID]) and
returns an Enum.ItemTryOnReason. The pane gains IsGeoReady, SetSheathed /
GetSheathed and SetAutoDress / GetAutoDress.

Hand: TryOnItem (0x00504540) picks a lane at one site, 0x0050492D
(mov edx,[edi+0x2C]; cmp edx,0x0D). A 6-byte call there jumps a named hand
to the worker's own main-hand (0x0050495F) or off-hand (0x005049B1) path,
so its CanHoldBoth (0x00504BC0) eviction, lane store and attach all still
run; with no hand it replays the two instructions and the jnz reads their
flags. The name is matched like GetInventorySlotInfo matches it: SStrCmpI
over the PaperDollItemFrame rows, slot 16 or 17.

Enchant glow: the player's AttachEnchantVisual step (0x005EED50) on the
attachment AttachItemModel (0x0047A0C0) returns: FindChild (0x00712F00),
then AttachItemVisuals (0x00479700) with SpellItemEnchantment +0x58,
skipped when the display's own ItemVisuals row exists (GetItemDescVisual's
rule, 0x0062EC70). The enchant is the argument, else the link's enchant
field, which Item::Arg now parses.

Sheathing re-runs the unit's AttachHandItem step on the pane's lanes with
the sheathed flag. The lanes keep no display row, so the pane records one:
the unit's vtable +0x9C row when SetModelInstance (slot 0x00808438) clones
it, then whatever the worker's attach (0x00504AE6) installs; its two
evictions (0x00504A0C, 0x00504A55) drop theirs. Each lane keeps its glow
too, a player's read through GetVisibleItem + GetItemDescVisual, so a
re-hung weapon keeps it. Auto-dress off runs ClearModel (0x00504490) after
SetModelInstance unless Dress() is the one rebuilding.

TryOn's result reads the gates the worker passes: an uncached record is
DataPending, a held type installs, armor needs the component and the
ready byte (+0x40C).

DressUpItemLink now passes the whole link to DressUpItem, so a
Control-click shows the link's enchant, and skips a cached item that
IsDressableItem rejects. DressUpItem stays, since Blizzard_AuctionUI and
Turtle both replace it.
2026-11-04 10:16:07 -06:00
Brues 3e0c40184b feat(cursor): add expanded cursors for NPCs and the fishing bobber
Adds the expandedCursors cvar (default 0; AddOn Options > ClassicAPI >
Interface > Cursor). At 1 the hover cursor shows what an NPC offers: an
anvil for a repairer, a hearthstone for an innkeeper, a horseshoe for a
stable master, and a quest giver's ! or ? (a blue ? for a repeatable
reward). The player's fishing bobber shows a fish hook in place of the
Interact gear. Each has a gray form beyond reach or when not usable.

NPCs: ClassifyHoveredUnit (0x00482200) reaches its NPC flag chain at
0x00482336 for a unit the player can interact with, the unit in ESI and
the beyond-reach flag in EBX. The chain's `mov ecx, [esi+0x110]` becomes
a call to a thunk. At 0 it replays the instruction and the stock chain
runs. At 1 it picks from the quest giver status first (CGUnit_C +0xCB8,
read by the meaning of the client's status-to-marker table at
0x0080C454), then the NPC flags in service order: repair, innkeeper,
flight master, trainer, spirit healer, banker, registrar/tabard/
battlemaster, auctioneer, stable master, vendor, then gossip or a quest
giver IsQuestGiverToTalk (0x005DF490) accepts. It leaves through the
chain's own epilogue (0x00482356).

Bobber: the fishing node handler's cursor slot (vtable 0x0080BC80, slot
4; GetCursor 0x005F8760 is its one reader) points at a wrapper that runs
BaseHandlerGetCursor (0x005F3070) and maps Interact/UnableInteract to
the hook. The engine still decides whether the bobber is interactable
and usable.

Showing a mode past 41: SetCursorMode indexes a 42-slot image table, so
its existing hook now sends the new modes to Cursor::Extended::Show. It
calls SetCustomCursor (0x00523C40) with the mode's path, so a real file
wins, and otherwise does what that function does after its load: copy
the 32x32 image into slot 41 (0x00C0BD80), store mode 41, send it
(SendCursorImage 0x00523790) and keep the name. The hook also records
the new modes while Hover::Mode computes, so the soft-interact pick, its
icon and SetUnitCursorTexture follow; a quest cursor has no icon image.

Images: the 14 BLPs ship inside the DLL (src/embed/Textures, a new
TEXTURES_ROOT pack). Texture::Builtin decodes each once with the
engine's BLP reader from memory: BlpParse (0x005A83B0) is BlpOpen
without the file read, and BlpReset never frees the file buffer. The
reader moves to Texture::BlpReader, shared with the map overlays.
Texture loads of the same paths, such as the option label's inline
icons, get the same images.

The reader refuses a DXT5 file. BlpDecodeLevel (0x005A7F00) converts a
DXT level through the matrix InitConvertMatrix (0x005A4FC0) fills, and
that matrix has DXT1 and DXT3 converters to BGRA8888 but none for DXT5:
BlpDecodeLevel would return 1 with its SMemAlloc buffer unwritten. No
shipped cursor is DXT5; the check keeps a later embedded DXT5 file, or a
DXT5 map overlay, from being read as heap memory.

Game paths now compare through one rule, Common::SamePath (any case,
either slash), and the embedded manifests through Embed::FindFile. The
embedded addons, the bindings splice and sound muting each had their own
copy of the rule; they and Texture::Builtin now share it.

The option's header, label and tooltip are translated for every client
locale, in Blizzard's own terms for each (NSC, PNJ, 物体, 物件, ...).

Release Win32 build is clean. In game, only the soft-interact quest
icon was checked so far.
2026-11-04 02:36:18 -06:00
MrbcatandBrues b3e8d92b03 feat(localization): translate the addon options panel into zhCN (#126)
* feat(localization): translate the addon options panel into zhCN

A Chinese client kept the English strings for ClassicAPI's own options:
the AddOn Options window title and its game-menu button, every page
name, header, control label and tooltip, and the AoE Loot binding name,
which zhCN only had as a commented-out line. The generic strings enUS
gained with those pages were missing from zhCN too: FOCUS_TOKEN_NOT_FOUND,
LUA_ERROR, RELOADUI, PLAYER_LIST_DELIMITER, SYMBOLIC_NEGATIVE_NUMBER,
SYMBOLIC_POSITIVE_NUMBER and the money texture formats.

The locale files load enUS first and the file that matches GetLocale()
overrides it, so English clients are unchanged and only zhCN is filled
in. Terminology follows the client's own: 插件, 界面, 姓名板, 动作条 and
动作瞄准 for action targeting.

The Release Win32 build embeds the new zhCN.lua in the !!!ClassicAPI
pack (the packed strings were checked). Not tested in-game.

* fix(localization): use Blizzard's zhCN terms in the options panel

The backpack options said 背包, which zhCN uses for bags in general,
so "ignore backpack" read as "ignore bags" and its tooltip contradicted
itself. Use 行囊 for bag 0, as BACKPACK_TOOLTIP and
BINDING_NAME_TOGGLEBACKPACK do. Junk is 垃圾 (BAG_FILTER_JUNK), and
helpful spells are 有益法术, as in the self-cast option tooltips.

Drop the coin-texture and signed-number format strings: they were
byte-for-byte copies of enUS.lua, which always loads first.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-11-03 21:29:40 -06:00
Brues 0a3f8324ea fix(frame): stop a re-anchor during layout from freeing the point being read
Crash #132 at 0x00768323 (FUN_REGION_GET_RECT reading [5+0x3C]): Show lays
a frame out before its children leave their layout deferral, so its
OnSizeChanged ran; the ScrollBox handler read a region's size, and laying
that region out reached an anchor point on a still-deferred child. The
point getter (0x007A2F90 / 0x007A3070) ends the relative's deferral with
FUN_REGION_LAYOUT_REALIZE(0), which ran the child's OnSizeChanged; that
script re-anchored the region, freeing the point, and the getter then read
the point again (0x007A2FC5) from freed heap.

The getters now end the deferral themselves with the point marked busy.
The point's deleting destructor (0x00767D80, the only free path) flags a
busy point; a flagged getter returns the layout's undefined value without
touching the point, and the point walk (0x007671A0 / 0x007671F0) is run
again with the current anchors, up to ten times. Otherwise the engine's
own getter reads the value, with the deferred bit hidden so a script that
hid the relative again cannot start a second resolve.

No hooks: the three getters/destructor are patched in the relative-point
vtable (0x0081C44C, their only reference), and the six edge resolvers'
calls to the walks are redirected. Adds Common::RedirectSlot for the
vtable entries.
2026-11-03 20:47:46 -06:00
6f3a8ffc1d feat(texture): add static creature portraits by display ID (#123)
* feat(texture): add static creature portraits by display ID

* docs(api): document static creature portrait functions

* Update API.md

* refactor(model): bake display-ID portraits on the engine's own path

SetPortraitTextureFromCreatureDisplayID now replays 1.12.1's unit
portrait bake, BakePortrait (0x00524F60), call for call on a display
model of its own, instead of driving a hidden PlayerModel through Lua.

The display model is built the way AttachDisplayModel (0x00505A70)
builds one, without a frame: M2CreateScene (0x00706E10), then
CreateModelFromPath (0x00707350) on the CreatureModelData path, then
ApplyCreatureDisplay (0x004797B0). A character display is dressed
through the engine compositor with the same code that dresses
PlayerModel:SetDisplayInfo, now shared as Model::DisplayInfo::
CreateDresser / PumpDresser / DestroyDresser.

The bake's own gate, IsReady(model, 0, 1) (0x00710450), only passes for
a model that something has drawn: a BLP texture gets its device texture
only when GetTextureDeviceObject (0x0044ACF0) is asked with wait set.
The shared M2 still loads on its own, so the gate here is
IsLoaded(model, 0, 1) (0x007103D0) plus the dress, and the bake's
IsReady(copy, 1, 1) makes the device textures, as it does for the copy
of a unit's model.

The bake itself is the engine's sequence: copy into a fresh scene,
DetachAllItemModels, camera 0, PlayAnimation, save projection, view,
viewport and fog (GxMasterEnable 0x0058A210 / 0x0058A1E0), the 64x64
DDC box in the bake's own float order, CameraSetDeviceTransforms, clear
colour 0, ClearDevice(3), PortraitLighting, both scene passes, read back
through 0x00589CF0, clear, cut the alpha mask in (0x005258A0), restore.
It runs at the head of the UI render callback, the same point as an
OnUpdate script that calls SetPortraitTexture, behind the bake's device
gate (0x0058A260 window active, 0x0058A280 device alive).

Each display ID owns one callback texture (TextureCreateWithCallback,
which makes its device texture at creation). It is bound with SetImage
(0x00770300) at call time and filled in place with GxTexMarkRectDirty
(0x0058ACD0), the bake's own path for re-baking a cached portrait. A
region the caller re-points before the bake finishes keeps what it was
given, so no region is tracked: the request map, the region-destruction
subscription and ClassicAPI_CancelPortraitTextureRequest are gone. The
function returns nothing, as retail's does.

Portraits are kept until logout, the lifetime of the engine's display-ID
portrait cache (cleared in ShutdownGame). A display with no portrait
camera is done once and stays transparent.

Offsets.h: the portrait block is renamed to engine names with calling
conventions and sources; the duplicates of FUN_M2SCENE_ANIMATE,
FUN_M2MODEL_SET_ANIMATED and GetCameraById are removed, as are the
made-up draw-flag and scene-count fields and the raw device-vtable
slots. Model::Camera::CameraById is exposed instead of being copied.

---------

Co-authored-by: z1xel <ramirezthiago@71gmail.com>
Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-11-03 20:00:22 -06:00
Brues 3862408e1a docs(readme): list the new base-library functions
The Lua row gains debuglocals, debugstack's coroutine argument,
difftime, gmatch, math.cosh/sinh/tanh, newproxy, scrub, string.byte and
strbyte ranges, string.format's two-digit %n$, %0 in string.gsub and
table.removemulti. The Lua errors section says the window shows each
error's local variables.
2026-11-03 15:36:32 -06:00
Brues 12a81f7f89 feat(baselib): debugstack takes a coroutine
debugstack([thread,] [start [, count1 [, count2]]]) returns the stack
of a coroutine when one is passed first, with start defaulting to 0
(the coroutine's innermost level), as 4.3.4's Script_debugstack does.

1.12.1's debugstack (0x703760) has no thread argument. A thread fails
its lua_isnumber and lua_isstring checks, so it returns the thread
itself, and msg .. debugstack(co) raises "attempt to concatenate a
thread value" in the coroutine error paths of WeakAuras, Questie's
ThreadLib, MRT and Zygor.

The engine function still builds the text, so its line format and its
12/10-level head and tail windows are unchanged, which keeps addons
that parse debugstack() for their folder working. It reads levels
through six calls on the state it runs on: lua_getstack (0x6FBAA0) at
0x70383F, 0x70386E, 0x703896, 0x7038AD and 0x703998, and
lua_getinfo (0x6FBC70) at 0x7038CD. Those calls are redirected to
read from the state the new global names for the call: the thread, or
the calling state. The engine function has no callers of its own, so
the global is its only way in and sets that state for every call; an
error part way cannot leave a thread behind for the next call.

The global removes the thread argument, inserts 0 as start when none
is given, and calls the engine function directly in its own frame, so
levels without a thread count exactly as before.
2026-11-03 15:33:30 -06:00
Brues 05fa5845b7 feat(baselib): debuglocals, and the error window shows locals
debuglocals([level [, skipFunctionsAndUserdata]]) returns the locals and
then the upvalues of a call level as text, one name=value line each.

It runs only while an error handler runs, as in 4.3.4. 1.12.1's error
function sets no flag for that, but while a handler runs that function
(FUN_FRAMESCRIPT_CALL_ERROR_HANDLER) is a C closure level on the stack;
ErrorCallstack's search for it moves into a header so both modules use
it. level counts as lua_getstack and debugstack do.

Each local comes from lua_getlocal (0x6FBB20, fastcall L/ar + n), then
each upvalue of the level's function (lua_getinfo "f") from
lua_getupvalue (0x6F4660, fastcall L/funcindex + n). Values are
formatted as 4.3.4's FrameScript_PackVariable does, with retail's
spacing (probed: n=7, s="hi", t=<table>{ / k=1 / }): a frame table shows
its name, read from t[0] as FrameScript_GetObject does; a table's fields
show one space in at the top level only; a function shows where it is
defined (lua_getinfo ">nS"). The text stops at 4095 bytes. The second
argument, which retail's error handler passes as true, leaves out
function and userdata values.

Where 4.3.4 would fail inside the handler, this does not: a number key
outside int range is formatted from a copy, not converted in place
(which breaks lua_next), and a key that is not a number or string prints
as its type.

Retail also lists (*temporary) lines, 5.1's names for a level's stack
slots past its locals, including a C level's arguments. 1.12.1's
lua_getlocal is 5.0's and names declared locals only; those slots are
compiler registers that 5.0 and 5.1 allocate differently, so they are
not imitated.

The error window takes the locals as retail's GetErrorData does,
debuglocals(level, true) at the stack's level, and shows them under
Locals ("<none>" when there are none).

LuaCAPI.md had lua_pushupvalues, lua_getupvalue and aux_upvalue one row
off; corrected.
2026-11-03 15:04:55 -06:00
Brues 6ed0edc947 feat(baselib): gmatch, table.removemulti, math hyperbolics, difftime, newproxy, scrub
The base-library names that 1.12.1's Lua 5.0 and its compat.lua do not
have:

- gmatch: the global alias of string.gmatch (5.0's str_gfind,
  0x7FCFA0), set by value like strmatch and strrev.
- table.removemulti(t [, pos [, count]]): removes count elements from
  pos, shifts the rest down with lua_rawgeti/lua_rawseti and returns the
  removed elements. 5.0 keeps the length apart from the keys, so like
  the engine's table.remove (0x7FB770) it records the new length with
  luaL_setn (0x6F4EA0).
- math.cosh, math.sinh, math.tanh: luaL_checknumber (0x6F4C80) and the
  C function.
- difftime(t2 [, t1]): C difftime over the two times, next to the
  engine's date and time globals.
- newproxy([false | true | proxy]): an empty userdata from
  lua_newuserdata. The closure's upvalue is a weak table (its own
  metatable, __mode "kv") that marks the metatables newproxy(true)
  makes, so only those can be shared.
- scrub(...): replaces each argument that is not a boolean, number or
  string with nil, in place with lua_replace (0x6F32B0).

All are registered on both Lua states.

Game::Lua gains RawSetI (lua_rawseti, 0x6F3F60), Replace, CheckLString
(luaL_checklstring, 0x6F4BE0), CheckNumber and OptNumber (luaL_optnumber,
0x6F4CD0); string.byte now uses them instead of local typedefs.

issecure, issecurevariable and forceinsecure are left out. 1.12.1 has
no taint, so they could only return constants, and a constant
"secure" from issecurevariable makes AceHook-3.0 refuse every plain
hook.
2026-11-03 14:23:25 -06:00
Brues 1645e6b43c feat(baselib): string.byte returns a range of byte codes
1.12.1's str_byte (0x7FC210) is Lua 5.0's: it reads only the start
position and pushes one code, so string.byte(s, 1, -1) silently returns
the first byte alone.

string.byte and the strbyte global now take (s [, i [, j]]) and push the
codes of bytes i..j, with j defaulting to i. Negative positions count
from the end and the range is clamped to the string. The arguments are
read with the engine's luaL_checklstring (0x6F4BE0) and luaL_optnumber
(0x6F4CD0), and positions truncate toward zero as the engine's str_byte
and str_sub do, so a call without j returns exactly what it did before.

Each code takes a stack slot, reserved with lua_checkstack (0x6F2F30).
The engine refuses more than 2048 slots, so a range longer than about
2000 bytes raises "stack overflow (string slice too long)".

compat.lua set strbyte from the old string.byte when the state opened,
so strbyte is re-aliased to the new table entry.
2026-11-03 14:00:10 -06:00
Brues efcdc54a50 feat(baselib): string.gsub takes 5.1 string and table replacements
1.12.1's str_gsub (0x7FD0E0) is Lua 5.0's. Its replacement argument
differs from 5.1 in four ways: a table is rejected ("string or function
expected"); in a replacement string, %0, and %1 when the pattern has no
captures, raise "invalid capture index" (add_s checks every %n with
check_capture, 0x7FCE20); a function that returns nil or false deletes
the match instead of keeping it; and one that returns a table deletes
it too instead of raising an error.

The first two only ever raised errors, so the 5.1 behavior cannot break
an existing addon. The function rules can: SuperAPI's
CombatText_AddMessage returns nil to delete the player's own " [0x...]"
GUID from heal text. So function replacements keep 1.12.1's behavior,
and only string and table replacements change. A scan of every gsub
call in the installed addons and the stock FrameXML found no other code
that depends on the old string or function results.

str_gsub's match loop, anchor, count and buffer stay the engine's. Two
parts are replaced:

- The 60-byte replacement-type gate at 0x7FD15E (lua_gettop / isstring /
  lua_type == function, then luaL_argerror) becomes a call to a
  __fastcall check with ECX = L that accepts a number, string, function
  or table and raises "string/function/table expected" otherwise.
- The one call to add_s (0x7FD203 -> 0x7FD2A0, __fastcall ms/b + s/e on
  the stack, ret 8) goes to a function with the same signature. A
  function replacement calls the engine's add_s unchanged. A string or
  number gets 5.1's add_s, and a table gets 5.1's lookup: the first
  capture or whole match as the key, a nil or false value keeps the
  match, and any other non-string value raises "invalid replacement
  value". Both use the engine's push_onecapture (0x7FCF40, plus 5.1's
  whole-match case for index 0 with no captures), luaL_addlstring
  (0x6F51F0) and luaL_addvalue (0x6F5270).

Both patches check the original bytes or call target and are skipped
when they differ.

The table-replacement shim in StringLib is removed. It wrapped the
pattern in an outer capture so a closure could return the whole match,
and deleted the match for a missing key when the pattern had a
back-reference. string.gsub and gsub are the engine's function again.
2026-11-03 14:00:04 -06:00
Brues 6a24271cd1 feat(baselib): two-digit %n$ argument numbers in string.format
1.12.1's str_format (0x7FD3D0) only reads a one-digit argument number:
isdigit(p[0]) && p[1] == '$'. In "%10$s" the "10" is read as a width and
the '$' as the conversion, which raises "invalid option in `format'".
Combat log strings such as ACTION_SPELL_PERIODIC_LEECH_RESULT,
"(%10$s %8$s Gained)", cannot be formatted.

Replace the engine's 18-byte one-digit branch at 0x7FD4AC with a call to
a naked thunk that sets the argument number ([ebp-8]) and the flags scan
start (EBX) for both "n$" and "nn$". EAX/ECX/EDX are dead at the site.
The engine still tests the first digit with its own isdigit, increments
the argument after the site, and does every conversion, so string.format,
format and the C callers of str_format all get the change. The patch
checks the original bytes and is skipped when they differ.
2026-11-03 13:07:32 -06:00
MrBCatandBrues a7ce7555f0 fix(softinteract): anyinteract yields when the target is out of reach (#121)
* fix(softinteract): anyinteract yields when the target is out of reach

GetAny treated Reach::Out — the cursor's Unable form — as a usable
target, so with a target too far away the Interact Key pressed the inert
target instead of the nearest object it could interact with.

Prefer the target only while the cursor says it can be used now
(Reach::Now), and fall back to softinteract otherwise. A target behind
the camera still wins while it is in reach: the cursor verdict does not
look at facing.

* docs(api): anyinteract needs the target to be in reach now

The token section said a target that is too far away still counts, which
the implementation no longer does.

* fix(softinteract): anyinteract keeps an out-of-reach target when nothing is picked

Retail 12.1.5, targeting an NPC that is out of reach: facing away from
everything (softinteract nil), anyinteract is the target; facing a nearer
NPC, it is that NPC. The previous change returned 0 in the first case,
so the Interact Key lost the engine's own out-of-reach handling on the
target (the "need to be closer" error, or the click-to-move walk).

GetAny now reads the target's cursor verdict once: in reach wins, then
softinteract, then the target while it is interactable but out of reach.

* feat(interact): honor looseTargeting in C_PlayerInteractionManager.InteractUnit

On retail the Interact Key on a nearer NPC opens its dialog while a
farther unit stays targeted; with no target it targets the NPC. The key
calls InteractUnit("anyinteract") with looseTargeting at its default,
true, which ClassicAPI ignored, so the right-click's select replaced the
target.

FUN_ON_SPRITE_RIGHT_CLICK (0x00492820) is the active-player gate, the
select (FUN_SET_SELECTION_BY_GUID, 0x00493540), then the object's
right-click virtual (vtable +0x60, call at 0x00492881) with
FUN_GAMEUI_IS_KEY_DOWN(0). The select stores only units, so only a unit
other than the current target would move it. With looseTargeting and a
target, that one case runs the gate and the virtual without the select;
every other case still calls the engine function, which nampower also
detours for its right-click guards. The global InteractUnit keeps
targeting.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-11-03 12:39:54 -06:00
Brues 04790cb6c1 feat(options): name the page scroll bars for skins
Each options page's MinimalScrollBar is now ClassicAPIOptionsScrollBarN,
numbered like the ClassicAPIOptionsControlN controls, so a skin can find
the scroll bars the same way it finds the controls.
2026-11-03 00:54:42 -06:00
Brues e7ecae56da feat(options): key binding rows for ClassicAPI's bindings
The Interact Key page gets rows for Interact With Target and Interact
With Mouseover, and Bags and Items gets AoE Loot under a Loot header.
A row is retail's settings-page binding row: the binding's name, then a
button for each of its two keys. Left click a button and press a key,
mouse button 3-5 or the wheel to bind it; Escape cancels; right click
unbinds that key. The tooltip on a bound key and the page's output line
use retail's strings, added to every locale with Blizzard's translations.

The binding is 1.12's Key Bindings window's (Blizzard_BindingUI): the
same ALT-CTRL-SHIFT chord order, the same skipped modifier keys, the same
KEY_UNBOUND_ERROR check for an action that loses its last key, and the
same put-back when SetBinding refuses a key. A change saves at once with
SaveBindings(GetCurrentBindingSet()), so it lands in the account or
character set in use, as every other control on these pages writes at
once.

While a button listens, a full-screen button on FULLSCREEN_DIALOG takes
keys, clicks and the wheel, as retail's KeybindListener and its input
blocker do. A left or right click on it cancels, and so does hiding the
page.
2026-11-03 00:54:35 -06:00
Brues 65c6b0b271 feat(action): spell search, slot item and #showtooltip action queries
C_ActionBar.FindSpellActionButtons, HasSpellActionButtons and
IsOnBarOrSpecialBar find a spell on the bars. A slot matches on the
spell ID stored in VAR_ACTION_TABLE under the spell tag, the same test
4.3.4's PutActionInSlot makes, so a macro or item that casts the spell
does not count and a rank matches only itself. A name resolves through
the engine's spellbook resolver. IsOnBarOrSpecialBar also reads the
shapeshift bar's spell array (pointer at 0x00B71108, count at
0x00B71104, as Script_GetShapeshiftFormInfo 0x004B45C0 reads them) and
the pet bar's spell entries (types 1-5, spell ID in the low 16 bits, as
Script_GetPetActionInfo 0x004BDC50 reads them, gated on the pet GUID).
Enum.ActionBarSet is registered; all 120 slots are its Mkb set.

IsStackableAction (global, 1/nil) and C_ActionBar.IsStackableAction
(bool) answer 4.3.4's IsStackableAucItem: the slot's item has a max stack
above 1. C_ActionBar.GetItemActionOnEquipSpellID returns the item's
first spell with trigger 1 (on equip). The item is the item-by-ID
action's, or the one a macro's #showtooltip / #show resolved to, as
4.3.4's CGActionBar::GetItem returns it. Both peek the item cache and
never query it.

C_ActionBar.IsMacroActionWithShowTooltip parses the macro's body with
the parse Macro::ShowTooltip hands the tooltip over on, so it answers
while that module yields or a publisher owns the macro.
2026-11-03 00:37:16 -06:00
Brues 5f94fb98bd feat(action): C_ActionBar.GetSpell
C_ActionBar.GetSpell(actionID) returns the spell an action-bar slot
casts, or 0. It is the engine's own slot resolver (0x004E5A50), which
the cooldown, usable and range readers already go through: a spell
action is its spell, a macro is its cached primary spell (+0x564, the
one #showtooltip sets), and an item-by-ID action is the first on-use
spell in its item cache record. An empty slot, a slot outside 1..120,
an equipment set or a macro whose macro is gone gives 0. The spellbook
flag the resolver also hands back is not part of the answer.
2026-11-03 00:16:02 -06:00
Brues 426f6b6ec9 fix(container): free slots count the bank and use the engine's counter
GetContainerNumFreeSlots and GetContainerFreeSlots now take the main bank
(-1) and the bank bags (5..10) while a banker is open. The main bank is
gated on the banker GUID (0x00BDD038); bank bags get the gate from the
engine's container-GUID getter (0x004F93E0), which answers 0 for them
while the bank is closed.

A bag's empty slots are counted by the engine's own CountFreeSlots
(0x00622910, __thiscall on the bag's inventory list), and its slot count
comes from that live list instead of the item record. The backpack and
main bank are ranges of the player's list, walked slot by slot. Nothing
walks PackBagSlot per slot any more, so the Lua stack is left alone.

A container that is not there (keyring, empty bag slot, closed bank) now
returns only 0, leaving bagFamily nil.

The bag view SortBags kept for itself moves to Container::Bag so both
modules share it, and Item::Location::EquippedBagInventory becomes
BagInventory (1..10) beside a new BagContainer.

C_Item.GetItemData's bagFamily now goes through BitmaskForRecord, so a
bag whose family field is empty reports the same family there as it does
from GetItemFamily (a Soul Pouch was 0 there, 0x4 here).
2026-11-02 21:03:01 -06:00
Brues 3a4d291748 fix(link): split links with string.split captured at load
LinkUtil.SplitLinkData and SplitLinkOptions looked up string.split on
every call. BigWigs (pepopo978 fork) defines a table-returning
string:split in Plugins/SpellRequests.lua, which replaces the global, so
with it loaded every custom link type resolved to a table, no handler
matched, and SetItemRef rejected the link as unknown.

string.split is registered in C by the DLL before any addon loads, so a
file-local captured when LinkUtil.lua loads always holds the real one.

Fixes brues-code/pfUI#73
2026-11-02 16:23:36 -06:00
Brues 1cdd46958f feat(combatlog): 4.3.4 combat log lines in retail-named log files
While combat logging is on, each combat log entry is also written as one
CSV line in 4.3.4's PackEvent layout: the subevent, source and dest
(GUID, quoted name or nil, flags as hex), the spell prefix, then the
suffix blocks the entry carries. Fields are written as 1 or nil, damage
values as numbers, and there is no hideCaster, isOffHand or alternate
power type. The line is written from Queue before the events fire, so
it is written even when no frame listens.

The switch is LoggingCombat's own flag (0x00B4FDB8), so /combatlog and
LoggingCombat() control both files. Each time the flag turns on, a new
file starts, named as retail names it:
Logs\WoWCombatLog-MMDDYY_HHMMSS.txt, the local time logging started.
The file is a Storm log opened as LoggingCombat opens its own:
SLogCreate (0x0065A0C0) with flag 4 (append). Lines go through SLogWrite
(0x0065ACE0), which puts the "M/D HH:MM:SS.mmm  " stamp in front.

The flag is read once a frame on FrameTick and before each line. When it
turns off, SLogClose (0x00659EC0) writes the buffered lines and closes
the file. This also covers logout: the chat teardown in
CGGameUI::ShutdownGame (0x00498700, its only caller) clears the flag,
and FrameTick runs on the glue screen too. Storm closes what is still
open at exit (0x0065A4B0). LoggingCombat itself is not hooked: it is a
jmp into the enable code the chat log shares, and other DLLs add their
own logs to it.

1.12's Logs\WoWCombatLog.txt keeps its chat-text lines, written by
0x0049B1E8, for the log readers that parse them.
2026-11-02 15:44:06 -06:00
Brues 72f0e5d98f docs(action): range and usable events move to the Events section 2026-11-02 14:06:41 -06:00
Brues ceb6aaf46b feat(action): action range and usable events
ACTION_RANGE_CHECK_UPDATE(slot, isInRange, checksRange) and
C_ActionBar.EnableActionRangeCheck(slot, enable). Enabled slots are
checked on each world tick while a frame is registered for the event,
with IsActionInRange's own answer (Action::Range::Answer, the macro
unit redirect included), and fire on change. Enabling is counted per
slot, and each enable makes the slot's next check fire, because retail
buttons take their first state from the event. A new Lua state starts
with no slot enabled.

ACTION_USABLE_CHANGED(changes) carries { slot, usable, noMana } for
each slot that changed. The engine's bulk refresh 0x004E5C00 already
compares each slot's pair against the caches IsUsableAction reads
(0x00BC6B60 / 0x00BC67A0). Its per-slot call at 0x004E5C15 is
redirected to record the slots whose pair differs, and its
ACTIONBAR_UPDATE_USABLE signal at 0x004E5C53 to send that event
unchanged and then the new one. No hook.
2026-11-02 14:03:27 -06:00
Brues 84c936faa4 fix(compat): hooks wrap the engine's body when wow_turbo got there first
wow_turbo detours about 380 engine functions to its own reimplementations
from its DllMain. It yields any function whose prologue another mod has
already patched, but ClassicAPI installs from the Load export, which
VanillaFixes calls after every DllMain. So wow_turbo always patches first,
and MinHook copies its jmp into our trampoline: the hook then calls the
reimplementation, not the engine's body. Everything that lives in that body
was lost. The script runners (0x00704D50, 0x00704F10) never reached the
pcall redirects at 0x00704E79 / 0x00705199, so every handler saw self ==
nil. The text builder (0x005CDC20) calls its own emitter, so the inline
texture emitter hook (0x005CCBE0) and the word-wrap redirects at
0x005CDDD3 / 0x005CDE23 never ran.

Before each HookAutoRegister hook is created, a prologue that is a jmp
rel32 into wow_turbo.dll gets its five stock bytes back. The bytes come from
WoW.exe on disk, found through the loaded image's section table. Then the
hook wraps the engine's body. wow_turbo's own rule produces the same state
when it loads after a mod that hooked first. It keeps its original in
place, logs the overwrite and does not re-patch these entries. Release
builds reclaim six: the two runners, the text builder and emitter,
GxSetViewport (0x0058AF60) and the selection-circle update (0x00614A90).
Nothing changes when wow_turbo is not loaded.
2026-11-02 13:00:50 -06:00
Brues 957d66af49 fix(addons): memory usage walks the live objects, as luaC_sizeall does
UpdateAddOnMemoryUsage summed Gc::Tag::SizeOf over the keys of the tag
map. That is only safe while every free reaches luaC_freeobj (0x006F7260),
whose co-hook erases the key. wow_turbo replaces luaC_collectgarbage
(0x006F7340) with a parallel sweep that frees strings, tables, closures,
userdata and upvalues itself and sends only threads and protos through
freeobj. Dead keys stayed in the map, and the recount read freed blocks:
crash 132.

The recount now walks the lists the engine sweeps: rootgc (G+0x10),
rootudata (G+0x14) and every string-table bucket (G+0x04, size G+0x0C),
and looks up the tag of each live object. 3.3.5's luaC_sizeall walks the
same lists. A create with no context word now erases its address's entry,
so a reused address never carries a dead object's tag, whoever freed it.
Dead entries a foreign sweep leaves are never read, and the pool's address
reuse bounds them. _classicapi_LuaHeapAudit uses the same walk.

Fixes #120
2026-11-02 13:00:50 -06:00
Brues 3849b7513b feat(statusbar): the standard fill moves the bar texture's rect
1.12's CSimpleStatusBar::OnFrameUpdate (0x007833C0) draws the fill by
cropping. InstallBarTexture (0x007831F0) sets the texture's
SetTexCoordModifiesRect flag (+0x124), and the update writes the filled
part into the coordinates. The crop shrinks the drawn quad but leaves the
texture's rect at the full bar, so a region anchored to
GetStatusBarTexture() stays on the bar's far edge. Reverse, center,
rotated and tiled bars already moved the texture's points.

The OnFrameUpdate hook now replaces the engine's update for every bar. It
runs the base frame update (0x0076B2C0), clears the crop flag, and moves
the texture's four points in from the bar's edges with CLayoutFrame
SetPoint and doResize, as 4.3.4's OnLayerUpdate does. The fraction comes
from the bar's fill-fraction virtual (+0x98), so SetValue, the ease and
SetTimerDuration all move the rect. doResize queues the texture for the
layout pass before the draw, so anchored regions follow in the same frame.
An empty fill keeps a zero-width rect on the start edge (CalculateRect
0x767A20 has no size test), so its anchors still resolve.

The crop path and the code that handed a bar back to it are removed. A
standard vertical bar now shows the bottom part of its image.
2026-11-02 11:25:46 -06:00
Brues 1cdd443e53 refactor(text): inline icons take their line's fade when its colour changes
The icon textures have no frame, so the frame alpha fold (0x0077FAC0)
skips them and their only alpha is the one copied from their fontstring's
colour (colors[0], OFF_FONTSTRING_COLOR_ARRAY). The tick read that colour
for every fontstring with icons, every frame, and re-coloured the icons
when it changed.

Every change of that colour ends in the fontstring's region slot 8,
CSimpleFontString::OnColorChanged (0x00772180, `ret 4`): SetVertexColor
(0x0077F750) calls it after storing a colour, which is how the chat fader
and SetTextColor reach it, and the frame alpha setter (0x0076A690) calls it
on each region of the frame. It folds the colour (0x0077FAC0) before it
hands it to the built string, so the value is final when it returns.

A co-hook on it now copies the colour onto the line's icons in the same
call. No other loaded DLL refers to that address. The batch reads a
texture's colour through a pointer, so no layer rebuild is needed. The glue
value-follow (FadedColor) is unchanged. The tick only deletes orphaned
textures now; the per-fontstring applied-colour stamp is gone.
2026-11-02 10:26:26 -06:00
Brues ada33825ad refactor(text): inline icons are placed at build and at move only
Inline icons were placed on three paths: the RebuildString refresh, the
paint flush (FUN_TEXT_PAINT co-hook), which recomputed every icon line's
placements after every paint and queued any change, and the tick, which
applied the queue. Measured over normal play, the paint flush never
supplied an icon the rebuild had missed. All it did was re-place icons
that had moved, 456 times: almost all by float noise (1e-5 px), each one
re-anchoring the icon and rebuilding the fontstring's layer; the rest by up
to 0.9 px.

That 0.9 px is a move. A fontstring whose size does not change keeps its
built string: the rect callback (0x00772D40), SetTextOffset (0x00772100)
and the animation translation only move it, through TextBlockSetStringPos
(0x0044D600) -> CGxString::SetPosition (0x005CCB10), which re-finalizes the
node origin (0x005CDF70) before it returns. The origin is floored to whole
render-target pixels, so an icon anchored to the unrounded fontstring rect
drifts off its glyphs by up to a pixel.

The icons are now placed when the string is built (the RebuildString
refresh) and after each TextBlockSetStringPos, from a co-hook on it. No
other loaded DLL refers to that address. The move lays the node out first
(FUN_TEXT_ENSURE_BUILT, as the rebuild does): a colour change can leave the
node unbuilt until the next paint, and with no built lines (+0x9C) the
origin finalize returns early with the raw normalized position in the
origin, which placed those icons at the bottom-left of the screen. The
placement now refuses an unbuilt node. Only nodes with icon records are
laid out early.

Removed: the paint flush's placement queue, the pool's queue and dirty
flag, and the tick's apply. The pool has one entry point, Apply, which
skips an icon set equal to the one applied. The paint flush keeps its
other jobs (the stuck-blockless re-dirty, the stale-record guard and the
baked-alpha mirror); the tick keeps the orphan deletes and the fade mirror.
2026-11-02 10:15:54 -06:00
Brues dd584703a2 refactor(text): place inline icons once, at scale 1
An inline icon texture was given its fontstring's layout scale (layout
slot 0x10, as AddRegionToLayer gives a region its frame's), its anchor
offsets were divided by that same scale, and every tick read each drawn
icon's resolved width back and folded the error into a per-icon
correction, re-placing the icon until it settled within 0.5%.

The textures have no frame, so that machinery has nothing to correct. The
layout constructor (0x00767680) sets the scale (layout +0x58, region +0x7C)
to 1.0 and nothing else changes it without a parent. RelativePointGetX/Y
(0x007A2F90 / 0x007A3070) place a point at the positioned region's own
scale times the stored offset plus the relative edge, so with scale 1 the
fontstring-relative edges land exactly. The scale copy and the divide
cancelled, and the correction stayed at 1.

The icon is now placed with two SetPoints at the raw offsets and the
layout realize (0x00768060, SetDeferResize(0), which resizes at once when
a resize is pending). Removed: the scale copy, the correction and the
per-tick rect readback, and VTBL_LAYOUT_SET_LAYOUT_SCALE, which named the
same slot as VTBL_LAYOUT_SET_SCALE.
2026-11-02 10:04:13 -06:00
Brues 5911298acd fix(text): inline icons are drawn by their line, as 4.3.4 does
Inline icons were CSimpleTextures registered on the fontstring's parent
frame, with their visibility copied from the line once per tick, after the
draw. Any line that hid kept its icons for one more frame; once chat lines
moved with their text, a line scrolled off the top flashed its icons above
the chat frame.

4.3.4's CSimpleEmbeddedTexture has no frame, and the fontstring draws it:
CSimpleFontString::Draw queues the string, then QueueTextures. 1.12's
equivalent is CSimpleFontString::Emit (0x00772E50), the only caller of
AppendToBatch (0x00773080). The icon textures are now made with no frame
(SimpleRegionConstruct skips SetRegionParent for a null parent; the
frame-alpha fold 0x0077FAC0 tests the parent), anchored to the fontstring
and given its scale through layout slot 0x10, as AddRegionToLayer does. A
hook on Emit adds a line's icons to the layer batch right after its text,
and only when the text went in (the batch count at +0x4 grew), so an icon
draws exactly when its line does, in the same frame.

The batch copies each texture's handle, blend and colour count when built
(0x00772FD0) and reads vertices, texcoords and colours through pointers, so
a change to a line's icon set marks the fontstring's layer
(NotifyLayerChanged 0x0077FDF0), and moves and fades need no rebuild.

4.3.4 sets the textures up in UpdateString. RebuildString (0x007724A0) now
does the same: when its gate passes (layout flags +0x60 bit 1, `test byte
[esi+0x60],1`) it replaces the built string, so the line's icons are
dropped, the new node is laid out (FUN_TEXT_ENSURE_BUILT) and its
placements applied at once. The paint flush stays the backstop.

Removed: the per-tick visibility mirror, the freshness expiry, region
Show/Hide and re-parenting, and the SMF early apply with its
_classicapi_InlineTexEarly toggle; the rebuild refresh covers what it did,
and it rebuilt every icon line on every layout. The textures are deleted
through their vtable slot 0 (as the frame destructor deletes regions) one
tick after their fontstring dies or a reload, once the batches holding them
were rebuilt.
2026-11-02 00:53:10 -06:00
Brues a6fa06faa0 perf(smf): lines a layout keeps on screen keep their font strings
The line layout (0x00788750) shows record (position - i) in line i and sets
each line's text through ShowLine (0x00788AF0). When the position moves, by
a message at the bottom or a scroll, every line got the text of its
neighbour: a copy, a freed built string, a new measure and a new shaping.

Before a layout of a shown frame, the line entries are now turned by the
distance the position moves (the layout's record minus the scroll record
+0x348, the record line 0 shows), so each line that stays on screen is the
font string that already holds its text. The layout itself runs unchanged.
SetText (0x00771D80) returns at its SStrCmp when the text is the one the
line holds, so the line keeps its built string and measured height;
SetVertexColor (0x0077F750) skips a repeated colour; the forced Resize only
moves the built string, since the rect callback 0x00772D40 rebuilds only on
a size change. Only lines that come round get new text. Hyperlink buttons
are rebuilt from the lines after every layout, and inline textures are
anchored to their line, so both follow.

The 0x10-byte entries move whole, as the engine's own array grow 0x00789060
moves them with SMemReAlloc. Two lines get new anchors: the new line 0 goes
on the frame, then the old line 0 on the line below it, in that order so no
line is anchored to one that depends on it. Both are anchored as the layout
anchors a new line, in the frame's insert mode (InsertMode::AnchorLine, now
shared). A frame whose last layout placed no line (+0x34C = 0, a hidden
frame's layout) is laid out as before, as is a distance as large as the
lines. A wrong distance costs only the reuse: the layout still sets every
text it shows.

The layout's before-listener now receives the record it runs from.
2026-11-02 00:24:28 -06:00
Brues 045ab77508 perf(smf): one line layout per update for messages added at the bottom
The ring writer 0x00788150, AddMessage's only callee, lays the lines out
(0x00788750) after every message at the bottom, and the layout sets the text
of every line it shows. k messages in one update cost k layouts of every
shown line, and only the last is drawn.

The writer's layout call (0x00788234) is redirected. The layout is put off
when its result is known apart from line heights: the frame is shown, it had
a message before this one, and its top flag +0x350 is clear (the lines do
not reach the oldest message, and a newer message cannot make them). The
layout's first store, the scroll record +0x348 = the newest record, is made
at once, so GetCurrentScroll and the writer's next check read as before.

The put-off layout runs at the first of:
- the frame's update, between its OnUpdate script and its fader (the call
  to 0x0076B2C0 at 0x00788471). The fader, RearmLines and the link-button
  rebuild read each line's record through node+0xC, and the writer may have
  reused those records.
- the end of the top's update pass, before the second layout-queue drain
  (0x00768ED0 at 0x00765799) and the draw, so a message added by any
  OnUpdate draws in the same frame.
- RearmLines 0x00788B80 (hooked), which ScrollDown, ScrollToBottom and
  ScrollToOffset run at the bottom instead of a layout.
- GetNumLinesDisplayed (0x00793590, reads +0x34C), overridden on the method
  registry to lay out first.
- any other layout of the frame, which replaces it. Layout gains a
  before-listener for this, since a layout can run Lua.

OnMessageScrollChanged now runs once for the messages a layout covers: the
put-off layout gets the scroll record from before the first of them. The
writer is put off only when both flush redirects apply.
2026-11-02 00:14:18 -06:00
Brues ac5df0fab8 perf(smf): BackFillMessage shifts in place and skips layouts it cannot change
BackFillMessage made every older message move up one record. It copied the
record span into a vector and back, built a new Lua table for the extra
arguments, and laid the lines out again on every call. pfUI's combat-log
refilter calls it once per frame for up to 300 lines, and its chat history
up to 30 times per frame at login.

The records now rotate in place (std::rotate over the 0x18-byte records),
and the extra-argument tables follow each cycle of the rotation in the same
table, so a call makes no garbage. RemoveMessagesByPredicate shares the
rotation.

A shown frame whose lines do not reach the oldest message (+0x350, the top
flag the layout 0x00788750 sets) cannot show the new oldest one. The layout
would place the same lines again, so it is skipped. The one thing it would
change, each laid-out node's record pointer (node+0xC, written by ShowLine
0x00788AF0), moves one record up with its message. The fader 0x00788460,
RearmLines 0x00788B80 and RebuildLinkButtons 0x00788C00 read records only
through that pointer, for nodes 0..+0x34C-1. Clear leaves +0x350 at 0 on an
empty frame, so the skip also needs existing messages. An empty or hidden
frame is laid out as before.
2026-11-01 23:52:22 -06:00
Brues 48822978c6 feat(statusbar): ExponentialEaseOut interpolation
bar:SetValue(value, interpolation) and SetMinMaxValues(min, max,
interpolation) take Enum.StatusBarInterpolation. With
ExponentialEaseOut the fill eases from what it showed to the new value;
GetInterpolatedValue, IsInterpolating and SetToTargetValue read and end
the ease, and SetTimerDuration's interpolation argument now chases the
timer the same way. The curve was measured in a retail 12.1.5 client
at 77 and 30 frames per second and fits to under 1%: each frame closes
the gap in the fill FRACTION by exp(-18 * elapsed), whatever the range,
and the frame whose gap before its step is under 0.001 snaps to the
target. The same probe on 1.12 matches: k = 18.0, a full-bar ease done
in 0.38 s against retail's 0.39.

SetValue stores the target at once (GetValue returns it, OnValueChanged
runs once, with it); a new eased value goes on from the shown fill, and
an Immediate one, or SetToTargetValue, snaps. SetMinMaxValues with the
ease keeps the fraction shown and eases to the new one. A hidden bar
does not ease. Only a target that held still since the last frame may
snap: an eased timer starts at a near-zero gap, and retail chases it
until the timer ends.

The ease lives where the timer does, so StatusBar::Timer becomes
StatusBar::Display: one state per bar holding the timer, the ease and
the fraction drawn. The co-hook on the bar's GetFillFraction virtual
(0x783380) answers that fraction, so the ease keeps 1.12's texture crop
and StatusBar::Fill's styles. Advance runs at the head of
CSimpleStatusBar::OnFrameUpdate (0x7833C0) for shown bars and now takes
the pass's elapsed, which is the step retail takes.

SetValue and SetMinMaxValues stay the engine's Lua methods (0x78F690,
0x78F4B0, read from the method table at 0x87B010), registered over by
wrappers that read the interpolation argument and the fraction shown,
call the engine method for its checks, errors and setter, then start or
stop the ease. Both engine methods read no argument past their own.
2026-11-01 23:34:36 -06:00
Brues f061179646 refactor(region): one region destruction signal; inline icons drop the vtable guess
Frame::RegionDestruction co-hooks SimpleRegionDestruct (0x77F6F0), the
destructor body every region ends in, and runs its listeners first. It
has exactly three callers: the base region's deleting destructor
(0x77F6C6), ~CSimpleTexture (0x76FD40, a tail JMP; its only caller is
the deleting destructor 0x76FD10) and ~CSimpleFontString (0x770E50, a
tail JMP; called by its deleting destructor 0x770E20 and by a
subclass's, 0x789320). The texture and font string vtables (0x81C718,
0x81C778) are written only by their constructor and destructor, so no
inlined destructor skips the hook. It replaces FontString::Destruction,
the font-string-only hook from the previous commit; the duration text
binding now listens here.

InlineTexturePool kept icon state keyed by font string pointer and
judged a key alive by its first word matching a vtable it had seen
painted. That guess had a hole: a destroyed font string's block goes
back to the region pool and can come back as another font string,
vtable and all, and the dead key's icons then served the new one. It
also read possibly-freed memory on every tick. Now a destroyed key
takes its entry with it at once, so the address starts clean; its icon
regions live on with their parent frame and are hidden on the next
tick, never inside the destructor that reported the death. A destroyed
icon region is dropped wherever it is held, and a live key that loses
one is placed again. The learned-vtable sets, IsLiveFontString and
IsLiveRegion are gone. The SEH latch stays, for the engine region calls
the tick makes from paint-time data.
2026-11-01 23:03:11 -06:00
Brues f8a796ae04 feat(duration): duration text bindings, Format methods, GetTotemDuration
A font string can now count down by itself. A binding from
C_DurationUtil.CreateDurationTextBinding() takes a font string
(SetFontString), a duration object (SetDuration) and a format: either
SetFormatter(formatter), which writes a NumericRuleFormatter's text for
the remaining seconds, or SetTextFormat(formatString, components), where
each "{}" takes one component's property (Enum.DurationTextBindingProperty)
through its own formatter. SetExpiredText and SetZeroDurationText give
fixed texts, SetUpdateInterval spaces the updates out, and SetEnabled /
Enable / Disable start and stop it. The getters, Copy, Assign,
SetToDefaults, UpdateFontString, GetFormattedText and the Can* checks
are there too; the color curves are not. Duration objects gain
FormatElapsedDuration, FormatRemainingDuration and FormatTotalDuration
on the same formatter. Each answer was probed in a retail 12.1.5 client,
and the same probe matches on 1.12.

A binding is a userdata over a reference-counted native object, like the
duration object and the formatter, and it keeps both of those by
reference, so a change to the duration shows at the next frame. An
enabled binding takes a reference of its own, because it must go on
updating with no Lua object left; a Game::ReloadAutoRegister disables
every binding before the Lua state goes. The text is set through
CSimpleFontString::SetText (0x771D80), only when it differs from the
font string's own text buffer (+0xF0).

The updates run at the head of the UI render root (0x764330), before
the frame pass runs any OnUpdate or draws: Tick::FrameTick gains
AutoSubscribeBefore for this. At the tail, where FrameTick and
WorldTick subscribers run, the text would draw a frame after a timer
bar's fill, which the same pass computes; the probe caught that as a
"3.0" where retail showed "2.9". Nothing is mid-draw at the head, so the
formatter's call into str_format is safe there.

A binding keeps a font string pointer, and 1.12 hands a destroyed font
string's block back to the region pool, where it can come back as
another font string. The new FontString::Destruction co-hooks
CSimpleFontString::~CSimpleFontString (0x770E50, decompiled; its
deleting destructor 0x770E20 calls it, then frees the block) and runs
its listeners first, like Frame::Destruction does for frames. The
binding drops the pointer there and writes nothing after.

GetTotemDuration(slot) now returns a duration object, as retail's does:
the totem's span from its spawn stamp to its expiry, in exact
GetTime() seconds rather than GetTotemInfo's whole seconds, or a zero
span for an empty slot, since retail's return is never nil. Each call
returns a new object.
2026-11-01 22:48:32 -06:00
Brues aff52e0ef6 feat(statusbar): timer bars, duration objects and Unit*Duration
A status bar can now fill by itself from a duration, with no Lua on each
frame. bar:SetTimerDuration(duration [, interpolation [, direction]])
takes a duration object from C_DurationUtil.CreateDuration(), and
Enum.StatusBarTimerDirection picks ElapsedTime (fills) or RemainingTime
(empties). GetTimerDuration() returns it. UnitCastingDuration(unit) and
UnitChannelDuration(unit) return the time span of a unit's cast or
channel as a duration object.

The duration object is a userdata like the NumericRuleFormatter: a
pointer to a reference-counted span (start, total, mod rate) that every
Lua object and every bar holding it own a reference to. Times are
GetTime() seconds read through Time::Clock::NowSeconds, so they agree
with GetTime() exactly. Its methods set the span from a start, an end
or both, and read the start, end, total, elapsed and remaining time,
the two percents and the started / expired / active state, in real or
base time (Enum.DurationTimeModifier). The answers were probed in a
retail 12.1.5 client and the same probe matches on 1.12.

1.12 already draws a bar's fill from a virtual, not from its stored
value: CSimpleStatusBar::OnFrameUpdate (0x7833C0) crops the bar texture
to the fraction its vtable slot +0x98 returns (0x783380,
(value - min) / (max - min), or 0 for an empty range; disassembled).
The timer co-hooks that function, so a timed bar keeps 1.12's texture
crop. StatusBar::Fill's reversed, centered, turned and tiled layouts
now take their fraction from the same virtual, so they follow a timer
too. Fill's OnFrameUpdate co-hook calls Timer::Advance first, which
marks the fill changed when the share moved and caches the share it
drew. Shown bars update on every frame; hidden bars do nothing and are
right on their first frame shown.

As in retail, the timer stores 0 for the value and the range (written
directly, so no OnValueChanged runs), SetValue leaves it running, and
SetMinMaxValues ends it: Frame::MinMaxChanged's co-hook on the range
setter (0x783270) clears the timer first. The bar keeps the duration
object, not a copy, so a change to the object shows on the next frame.
ExponentialEaseOut is accepted and draws as Immediate for now.

UnitCastingDuration and UnitChannelDuration share one per-unit lookup
with C_Spell.UnitCastingInfo / UnitChannelInfo, so they take the same
unit tokens and have the same limits. Each call returns a new snapshot;
it does not follow pushback or the end of the cast.
2026-11-01 22:28:01 -06:00
Brues aef68d5ea4 fix(nameplate): fire REMOVED and ADDED when a unit moves to another plate
The name-query callback (0x5FB86E) and the creature-cache reply (0x6046C1)
call CGUnit_C::ReleaseNamePlate (0x608A10) so the plate is rebuilt with the
name, and the next tick takes a plate again through AllocNamePlate
(0x6087F0). The free list is FIFO: release links the frame in at the tail
and alloc takes s_freeNamePlates[2], the head. So unless the list was empty,
the unit gets a different CGNamePlateFrame. The per-tick diff compared GUIDs
only. The GUID was in both snapshots, so no event fired, and an addon that
keys its state by frame kept the old, hidden frame.

A binding is now the (GUID, frame) pair. A unit on a new frame gets
NAME_PLATE_UNIT_REMOVED for the old binding, then NAME_PLATE_UNIT_ADDED for
the new one. The REMOVED pass now runs before the ADDED pass, so the old
binding's slot is free before the new one is assigned. A re-acquire that
hands back the same frame still fires nothing.

During REMOVED, GetNamePlateForUnit / GetNamePlateForGUID now return the
frame being removed before they read unit+0xE60. After a rebind, that field
already names the new frame, and the getters would have given the handler
the wrong plate.
2026-11-01 21:46:34 -06:00
Brues cc1e70a641 feat(debugtools): modern /etrace
/etrace and /eventtrace now open a backport of retail's
Blizzard_EventTrace, the load-on-demand addon ClassicAPI_EventTrace
embedded in the DLL. It replaces the old event trace frame in
ClassicAPI_DebugTools, and DebugToolsSavedVars with it; the panel saves
EventTraceSavedVars.

What differs on 1.12.1:

- RegisterAllEvents adds the frame to every event slot, so it opens the
  listener gate of each ClassicAPI event that builds its arguments only
  for a listener (UNIT_AURA_DELTA, the combat log and cast events). The
  panel registers all events only while it is shown or logging while
  hidden; otherwise it keeps PLAYER_LOGOUT, which saves its variables,
  since this client has no ADDONS_UNLOADING.
- An engine event signalled by a number with no name arrives with a nil
  event and is not logged.
- An event's table arguments are copied when logged, and the tooltip
  lists their contents. UNIT_AURA_DELTA refills the same tables on every
  fire, so a kept reference shows only the latest delta.
- No tool windows, ImGui debug tools or secret values.

The window's templates are new shared templates in !!!ClassicAPI:
ButtonFrameTemplate and PortraitFrameBaseTemplate (with
PortraitFrameMixin / TitledPanelMixin), UIPanelCloseButtonNoScripts,
PanelResizeButtonTemplate, InputBoxInstructionsTemplate,
SharedTooltipTemplate, VisibleWhilePlayingAnimGroupTemplate, and
GameTooltip_AddHighlightLine / GameTooltip_AddColoredDoubleLine. Art
this client lacks is drawn with its own textures: tooltip border
chrome, the world map magnifier, the cancel button, a turned chat
expand arrow for the resize grip, and the panel button in three slices.
The scroll bars are the 1.12 bar, whose art is wider than its frame,
so the lists leave room for it.

Retail's search box is ClassicAPISearchBoxTemplate. Turtle's FrameXML
registers its own SearchBoxTemplate first, and 1.12 keeps the first
template of a name, so the retail one takes that name only through a
TOC line marked [ExcludeLoadGameType turtle].

The EVENTTRACE_* strings and SLASH_EVENTTRACE1-4 come from Classic
Era's GlobalStrings for each client locale but koKR.
2026-11-01 21:29:44 -06:00
Brues f1843afc0f feat(addons): ExcludeLoadGameType and the turtle game type in TOC lines
A TOC file line can now end in [ExcludeLoadGameType ...] as well as
[AllowLoadGameType ...]. An unknown condition drops its line, so a
line excluded for some other game type used to be dropped here too.

Both lists may name "turtle", a ClassicAPI extension like the
_Turtle.toc flavor: it matches when Turtle::Detected() (the engine's
TURTLE_WOW_VERSION or the glue TURTLE_* globals), and "vanilla" matches
on every client. So [ExcludeLoadGameType turtle] loads a line
everywhere but Turtle.

The TOCs of the addons embedded in the DLL now go through the same
rewrite. The FUN_FILE_READ hook serves an embedded addon's file from
disk or from the DLL as before, now in ReadAddonFile, and passes a read
that succeeded to TocRewrite::Transform, which rewrites only TOCs.
2026-11-01 21:25:47 -06:00
Brues f8304c06f7 fix(xml): frames loaded from XML lay out after OnLoad
When a frame finishes loading from XML, CSimpleFrame::PostLoadXML
(0x0076A2F0) clears the loading flag and, for a visible frame, ends the
layout deferral of the frame, its title region and its registered
regions with 0x00768060(0). That call resolves a pending layout at once
(0x007680E0 with force 1), so OnSizeChanged runs before the frame's
OnLoad, and before its children, built next, run theirs. Building the
children first does not help: resolving a child ends the deferral of the
frame it anchors to and lays that frame out too (0x007A2F90).

Retail lays these frames out later, from its end-of-frame resize list.
Its EventFrame, ScrollBox and scroll bars trigger callbacks from
OnSizeChanged on the registry their OnLoad creates, so a retail window
that loads visible raised "executingEvents (a nil value)" from each of
them.

The three calls (0x0076A310, 0x0076A324, 0x0076A35B) now go to
EndLoadDeferral: it clears the deferred bit (0x02 of the layout flags
at +0x3C) the same way, and sends a pending layout (0x00768310) to the
engine's layout queue with 0x007680E0(0), the path SetPoint takes. The
queue drains on the top's update and in the interface build, after
every OnLoad of the load. A script that reads a size or an edge still
lays its frame out at once. The minimap and tooltip finalizers call the
base first and read no rect after it. Each redirect checks the call's
target first, so a site another DLL has patched keeps its code.
2026-11-01 21:25:33 -06:00
Brues 2396d44f10 fix(frame): GetWidth / GetHeight / GetSize keep 1.12's scaled size
For a region with no set size, 1.12's Script_GetWidth (0x007A1E00) and
Script_GetHeight (0x007A2030) return the rect span without dividing by
the region's layout scale. The value is the size times the effective
scale: a 160-high track at a UI scale of 0.91 answers 145.6.

dceec8b replaced both getters with the divided form. That broke vanilla
addons tuned to the scaled value. BetterCharacterPanel sets its paperdoll
column from PaperDollFrame:GetHeight() with padding tuned at one UI
scale, so the resist icons and the stat list left the frame.

- GetWidth / GetHeight / GetSize call the engine getters again. With
  ignoreRect, a region with no set size still answers 0.
- New region methods GetUnscaledWidth / GetUnscaledHeight /
  GetUnscaledSize give the size in GetTop / GetBottom units: the explicit
  size, else the rect span over OFF_REGION_EFFECTIVE_SCALE after a
  pending resize. GetRect and GetScaledRect keep using these.
- The ported Lua in !!!ClassicAPI (ScrollBox, Menu, LayoutFrame, Util)
  calls the GetUnscaled* names wherever it measures a region.

Fixes #118
2026-11-01 19:12:04 -06:00
Brues 1ee80b74e9 docs(readme): texture wrap modes, tiling and the element XML attributes
The Texture row lists the SetTexture wrap modes and the tile methods. The
XML attributes row now names the element attributes that ClassicAPI reads,
for frames, buttons, textures, font strings, status bars and edit boxes,
and intrinsic frame types.
2026-11-01 18:35:11 -06:00
Brues 932e6ed82f feat(texture): wrap modes and tiling
texture:SetTexture(file, wrapModeHorizontal, wrapModeVertical), the XML
hWrapMode / vWrapMode attributes, texture:SetHorizTile / GetHorizTile /
SetVertTile / GetVertTile and the XML horizTile / vertTile attributes.

Wrap. 1.12 fixes a texture's wrap when its file loads.
CSimpleTexture::SetTexture (0x00770200) builds the flags word with
CGxTexFlags (0x0058A980) from one wrap argument for both axes, and
TextureCreate (0x00449D90) caches the handle under the name and that
word, so a repeating copy of a file is its own shared texture. The device
reads one bit per axis (3 for U, 4 for V), repeat or clamp, so the mirror
and border modes clamp. A texture with a mode or a tile flag loads
through a co-hook on that SetTexture: the same body, with a repeat per
axis. The engine's same-file early-out (0x0044AC70) ignores flags, so the
co-hook also compares the held image's wrap (its device texture's flags
at +0x3C, or a loading BLP handle's at +0x150), and for the same file it
swaps in the other copy and keeps the pixel shader. Changing a mode or a
tile flag reloads the held file the same way. The Lua method is
registered again so it stores the wrap arguments before the engine
handler (0x0079BB40) runs: true or "REPEAT" repeats, anything else clamps.

Tiling. A tiled axis repeats, and each non-zero coordinate on it becomes
the texture's length in script units over the image's size in texels.
The script units are the engine's own coordinate push: DivideByScreenScaleX
(0x0041AE40) of aspect (0x0041AD70) x 1024 x length, over the effective
scale. The texels are the device texture's width and height (+0x24 /
+0x28): the file's size, halved only past the GPU limit and untouched by
BaseMip. The layer batch keeps a pointer to the eight coordinates
(0x00772FD0), so the count is written whenever an input changes: after
each corner store, after both native SetTexCoord forms (0x00770410,
0x007704C0), on a tile change, and after CSimpleTexture::Emit
(0x007706E0), whose device lookup loads the image. A tile change counts
against the held image before the repeating copy of the same file
replaces it, since the copy has no size until it is drawn.

A texture showing an atlas does not tile (the atlases are parts of their
files), and neither does one with SetTexCoordModifiesRect on. SetAtlas
clears modes and tiling. A tiled status bar texture takes
StatusBar::Fill's anchored layout instead of 1.12's crop, which would size
it by the count, and its fill sets no coordinates. An XML <TexCoords> that
moves a tiled axis off 0..1 logs "Invalid TexCoords value (horizTile is
on)" at error level (new Xml::Error) and falls back to the whole image.

Also corrects the AtlasData.h note on the atlas tile flags: 4 is
horizontal and 2 is vertical.
2026-11-01 18:34:36 -06:00
Brues b032dc09ac refactor(texture): shared hooks for the texture constructor and corner store
MinHook takes one hook per address. Texture::Mask hooked the
CSimpleTexture constructor (0x0076FC40) to drop its state when pool memory
is reused, and Texture::Transform hooked the corner store (0x007705B0) to
turn the quad again after each layout. Texture wrap modes and tiling need
both hooks too, so each hook now has an owner that fans out to listeners:

- Texture::Construct runs its listeners before the constructor, on the
  memory it is about to build. Mask listens.
- Texture::CornerStore runs its listeners after the store. Transform
  listens.

The store writes only the corners. The layer batch reads them through a
pointer on every draw, so nothing marks the layer changed.

The XML number parse through SStrToFloat (0x0064AAA0) moves into
Xml::FloatAttr, which NativeSetters and Transform's rotation attributes
now share.
2026-11-01 18:30:32 -06:00
Brues eb0b70bc5e feat(xml): rotation, degrees, registerForDrag and group parentArray
Four more later-client XML attributes, each applied only when present and
non-empty, after the engine has loaded the node.

- Texture `rotation` (degrees) and FontString `degrees` / `radians`
  (`radians` wins when both are given), parsed with SStrToFloat
  (FUN_SSTR_TO_FLOAT): Texture::Transform's rotation about the default
  pivot. The bodies of texture:SetRotation and fontstring:SetRotation
  move into SetTextureRotation / SetFontStringRotation, which the Lua
  methods and the Xml::TypeLoad subscribers both call.
- Frame `registerForDrag`: the names, split on spaces and commas with
  Storm's tokenizer (FUN_STORM_STR_TOKENIZE) as registerForClicks is,
  passed to Frame:RegisterForDrag itself (FUN_SCRIPT_FRAME_REGISTERFORDRAG
  0x00776D60) as its own Lua call. That function ORs LeftButton 1,
  MiddleButton 2 and RightButton 4 and stores the mask at frame+0xFC;
  there is no setter to call instead.
- AnimationGroup `parentArray`: the group is appended to region[key].
  The append moves out of Xml::ParentKey into Xml::AppendToArray, which
  frames, regions and groups now share.

Tested in game with an XML test addon: rotation="90" and degrees="90"
read back as pi/2, two groups land in parentArray in load order, and a
frame with registerForDrag="LeftButton" drags.
2026-11-01 17:25:28 -06:00
Brues 238e35ae53 feat(animation): from/to alpha, setToFinalAlpha, target keys, scale from/to
Later clients' animation attributes and the methods behind them, on the
animation port's own objects.

Alpha fromAlpha / toAlpha (SetFromAlpha / SetToAlpha / GetFromAlpha /
GetToAlpha): an absolute alpha. Each update the target's alpha becomes
from + (to - from) x progress, through Region::SetAnimAlpha, which takes
AddAnimAlpha's target rule but sets instead of adding: a frame's own
alpha through its vtable setter, a texture's or font string's vertex
alpha through FUN_REGION_GET_COLOR / FUN_FONTSTRING_SET_COLOR. Earlier
orders apply at full progress before the current order updates, so the
last write wins. Setting either end turns the mode on, an unset end is 0,
and SetChange returns to the relative change. Absolute values and the 0
default follow Blizzard's own code: it starts fades with
SetFromAlpha(region:GetAlpha()) and fades in with toAlpha="1" alone.

AnimationGroup setToFinalAlpha (SetToFinalAlpha / IsSetToFinalAlpha):
when the group finishes (Finish included), Region::KeepAnimAlpha makes
the alpha each alpha animation's target ended on the stored alpha, so the
end restores that. Stop restores the stored alpha as before.

targetKey / childKey (SetTargetKey / SetChildKey), with SetTarget,
SetTargetName, SetTargetParent and GetTarget: a key path from the
animation, where $parent steps to the group, then its region, then that
region's parent; childKey "X" is "$parent.$parent.X". The steps among the
animation objects are taken by Region::FindRegionByKey, and the rest goes
to the relativeKey resolver in Xml::Anchors, now public with a switch for
its leading-global rule. A name or key is looked up again on Play, as
4.3.4 looks up `target`; the setters also look it up at once and return
whether they found a region. GetTarget returns the group's region when
there is no target.

Scale fromScaleX / fromScaleY / toScaleX / toScaleY (SetScaleFrom /
SetScaleTo / GetScaleFrom / GetScaleTo): the scale goes from `from` to
`to`, passed to AddAnimScale as 1 - scale. SetScale sets the end, so
4.3.4's scale is the case from = 1 and its results do not change.

Tested in game with an XML test addon: childKey and targetKey resolve,
the absolute alpha and the last-write-wins rule give each order's end
value, setToFinalAlpha keeps 0.5 after the group finishes, a group without
it restores alpha 1, and the from/to scale values load.
2026-11-01 17:25:18 -06:00
Brues 5b7fe94d4d feat(xml): alpha, scale, desaturated, indented and other XML attributes
Later clients read these attributes in their XML loaders; 1.12's do not.
Each is now read after the engine has loaded the node (Xml::FrameLoad for
frames, Xml::TypeLoad for the rest) and goes through the setter the
matching Lua method uses. Each applies only when present and non-empty,
so an element's own value overrides its template's.

Frames:
- scale: Frame:SetScale's path (0x00775140). A negative scale is refused,
  anything else goes to SetFrameScale (FUN_FRAME_SET_SCALE 0x0076AC10,
  __thiscall(frame, float, force), ret 8) without force. A Model keeps
  `scale` as its model scale, which its own loader reads.
- dontSavePosition, propagateKeyboardInput: the existing frame flags,
  through FUN_FRAME_SET_FRAME_FLAG.

Textures and font strings:
- alpha: parsed as the frame loader parses its own `alpha` (SStrToFloat,
  clamped to 0..1, truncated to a byte), then set as Texture:SetAlpha and
  FontString:SetAlpha set it (0x0079B580, 0x0079CB70): the region color
  from FUN_REGION_GET_COLOR with its alpha byte replaced, through
  FUN_FONTSTRING_SET_COLOR. It applies after the node's <Color>.
- desaturated (textures): Texture::Desaturation's full amount, the same
  as SetDesaturated. It applies whenever present; an empty value is false.
- indented (font strings): the style bit SetIndentedWordWrap sets.

Status bars:
- reverseFill, rotatesTexture, fillStyle: StatusBar::Fill's modes, read
  after the status bar loader has set the BarTexture. An unknown
  fillStyle name changes nothing.

Tested in game with an XML test addon: every attribute set its value, and
parentKey, wordwrap and countInvisibleLetters still load.
2026-11-01 16:45:11 -06:00
Brues 43594398f0 refactor(xml): one observer owns the per-type XML loader hooks
MinHook allows one hook per address, so the texture, font string and
button loader hooks lived in Xml::ParentKey, which then read every other
module's attribute for it (mask, atlas, wordwrap, registerForClicks), and
CountInvisibleLetters hooked the EditBox loader on its own.

Xml::TypeLoad now owns the hooks on the engine's per-type node loaders,
the way Xml::FrameLoad owns FUN_XML_FRAME_LOAD's, and fans out to
subscribers after the engine has loaded each node:

- texture        FUN_XML_TEXTURE_LOAD    0x0076FE20
- font string    FUN_XML_FONTSTRING_LOAD 0x00770F40
- button         FUN_XML_BUTTON_LOAD     0x007788C0 (CheckButton's loader
                 calls it first)
- edit box       FUN_XML_EDITBOX_LOAD    0x00779FB0
- status bar     FUN_XML_STATUSBAR_LOAD  0x00782EF0 (new; calls
                 FUN_XML_FRAME_LOAD first at 0x00782F06, ret 8)

All five share the sub-object convention __thiscall(loader, node,
status), ret 8, object = loader - OFF_XML_LOADER_SUBOBJECT. An inherited
template goes through the same loader first, so a node's subscribers run
after its templates'. The texture and font string loads keep running in
the node's mixin scope (Xml::Mixin::Begin / End), as before.

Each attribute is now read in the module that owns its setter:
Texture::Mask (mask), Texture::Atlas (atlas, useAtlasSize),
FontString::WordWrap (wordwrap), Frame::ClickMask (registerForClicks) and
EditBox::CountInvisibleLetters (countInvisibleLetters). The XML-only
entry points Atlas::SetFromXml, WordWrap::Set and ClickMask::SetFromXml
become private, and ClickMask.h and WordWrap.h go. ParentKey keeps only
its own binding work. Same hook addresses, same order around the engine
call, no behavior change.
2026-11-01 16:44:59 -06:00
Brues 2eef939b5a feat(xml): registerForClicks and wordwrap attributes
1.12's loaders read neither attribute: the Button loader (0x007788C0)
has no registerForClicks, and the font string loader (0x00770F40) reads
nonspacewrap but not wordwrap. Both were silently ignored, so ported
templates got the default click mask and wrapping text.

Both are read in the loader hooks Xml::ParentKey already owns, after
the engine's loader and before OnLoad, and only when present and
non-empty, so a node's value beats its template's and an OnLoad call
still overrides it. No new hooks.

registerForClicks follows 3.3.5's CSimpleButton::LoadXML. Storm's
tokenizer (0x0064AE50, the one 3.3.5 calls) splits the value on spaces
and commas. Each name ORs in its bits through
Frame::MouseRegistration::MaskForName, the RegisterForMouse name table
(3.3.5's MouseButtonStringToBitmask, AnyUp / AnyDown included). The
result replaces the mask through the engine's own setter 0x00779730
(__thiscall(button, mask), ret 4, writes only +0x330).

wordwrap goes through FontString::WordWrap::Set, the body of
fontstring:SetWordWrap: it clears the font's override of the no-wrap
style bit and lays the string out again when the value changes.

Tested in game: WowStyle1DropdownTemplate's Text (wordwrap="false")
now reports CanWordWrap() = nil.
2026-11-01 16:03:33 -06:00
Brues 36f3661b98 feat(lua): GetCallstackHeight, GetErrorCallstackHeight, SetErrorCallstackHeight
Adds the three call stack heights an error handler uses to start its
stack at the code that failed:
    debugstack(GetCallstackHeight() - (GetErrorCallstackHeight() - 1))
A height counts levels as lua_getstack (0x006FBAA0) does, and so as
debugstack does: C functions and lost tail calls count, and level 1 is
the caller.

1.12.1 records no error height, but every error report runs one C
function, FrameScriptCallErrorHandler (0x00703B40, __fastcall(L)). It
pushes the seterrorhandler function (registry ref 0x008722CC), moves it
under the message and lua_calls it. Nothing calls it directly: state
open pushes it as a C closure and refs it (0x008722C8). Every script
pcall passes that closure as the errfunc, so Lua calls it at the point
of the error before the stack unwinds; a chunk that fails to compile is
reported by a pcall of it (0x00704AE0). ClassicAPI's securecall,
hooksecurefunc and script runners pass the same ref.

So while any handler runs, that closure's level sits directly above the
code that failed. GetErrorCallstackHeight walks the levels with
lua_getstack and lua_getinfo "f", finds the innermost one whose function
is 0x00703B40 (lua_tocfunction, 0x006F3720) and answers the height below
it, or nil when no error is being reported. There is no hook, and
nothing is recorded, so a handler that fails part way leaves nothing
behind.

SetErrorCallstackHeight sets the height for a handler called with no
error raised. It applies only while no 0x00703B40 level is on the stack,
so a value left set by a failed handler cannot move a later error's
stack. A new Lua state starts with no value set.

Users:
- The Lua error window takes its stack this way, so it starts at the
  failing code even when another addon wraps the handler.
- CallErrorHandler and assertsafe set the height around their direct
  handler call, so they report from their caller.
- Game::Lua gains GetStack, GetInfo and ToCFunction; SourceLocation uses
  them in place of its own copies.

Docs: the xpcall and coroutine notes said error() returns without
raising. Stock error (0x00702970) ends in lua_error (0x006F4440) and
raises. pfUI replaces the global error with one that prints and
returns, which is what those notes described.

Tested in game: with seterrorhandler wrapping the old handler, a nil
index in a local function f showed a stack that starts at f.
2026-11-01 15:37:11 -06:00
Brues 4f3ee595e7 feat(ui): Lua error window replaces the stock error box
The Lua error window (/luaerrors) moves from the load-on-demand
ClassicAPI_DebugTools into !!!ClassicAPI and becomes the client's error
display. Each error opens it with the message, time, count and stack, and
the arrows page through every error so far.

1.12.1's error handler is FrameXML's _ERRORMESSAGE (BasicControls.xml). It
reports an error as ScriptErrors_Message:SetText(message) and then
ScriptErrors:Show(), and only while the stock box is hidden. The window's
OnLoad takes those two slots, the same two !BugGrabber 2.1.1 takes: SetText
records the error and Show does nothing, so the stock box stays hidden and
every error arrives. Errors still pass through the handler first, so:
- !BugGrabber loads after !!!ClassicAPI and takes the slots back. BugSack
  gets the errors and the window does not open.
- An addon that calls seterrorhandler (pfUI) replaces _ERRORMESSAGE, so
  neither shows. One that wraps the old handler still ends here.

The engine's error function (0x00703B40) is C. It runs at the point of the
error, before the stack unwinds, and calls the registered handler. From the
SetText slot, level 1 is the slot, 2 is _ERRORMESSAGE, 3 is that C function
and 4 is the code that failed, so the stack starts at debugstack(4), the
level !BugGrabber's GrabError reads from the same slot.

The text is ClassicAPI's ScrollingEditBoxTemplate with a MinimalScrollBar.
The bottom row has Reload UI, arrows that wrap around the index label, and
Close. /luaerrors opens or closes the window and /luaerrors clear empties
it; the old on/off handler install is gone.

Not tested in game yet.
2026-11-01 15:15:52 -06:00
Brues 99f72aa631 feat(ui): UI_SCALE_CHANGED event
Fires (no payload) each time the game applies the interface scale to
UIParent.

In 1.12 every scale change goes through one function, SetUiParentScale
(0x00494550, void __stdcall(float), ret 4). It raises the value to 0.64,
calls SetScale with force (0x0076AC10) and drains the layout queue
(0x00768ED0), and does nothing while UIParent (0x00B4B44C) is null. It
has six callers:
- the uiScale cvar callback (0x00490770, two sites)
- the useUiScale cvar callback (0x004907F0, two sites)
- OnDisplaySizeChanged (0x00492E90) when useUiScale is on
- the automatic scale ApplyAutoUiScale (0x00492F70)

One MinHook on it fires the custom event after the original returns,
only while UIParent is set. The game UI's Initialize stores UIParent
(0x00490077) and its Shutdown clears it (0x00490CA4), so the event never
fires on the glue screen. Each path calls the setter once, so one change
fires one event; a resize fires it before DISPLAY_SIZE_CHANGED.

Tested in game: useUiScale on, uiScale 0.8 and useUiScale off each fired
one event with the new scale (0.91, 0.8, the automatic 0.9).
2026-11-01 14:38:33 -06:00
Brues 9e5c0c558a feat(autocomplete): C_AutoComplete name completion (API only)
Adds C_AutoComplete.GetAutoCompleteResults, C_AutoComplete.IsRecognizedName,
Enum.AutoCompleteEntryFlag and Enum.AutoCompletePriority, and the cvars
autoCompleteResortNamesOnRecency, autoCompleteWhenEditingFromCenter and
autoCompleteUseContext. ClassicAPI only answers the queries; an addon draws
the list of names.

1.12.1 keeps no autocomplete list, but it keeps every list the names come
from, so each query reads them where the client keeps them:
- party: the four GUIDs at VAR_PARTY_GUIDS (0x00BC6F48), names from the
  name cache, online from the member stats block
- raid: the VAR_RAID_MEMBER_PTRS slots (0x00B712A8) and their online bit
- guild: the GuildMemberInfo roster at 0x00B72704, GUID at +0x00 and the
  online word at +0x48 (stored at 0x004D0C22, tested by GetGuildRosterInfo
  at 0x004D13C5). Read only while the player's guild key is set, the test
  IsInGuild (0x00516DE0) makes, because the client keeps the old roster
  after a /gquit
- friends: the 50 slots of the social singleton

Whisper partners are the one list the client does not keep. The chat
dispatch hook (FUN_0049A870) reports each whisper and whisper inform
(types 6 and 7, not the addon language -1) with the sender GUID it already
resolves. Logging out clears the list.

Names match case-insensitively by UTF-8 code point; Text::Utf8::CompareI
now takes a character limit. Results come most recent whisper first, then
by name. A result's priority is its closest tie: friend, guild, group,
whisper.

GetAutoCompletePresenceID and GetAutoCompleteRealms are constant answers in
Compat.lua. The three cvars are on a new Social page of the options panel.
2026-11-01 14:15:25 -06:00
Brues b3b950f2d8 feat(spell): spell alerts and proc glows (API only)
Adds C_SpellActivationOverlay.IsSpellOverlayed (and the global
IsSpellOverlayed), Enum.ScreenLocationType, and the four
SPELL_ACTIVATION_OVERLAY_* events. Nothing is drawn: an action-bar or
UI addon draws the alerts and the glows from these.

Glows come from the engine's own reactive-spell list. AddSpellToBook
puts every learned spell whose record has AttributesEx4 0x200 on the
list at 0x00B71150 (count 0x00B7114C), one 8-byte {spellID, usable}
entry per name. FireUsableEvents (0x004B31C0) retests the list with
the engine's usable check, stores each answer, then signals
SPELL_UPDATE_USABLE (0x107). The module subscribes to that signal
through Event::SignalHook and reads the stored answers, so the verdict
is the engine's (rage, target health, aura states, and the hidden
combo point behind Overpower) and no new hook is needed. A usable entry
glows every spellbook spell with the same name, which is the list's own
identity rule, so a bar slot with any rank glows. On stock 1.12.1 this
is Execute, Overpower, Revenge, Riposte, Counterattack, Mongoose Bite
and Hammer of Wrath; Turtle's Spell.dbc changes the set by itself.

Alerts come from two Blizzard rows whose aura exists unchanged in 1.12:
Shadow Trance (Nightfall art, glows Shadow Bolt through its class mask
via Spell::Lookup::IsFitToFamily) and druid Clearcasting
(Natures_Grace art). An Aura::Source observer reconciles on the
player's aura add/remove, rescanning the descriptor so counts can't
drift. The texture is a path; 1.12 has no file data IDs.

On world entry, HIDE fires with no spell ID and every active alert
fires SHOW again, so a /reload redraws them. Glows already lit before a
/reload do not re-fire; a button reads IsSpellOverlayed when it draws.
Logging out clears the state without events.

Event::EnteringWorld gains an observer list, because it claims
PLAYER_ENTERING_WORLD in the signal chain and later subscribers never
see it. Event::Custom's reservation cap goes from 96 to 128: the four
new events filled the old cap exactly, and a name past the cap is
dropped silently.
2026-11-01 13:35:12 -06:00
Brues 5dcf10a9fd fix(player): name cache keeps one copy of each player and honors renames
The persistent name cache copied every name reply into its own map, so
each player the engine named this session was held twice. The copy also
went stale. On a rename the server sends SMSG_INVALIDATE_PLAYER (0x31C)
and HandleNameInvalidate 0x00555600 frees the engine's record, but our
copy kept the old name, and GetPlayerInfoByGUID / UnitNameFromGUID fell
through to it.

The store now holds only the players the engine's name cache
(0x00C0E228) does not:

- A Net::PacketDispatch subscriber reads SMSG_NAME_QUERY_RESPONSE (0x51)
  in the same order as HandleNameQueryResponse 0x005551A0 and drops our
  entry just before the engine stores its record. This replaces the hook
  on NameCacheStore 0x0055F310. The backstop save runs before the drop,
  so no save misses the player.
- The same subscriber drops our entry on SMSG_INVALIDATE_PLAYER.
- The engine empties its cache only at world entry: NameCacheClear
  0x00560400, called from CGGameUI::InitializeGame through 0x00555740.
  A hook there copies the engine's records into the store first, while
  the store still holds the realm they came from.
- At exit the engine frees the cache from its atexit handler
  (NameCacheSave 0x0055EC70). Storm's exit handler 0x0064CC30 runs every
  atexit handler before ExitProcess, so DLL_PROCESS_DETACH was too late
  to read it. At the first world entry the clear hook registers our save
  with the exe's own _atexit (0x00409AEF). Handlers run newest first, so
  ours runs before the engine's. Detach now calls Shutdown, which never
  reads the engine's cache.
- A save writes our store, then the engine's records, so a load applies
  the engine's data over ours.
- C_PlayerCache.RememberPlayer leaves alone a player the engine holds.

One hook removed (0x0055F310), one added (0x00560400).
2026-11-01 13:16:56 -06:00
Brues 3ef6c4ffed fix(player): name cache keeps each player's realm and whole UTF-8 names
The persistent name cache cut names at 16 bytes. A Chinese character is
3 bytes in UTF-8, so a 6-character name lost part of its last
character. The limit is now the engine's own: the name cache store
(0x0055F310) copies the name with SStrCopy(dst, src, 0x30) and the
realm with SStrCopy(dst, src, 0x100), now PLAYER_INFO_NAME_SIZE and
PLAYER_INFO_REALM_SIZE in Offsets.h. A longer name from Lua is cut on
a UTF-8 lead byte, never inside a character.

Entries are now keyed by GUID, the engine name cache's own key, and
keep the record's server name (+0x30, empty for a player on this
realm). The by-name index uses the form the engine itself shows for a
player from another realm: ClientChatHandler (0x0049D560) builds the
sender as name, "-", and the realm with spaces and tabs removed. A
bare name stands for this realm. Player::FullName builds and parses
that form. Two players with one name from two realms no longer replace
each other, C_PlayerCache.GetPlayerInfoByName takes "Name-Realm" (a
chat sender name as it comes), and the persistent fallbacks of
GetPlayerInfoByGUID and UnitNameFromGUID return the stored realm. A
"Name-Realm" skips the by-name search and the friends list, which keep
no realm. The engine name cache walk moved from Unit::Identity into
Player::Info, its one caller.

The cache is one flat file per realm,
WTF\ClassicAPI\NameCache-<realm>@<realmList>.txt, in a v5 format split
on tabs (a realm can hold spaces): guid, name, realm, class, race, sex.
The v4 file under WTF\ClassicAPI\<realmList>\<realm>\ is migrated on
first load and deleted, with its emptied folders, once v5 is saved.
The old import from the per-account path is gone.

The store loaded once per process and saved to whatever realm was
current, so logging out into another realm wrote the first realm's
players into the second realm's file. It now records the file it
holds: every access compares that with the current realm's file, and
on a change saves the old realm's entries to their own file before
loading the new one. A failed rename leaves the cache dirty for the
next flush.

Verified on Octo: all 63,178 N'Zoth v4 entries migrated unchanged,
13 of 13 C'Thun entries migrated, the v4 folders were removed, and a
N'Zoth to C'Thun switch in one session kept the two files apart.

Fixes #119
2026-11-01 12:34:31 -06:00
Brues 1ef8c5597a fix(player): UnitNameFromGUID returns the name cache's realm
CGUnit_C::GetUnitName (0x00609210) takes a realm out-pointer as its
stack argument, not the flags word Offsets.h called it. For a player
whose name-cache record has a non-empty server name (record +0x30) it
stores a pointer to that string, and otherwise leaves the pointer alone
(0x0060926B-0x00609283). Vanilla's Script_UnitName (0x00517020) passes
&realm there and returns it as UnitName's second value. The record's
server name is the realm string SMSG_NAME_QUERY_RESPONSE carries:
Tortoise sends it empty, a cross-realm server fills it.

UnitNameFromGUID pushed a hard-coded "" instead. NameFromGuid now passes
the out-pointer through, as Script_UnitName does, and gains a step
between the friends list and the persistent cache: the engine name
cache record itself (FUN_PLAYER_INFO_LOOKUP with no callback, a passive
peek), which also gives the realm for players out of range. Before, a
player who whispered from far away resolved only with the persistent
cache on. UnitSpellTargetName shares NameFromGuid and finds those
players too. The realm is "" when the record has none, or when the name
came from the friends list or the persistent cache, which stores no
realm. Retail documents both returns as non-nil strings.

GetNameAndServerNameFromGUID in the addon's PlayerUtil returned
GetRealmName(), the local realm, for every GUID. It now returns
GetPlayerInfoByGUID's realm, as retail's UnitUtil does, so a player on
the local realm gets "" and code that appends "-" .. realm only when it
is non-empty works.

Seven files declared their own function-pointer type for 0x00609210,
all with the wrong int *outFlags argument. Unit::Identity::NameForUnit
is now the one wrapper. The other six callers pass no realm and behave
as before.

Offsets.h gives the getter's real signature (RET 4) and what it stores.
API.md's GetPlayerInfoByGUID and UnitNameFromGUID entries describe the
realm and the four sources.
2026-11-01 11:05:24 -06:00
Brues 9b0aa46ff0 fix(tts): a stopped utterance no longer finishes the next one
StopSpeakingText purges SAPI's queue, but the purge still queues
START/END events for the streams it cut off, and SAPI numbers streams
from 1 again afterwards. The next SpeakText then reused stream 1, so
the stale events were read as the new utterance's:
VOICE_CHAT_TTS_PLAYBACK_STARTED and _FINISHED fired for it before it
played, and its real end fired a FINISHED with utteranceID 0.

The purge is synchronous and has queued all of those events by the
time it returns, so StopAll now drains and discards them right after
it. That covers stop and speak in the same Lua call too, where the
stale START is still queued and a "require START first" check on the
END handler would not have been enough. An END for a stream we do not
track no longer fires FINISHED with utteranceID 0. Purged utterances
now signal nothing, which is retail's contract.

Verified with a standalone SAPI probe: speak/stop/speak, with and
without a message pump between the calls.
2026-11-01 00:00:27 -05:00
Brues 84171bef2d fix(unit): mirror timers clear on leaving the world, empty slots say UNKNOWN
The engine's handler for the three mirror-timer SMSGs (0x005E7990) only
reads each packet and signals MIRROR_TIMER_START / _PAUSE / _STOP, so
GetMirrorTimerInfo and GetMirrorTimerProgress read a table of our own.
A MinHook on that handler fed it by reading the packet and putting the
cursor back. The table now reads START (0x1D9) and STOP (0x1DB) as a
Net::PacketDispatch subscriber, and the hook is gone.

CGPlayer_C::Release (0x005E9AA0) runs StopMirrorTimers (0x005E9B90) for
the active player: MIRROR_TIMER_STOP for all three types, with no
packet. The table never saw it, so a breath timer stayed after a logout
or a loading screen. Release then calls LeaveWorldUI (0x00490A80),
which fires PLAYER_LEAVING_WORLD through the no-arg dispatcher. An
Event::SignalHook subscriber clears the table on that event.

What the functions return:

- GetMirrorTimerInfo returns an empty slot as "UNKNOWN" with zeros, the
  name helper 0x005E7AE0 gives for no type, instead of nothing. Code
  that tests for "UNKNOWN" on PLAYER_ENTERING_WORLD called its setup
  with nil before. paused is a number, as the event's %d is, and
  spellID is a seventh value.
- A PAUSE packet no longer changes the table. Tortoise never sends one:
  it resends START with the paused byte, which the table keeps.
- GetMirrorTimerProgress is value + scale * elapsed with no clamp. A
  timer started paused holds its value. Names match through SStrCmpI,
  and a name that is not a timer type returns nil.
- The time comes from Time::Clock. 0x0042B790 truncates the tick
  itself and returns it in EAX, so the GetTickCount workaround for an
  FPU return had no cause.

Offsets.h drops the CDataStore readers, the handler and the PAUSE
opcode, which nothing reads now, and its comment gives the verified
signatures and packet layout. Both functions get API descriptors under
the MirrorTimer system. API.md's section is rewritten to match.
2026-10-31 23:34:39 -05:00
Brues f19f13d44c feat(debugtools): fold pfDebug in as /profiler
pfDebug was a separate addon that profiled through ClassicAPI's own
APIs: GetAddOnMemoryUsage and GetAddOnCPUUsage, GetFrameCPUUsage,
GetFunctionCPUUsage, GetEventCPUUsage, and the intrinsic precall and
postcall script hooks. Its code now lives in ClassicAPI_DebugTools
under Profiler/, with its MIT notice (Copyright (c) 2018 Shagu). The
analyzer tabs (Addons, Frames, Events, Globals) and the widget are
pfDebug's, with the frame and template names renamed to
ClassicAPIProfiler*.

/profiler and /prof load DebugTools on demand through the same stub as
/dump, then toggle the analyzer. The subcommands widget, reset and
profile on|off are pfDebug's.

What changed in the move:

- The sampler starts only when the widget or the analyzer first opens,
  so a load for /dump costs nothing. It first takes every counter as it
  is, so the first CPU/s and KB/s cover one second, not the session.
- Whether profiling runs is probed, not read from the cvar: a function
  is called once and GetFunctionCPUUsage must count that call. The
  scriptProfile cvar can already hold the next session's value.
- A frame record starts at the frame's current CPU time and call count,
  and opening the analyzer takes every frame and event counter again,
  because the frame totals and the deep hooks keep counting while it is
  closed. pfDebug started records at 0, so the first scan and each
  reopen showed a frame's whole session as one second.
- The /fstack lines (owner, OnUpdate and OnEvent owner and CPU, all
  scripts, deep allocations) are added at the end of
  FrameStackTooltip_OnTooltipSetFrameStack, not by hooking
  OnTooltipSetFrameStack.
- No pfUI skin and no SavedVariables. The plain backdrop is pfDebug's
  own fallback. The widget no longer opens at login, because that would
  load DebugTools at login.

README's Debug tools table gains /profiler and the new /fstack lines.
2026-10-31 23:16:01 -05:00
Brues 4509da0966 build: pack each embedded addon into one gzip stream
Each embedded file was its own gzipped RCDATA resource, 175 in all.
Every stream started with an empty deflate window, so no file could
match text it shares with its neighbours, and 97 of the files are under
4 KB, where that costs the most. Each resource also cost about 50 bytes
of resource directory and padding.

cmake/pack_files.cmake, which replaces gzip_file.cmake, now joins each
addon's files at build time into one gzip stream. It holds an index,
each file's size as a decimal line and then an empty line, followed by
the files' bytes in path order. `cmake -E cat` joins them byte for
byte, in batches of 100 so the Windows command-line limit cannot fail
the build. The index goes through file(CONFIGURE NEWLINE_STYLE UNIX)
because file(WRITE) writes \r\n on Windows. The resources are now three:
Bindings.xml as a pack of one, !!!ClassicAPI, and ClassicAPI_DebugTools.

The manifest entries become {path, resourceId, index}, and
Embed::Resource(id) becomes Embed::File(id, index). On first use it
inflates the whole pack with the engine's zlib, splits it into views,
and keeps it for the life of the DLL, as before. A pack whose sizes do
not cover its bytes exactly is rejected. The load-on-demand DebugTools
pack is still inflated only when it loads.

Embedded data 323,947 -> 272,825 bytes; .rsrc 334,336 -> 274,432;
DLL 1,632,768 -> 1,573,888 bytes.
2026-10-31 23:06:40 -05:00
Brues 38d5c6c7b6 fix(unit): ClassicAPI's unit events reach markN and the soft tokens
ClassicAPI fires its own unit events (UNIT_AURA_DELTA, the remote
UNIT_SPELLCAST_*, the power, group-member, distance, incoming-resurrection
and targetable events) once per token through
Unit::Identity::TokensForGUID. That took the engine's tokens from its
reverse map FUN_UNIT_TOKENS_FROM_GUID (0x00515C50) and then added its own
short list: focus and nameplateN. The engine's unit events get their
ClassicAPI tokens from a second list in Unit::TokenEvents, which also has
markN, softenemy and softfriend. So a soft enemy got UNIT_HEALTH but never
UNIT_SPELLCAST_START.

That list is now the public Unit::TokenEvents::TokensOf, capped at the
caller's room and empty before the player object exists, as before.
TokensForGUID appends it to the engine's tokens, so both kinds of event
reach the same tokens, and a new token goes in one place. nameplateN now
comes before focus, the order TokensOf already used.

API.md's soft enemy and soft friend section now says that their tokens
fire unit events, as the focus, nameplateN and markN sections do.
2026-10-31 22:46:51 -05:00
Brues be5ebd4017 docs(unit): name softenemy and softfriend in the token comments
44f9bcd added softenemy and softfriend to Unit::TokenEvents, but the
comments that list its tokens still named only focus, nameplateN and
markN. They now name all five. The call-site mismatch log no longer
lists them at all: it says ClassicAPI tokens get no engine unit events.

The token resolver's header in TokenExtensions.cpp had drifted too. It
said markN unit events go through TokenObserver (TokenEvents fires them
now), spoke of "both" families where there are six, and gave a
resolution order of focus then nameplate. The order in the hook is raw
GUID, focus, the soft targets, nameplateN, markN. UnitCreatureID's
comment now points at that header instead of keeping its own list.

UnitTokenFromGUID's comment called the soft targets' place in retail's
order unverified. Retail's list puts them last, as the code does, and
has no markN, so the comment now says markN is never returned.
2026-10-31 22:37:48 -05:00
Brues 44f9bcd9af feat(unit): softenemy and softfriend fire unit events
Unit::TokenEvents already redirects the 38 broadcast and 4 combat
feedback call sites so a unit holding focus / nameplateN / markN gets
every engine unit event under that token. softenemy and softfriend join
that token list, read through SoftUnit::Current (the last pick, no scan)
because TokensOf runs on every unit event.

The registration bit (UNIT_SCRIPT_REG_TOKENS) is what makes the engine
watch a unit, so SoftUnit::Refresh re-runs FUN_UNIT_SCRIPT_RECOMPUTE
through TokenEvents::Refresh for the old and new guid before the
PLAYER_SOFT_*_CHANGED event fires. The frame tick now picks every frame
rather than only while that event has a listener: a UNIT_HEALTH listener
never registers for it, and the pick is cached per scene drain anyway.
2026-10-31 22:25:18 -05:00
Brues f9ec92014c feat(target): show softenemy and softfriend names as the target's
Retail shows a soft unit's overhead name the way it shows the target's:
a soft enemy past nameplate range keeps its name, whatever the UnitName
cvars say.

1.12 decides an overhead name in CGUnit_C::ShouldShowName (0x6070A0),
which its only caller, the name draw PLAYERNAMEDESC::UpdatePlate
(0x6C6EE2), asks every frame. In order: no name when CanSelect (vtable
+0x58) refuses the unit, or when it has a nameplate (+0xE60) or a chat
bubble (+0xE64); the active player by UnitNameOwn; the target always;
then the UnitName mask. A hook gives a soft unit the target's branch:
the first three tests, then 1. The player is never a soft unit, so the
own-unit test does not apply. In nameplate range the plate shows and
the name does not, as for the target.

The name draw runs inside the scene (the model draw callback 0x6C7780),
so the hook reads the soft GUIDs cached on the UI frame tick, as the
selection circle does, and never picks there. Nothing invalidates: the
verdict is asked fresh each draw.
2026-10-31 20:38:51 -05:00
Brues 264af04ee3 feat(cooldown): countdown formatter and C_StringUtil.CreateNumericRuleFormatter
Addons can now choose the countdown text and its color for each range of
time left. Cooldown:SetCountdownFormatter(formatter) and
GetCountdownFormatter() take a NumericRuleFormatter from
C_StringUtil.CreateNumericRuleFormatter(). Its breakpoints each give a
threshold, an optional step, rounding (Enum.NumericRuleFormatRounding),
min and max, a format string, and optional div/mod/step components, one
for each format argument. Color codes in the format string pass through.

The formatter is a full Lua userdata, the first in the DLL. Its block
holds a pointer to a reference-counted native object. Every Lua object
and every frame that uses it hold one reference, so the GC finalizer
(__gc) and the frame's deleting destructor can run in any order.
lua_newuserdata (0x6F4560, __fastcall, block at Udata + 0x10, read from
the disassembly) is new in Offsets.h. lua_touserdata reuses
FUN_FRAMESCRIPT_GET_OBJECT, which is that function. One metatable per
Lua state lives in the registry. Its __metatable is false, and the
identity check compares a value's metatable with it. 1.12 has no
newproxy, so the only finalizer an allocation can run is ours. Thus no
addon code can change a formatter while it formats.

The text goes through 1.12's own str_format (0x7FD3D0). Its closure is
made once per state and kept in the registry, because FormatNumber runs
from addon timers and lua_pushcclosure allocates on each push. The
rounding is x - fmod(x, step), plus a step away from zero when the
rounding needs it. Only that arithmetic matches retail to the last bit:
Up of 0.7 by 0.1 gives 0.7000000000000001 and of 0.6 gives 0.6, but
ceil(x / step) * step gives 0.6000000000000001.

The cooldown shares the formatter and gives it the unrounded seconds
left. The formatter replaces the built-in text and both thresholds, and
every gate stays. The cached countdown text is now a heap std::string,
because a formatter's text has no length limit. The frame frees it, and
its reference, in DeletingDestructor.

A probe addon recorded 229 results in retail 12.1.5. The same probe on
1.18.1 matched 197 of them. The other results come from 1.12's own
str_format (%e exponent digits, %q, %d past the int range, its error
wording), from field storage on the object (not ported), and from
addresses and times.
2026-10-31 18:50:09 -05:00
Brues 2063507fb4 fix(lua): ported files read wipe from the ClassicAPI mirror
The global wipe is ours only until an addon declares its own: whoever
writes _G.wipe last wins, with no error. RegisterGlobalFunction mirrors
every global it binds into _G.ClassicAPI at registration, before FrameXML
and every addon load, so ClassicAPI.wipe is always our table.wipe C
function.

The nine embedded files that call the bare global now take
`local wipe = ClassicAPI.wipe;` and list it as their difference from
retail: ScrollBoxListView, ScrollUtil, Menu, CallbackRegistry, MixinUtil,
SecureTypes and the three DebugTools table inspector files. Files that
read table.wipe, as their retail sources do, are unchanged. The global
stays for third-party code.
2026-10-31 16:50:14 -05:00
Brues 090cfc3bfd feat(lua): global wipe, the table.wipe alias
On a stock 1.12.1 client, ScrollBoxListView, ScrollUtil, Menu and the
DebugTools table inspector failed with "attempt to call global `wipe'":
those ports call bare wipe(), and only Turtle's client defines that
global. Stock 1.12.1 has only the table.wipe that ClassicAPI registers.

3.3.5 makes the alias in FrameScript's compat preamble, next to tinsert
and tremove (wipe = tab.wipe). 1.12's preamble is older than table.wipe,
so Wipe.cpp now registers the same C function as the global wipe as well
as table.wipe, with a LuaGlobals descriptor.

CallbackRegistry, MixinUtil and SecureTypes lose their "1.12 has no
global wipe" notes and their table.wipe locals, and now match retail.
2026-10-31 16:44:34 -05:00
Brues d1cdb47c3e feat(unit): restore UnitFacing
UnitFacing(unit) returns the unit's facing in radians (0 = north,
counter-clockwise, 0..2pi), or nothing when the token has no unit.

The facing comes from the object's GetFacing virtual, vtable slot 6.
The unit and player vtables (0x80C4F8 / 0x80AF78) both hold
CGUnit_C::GetFacing (0x5F1F30) there, read from the binary: it loads the
mover at +0x118, pushes its facing +0x1C and returns
CMovement::TransportFacingToWorld (0x7C4AE0), which adds the transport's
facing and wraps once into [0, 2pi]. Unit::Position::Facing wraps the
call next to the shared position read.

GetPlayerFacing moves to the same read. It used to load the float at
+0x9C4 (the mover's +0x1C) directly, which is the facing relative to the
transport, so on a boat or zeppelin it returned the wrong angle. The
OFF_UNIT_FACING offset goes with it.
2026-10-31 16:25:24 -05:00
Brues 237e5a7500 fix(container): sort gear by equip slot before item class
The bag sort compared item class before the equip slot rank. Shields,
held-in-off-hand items and relics are armor class (4), so they left the
weapon group and sorted first in the armor block, before head pieces.

For gear, the slot rank (Item m_inventoryType through kSlotOrder) now
comes first and item class is the next tiebreak. Those items now sort
with the weapons, where the slot order puts them. Non-gear items sort
the same as before.
2026-10-31 15:24:24 -05:00
Brues d339f4486d refactor(swing): reset on weapon swap from the inventory-slot observer
A weapon equipped in combat resets that hand's swing timer on the
server, with no packet for it. PLAYER_SWING used to catch this by
reading the main-hand, off-hand and ranged GUIDs from the player's
inventory manager (player+0x1D38) on every WorldTick and comparing
them with the previous frame.

The engine already reports these changes. CGPlayer_C::AddActiveWatchers
(0x005DD8A0) registers OnInventorySlotChanged (0x005DDCF0) on every
equipment slot, and the descriptor dispatcher calls it only when a
slot's GUID really changes. Player::Equipment already hooks that
handler for PLAYER_EQUIPMENT_CHANGED. It now also calls
Combat::Swing::OnWeaponSlotChanged, which resets the hand for slots
15/16/17 when the player is in combat.

The call runs inside SMSG_UPDATE_OBJECT, after the values block is
written, so the attack-time descriptor field already holds the new
weapon's speed. The lookups it makes (player by GUID, descriptor
reads) do not throw.

The per-frame poll and its snapshot state are removed. The WorldTick
subscriber stays: it still merges several resets in one frame into
one PLAYER_SWING per swing type.
2026-10-31 13:50:41 -05:00
Brues 92025896b5 feat(options): a control for every cvar, one cvar per control
The AddOn Options panel now has a control for each of the 38 cvars that
ClassicAPI registers, plus the player cache, on pages grouped by
feature: Interact Key, Action Targeting, Combat, Bags and Items,
Interface, Text To Speech and Advanced.

Each control reads and writes exactly one cvar, and writes it only when
the player uses that control. The "Interact Key Icons" preset dropdown
is gone: it wrote four icon cvars at once, and Cancel restored it from
a snapshot that read any mixed state as "NPCs Only", which turned
SoftTargetIconInteract back on. Okay, Cancel and Defaults no longer
write anything on these pages.

- On/off cvars are checkboxes. The soft-target enable cvars read as on
  for 2 or 3 and write 3 or 0; 1 is gamepad, which does nothing here.
- Fixed choices (the three arc cvars, SoftTargetForce) are dropdowns. A
  value outside the choices shows as its number.
- Open-ended numbers (ranges, icon size, shake strength, combat log
  retention) are number boxes, so the panel sets no maximum. Sliders
  are kept for documented ranges only.
- Each page's controls sit in a WowScrollBox with a MinimalScrollBar.
  The box clips its children, and the clip also keeps the mouse off
  controls that are scrolled out of view.

The panel's strings are globals in locales\enUS.lua, which every client
loads: CLASSICAPI_* for ClassicAPI's own, and retail's GlobalStrings
keys where retail has the string (COUNTDOWN_FOR_COOLDOWNS_TEXT and its
tooltip, with retail's translations in the other locale files).

The README cvar table gains the five cvars it was missing.
2026-10-31 12:58:22 -05:00
Brues 4eb214f7f1 fix(tick): run world-tick subscribers after the UI draw
CWorld::BeginFrame (0x0066FD50), the world tick, runs inside the UI
strata walk. Its only caller is CGWorldFrame::OnRender (0x00482EA0),
which WorldFrame's layer-0 draw callback (0x00482D70) runs. By then
0x007657D0 has already rebuilt the WORLD stratum's level batches. The
levels above 0 are not drawn yet. Nameplates sit at level 1, with
their name and level text on OVERLAY.

A batch's text run keeps a raw pointer to its font. The run's draw
(0x005C8FE0) uploads all eight of that font's atlas pages, even when
no strings are left in the run. Every subscriber ran at the hook, and
several of them run Lua (NAME_PLATE_CREATED, the C_Timer callbacks).
An addon that restyled a plate there made the plate leave level 1 and
gave its font strings a new font. The old font was destroyed while
the built batch still pointed at it. The upload then read a freed
texture's format and faulted at 0x005A09B8.

The crash dump shows this state:
- Level 1 has no frames.
- Its dirty mask is 0xFFFFFFFF, and the stratum's flags are set again.
  Both were written after the rebuild.
- Its one OVERLAY run is empty, and its font's memory holds Lua table
  nodes.

The hook now only marks that the world ran. The subscribers run from
the UI render root's tail (Tick::FrameTick), after the strata walk,
so the engine rebuilds anything they change before it is drawn.
OnUpdate and packet events still run in the same order relative to
them. GetTickTime() also reads the same pass delta as before.

Fixes #116
2026-10-31 06:06:38 -05:00
Brues 706fb1c540 docs(readme): refresh the function, namespace and event counts
The intro and the Lua-calls summary still said 550+ functions across ~60
namespaces and 50+ events, the counts from 54516ad. Counted the same way
(backticked calls in the Lua-calls table, rows in the Events table), the
README now lists 980 calls under 75 namespaces and 86 events, so the
rounded-down figures become 950+, ~75 and 80+.
2026-10-31 05:22:52 -05:00
Brues e37052c67d feat(lua): SharedColorConstants
Port of retail's Blizzard_SharedXML/SharedColorConstants.lua, in
Blizzard's own text. It loads after ColorUtil.lua, when Color.lua has
already made the GlobalColor globals it reads, and adds
PLAYER_FACTION_COLORS_HEX, PLAYER_FACTION_BRIGHT_COLORS (the PvP
scoreboard colors) and COVENANT_COLORS.

FACTION_BAR_COLORS now holds retail's color objects in place of 1.12's
plain {r, g, b} tables. The stock code that reads it (the unit tooltip
and the reputation bars) reads only .r, .g and .b, which the objects
have; the values differ by less than 1/255.

PLAYER_FACTION_COLORS moves out of Constants.lua, because retail
defines it only here, and GetFactionColor goes back to retail's
one-line body without our nil guard.

Verified in game: FACTION_BAR_COLORS[1] is ffcc4d38 and [5] is
FACTION_GREEN_COLOR, PLAYER_FACTION_COLORS_HEX[0] is ffff2934,
PLAYER_FACTION_BRIGHT_COLORS[1] is ff00adf0, GetFactionColor("Alliance")
is ff00adf0, and COVENANT_COLORS.Kyrian is ff2aa2ff.
2026-10-31 05:14:36 -05:00
Brues f8f6dc28b8 feat(ui): GlobalColor table from build 1.60.1.70707
C_UIColor.GetColors now returns the GlobalColor.dbc rows of build
1.60.1.70707 instead of the BC Classic 2.5.5 snapshot: 331 rows where
there were 187, in the table's own row order.

- 148 new colors, among them PVP_SCOREBOARD_*_CELL_COLOR, the
  EXPANSION_COLOR_* set, and the profession, threat and power-prediction
  colors.
- 10 changed values, as the newer client has them: NORMAL_FONT_COLOR
  ffd200, RED_FONT_COLOR ff2020, PLAYER_FACTION_COLOR_HORDE ff2934,
  PLAYER_FACTION_COLOR_ALLIANCE 00adf0, TALENT_LINK_COLOR 71d5ff, and
  more. The C++ tooltips that read the table (item comparison,
  equipment sets, links) take the new values. Lua globals that 1.12
  FrameXML already defines keep their own values, because Color.lua
  only creates the globals that do not exist.
- The four HEALTHBAR_*_HEAL_PREDICTION_GRADIENT_COLOR* rows are gone;
  the newer table does not have them and nothing read them.
- A name that the DBC lists twice keeps only its last row, which is
  the value the client's own Color.lua loop ends on.
  COMPACT_UNIT_FRAME_FRIENDLY_HEALTH_COLOR and
  CHARACTER_FRAME_SIDE_PANEL_SKILL_COLOR join the earlier duplicates.
- DEBUFF_TYPE_ENRAGE_COLOR stays as our own row, for
  C_UnitAuras.GetAuraDispelTypeColor("Enrage").

Verified in game: GetColors returns 331 rows,
PVP_SCOREBOARD_HORDE_CELL_COLOR is ffff2934 and the alliance one
ff00adf0, GetAuraDispelTypeColor("Enrage") is ffff8c00, and
HEALTHBAR_MY_HEAL_PREDICTION_GRADIENT_COLOR1 is nil.
2026-10-31 05:11:55 -05:00
Brues 4472c81137 feat(lua): retail SharedXML helpers, Spline, ExportUtil and MixinUtil
Ports from retail's Blizzard_ObjectAPI, SharedXML, SharedXMLBase and
FrameXMLUtil, in Blizzard's own text, from the _forever_ build:
- ObjectCache.lua and SpellBookItemLocation.lua (ObjectAPI).
- TypeUtil.lua: ValueToBoolean and StringToBoolean.
- SortUtil.lua: SortUtil.CreateSortManager and the comparators.
- Sequencer.lua, Spline.lua (Catmull-Rom splines), TaggableObject.lua,
  ObjectUpdater.lua and ExportUtil.lua (base64 export/import streams).
- AnimationSystem.lua: SetUpAnimation and CancelAnimations.
- SmoothStatusBar.lua: SmoothStatusBarMixin.
- MixinUtil.lua: DrawLine, LineMixin, SparseGridMixin,
  DoublyLinkedListMixin, DirtiableMixin, DirtyPhaseMixin and more. 1.12
  has no global wipe, so the file reads table.wipe, as the other ports do.

FrameDeltaLerp now takes retail's three arguments and reads the frame
time from GetTickTime(). The old form needed a fourth elapsed argument,
so SmoothStatusBar's per-frame ticker would have errored. Nothing else
called it.

DebugTools drops its private StringToBoolean copy and calls the global
one from TypeUtil for the /framestack arguments.

FadingFrame.lua is not ported: 1.12's own FrameXML defines the same
FadingFrame_* names with no-argument `this` signatures, and ZoneText
calls FadingFrame_OnUpdate() every frame.

Verified in game: StringToBoolean, ValueToBoolean and
SpellBookItemLocation return the expected values, a 2D spline's midpoint
is (5, 10), an export stream round-trips 200 and 9, the sort manager
orders {3,1,2}, the linked list enumerates 0 1 2, ObjectUpdater,
Sequencer and SetUpAnimation finish, a smoothed status bar reaches 100,
and /framestack still opens.
2026-10-31 05:01:37 -05:00
Brues 1e1463cf9a feat(unit): UNIT_IN_RANGE_UPDATE and UNIT_DISTANCE_CHECK_UPDATE
UNIT_IN_RANGE_UPDATE (unitTarget, isInRange). Nothing in the client
reacts to a distance: the player moves every frame while it moves, and
other units in view are moved a little each frame between their movement
packets. So a world-tick pass checks the units, only while a frame is
registered for the event. The pass walks the event's subscriber chain
(Event::Custom::ForEachListener, which FireValues now uses too): a frame
registered with RegisterUnitEvent adds its units
(Frame::UnitEvent::Units), and a plain registration adds pet and each
party and raid member and their pets. A token fires when
Unit::Range::InRange changes for it. UnitInRange now calls the same
function. A filter unit that is not a unit token is dropped after one
protected IsUnitToken check, since the engine's resolver raises a Lua
error for it.

UNIT_DISTANCE_CHECK_UPDATE (unitTarget, isInDistance) is true while the
client holds a group member's object. UpdateRaidMemberRecord (0x004BADC0)
has four E8 callers, which are exactly a player object entering the
object table (CGPlayer_C::PostInit 0x005DEC43, PostUpdate on reactivation
0x005DECAF) and leaving it (the release slot 0x005E9ACF, ~CGPlayer_C
0x005DD6AB for an object never released). The calls point at a site that
notes a party or raid member's GUID (IsRaidMemberOrPet, not the active
player), and the next world tick fires for each of its tokens with
whether the object table holds it then. The release slot runs before the
manager moves the object to the released table, so a fire in place would
still show the member to UnitIsVisible. No loaded DLL references the
function or the sites.
2026-10-31 04:54:35 -05:00
Brues c21e44e086 feat(unit): UNIT_AREA_CHANGED fires when a group member changes zone
DiffPartyRecords (0x005E5510) already sets bit 0x80 when the zone in a
party record (+0x14) differs, but SignalPartyRecordChanges (0x005E5720)
raises nothing for it. The existing SignalSite redirects (the calls in
ReadPartyMemberStats and ComparePartyRecord, and the AddPartyMember tail)
now fire UNIT_AREA_CHANGED (unitTarget) on that bit, after the engine's own
events, once per token of the member.

The server sends the zone only to members that cannot see the player.
A member in view is built with the player's own zone (BuildPartyRecord
stores s_zoneId), the same zone GetRaidRosterInfo gives for a held object,
so ComparePartyRecord sets the bit when a member comes into view from
another zone. CGPlayer_C::PostInit skips ComparePartyRecord for the active
player, so "player" gets no event.
2026-10-31 04:25:36 -05:00
Brues e76616de83 feat(player): PLAYER_MOUNT_DISPLAY_CHANGED fires when the player's mount changes
1.12.1 reacts to a unit's new UNIT_FIELD_MOUNTDISPLAYID in
CGUnit_C::OnMountDisplayChanged (0x005FFA50): dismount from the old
display, mount the new one with the mount-up effect, refresh the loop
sound, quest marker and name. The field's type watcher
OnMountDisplayFieldChanged (0x00604570) resolves the unit and calls it
with the old value from one E8 call (0x0060459B), only on a real change.

That call now reaches a function that runs the handler, then fires
PLAYER_MOUNT_DISPLAY_CHANGED (no payload) when the unit is the player.
VanillaHelpers calls the handler directly after a local mount morph and
patches neither address, so a cosmetic morph fires nothing.
2026-10-31 04:15:13 -05:00
Brues 92794a1822 feat(unit): UNIT_TARGETABLE_CHANGED fires when a unit's selectability flips
1.12.1 reacts to a changed UNIT_FIELD_FLAGS in
CGUnit_C::OnUnitFlagsChanged (0x005FF580), which the flags field's type
watcher OnFlagsFieldChanged (0x006044B0) calls with the old flags from
one E8 call (0x006044DB). It handles looting, disarm, reaction, PvP and
the aura bit, but nothing reads UNIT_FLAG_NOT_SELECTABLE (0x02000000).

Unit::FlagsChanged now owns that call: it runs the handler, then each
subscriber with the unit and the flags before and after, since a call
site can be redirected only once. Unit::Targetable subscribes and fires
UNIT_TARGETABLE_CHANGED (unitTarget) once per token of the unit when the
not-selectable bit flips.
2026-10-31 04:07:26 -05:00
Brues ab0991f054 feat(unit): UNIT_CONNECTION fires when a group member goes on or offline
A party record's status byte (+0x08) carries the online bit
UnitIsConnected reads. 1.12.1 changes it in three places, and none
signals the flip:

- The party member stats packet: ReadPartyMemberStats (0x005E5110) ends
  in SignalPartyRecordChanges (0x005E5720) with the status change bit.
  The redirected call that already adds the generic power events now
  also fires UNIT_CONNECTION (unitTarget, isConnected) when the old and
  new records differ in the online bit.
- The group list (0x7D): the server reports a logoff only there.
  AddPartyMember (0x004E82D0) copies a kept member's previous record and
  sets the online bit, then stops. Its call now diffs the previous record
  against the stored one (DiffPartyRecords, 0x005E5510) and runs the same
  SignalPartyRecordChanges path, so the engine's status events and
  UNIT_CONNECTION follow.
- A raid member outside the player's party has only a raid slot, whose
  status byte RebuildRaidRoster (0x004BA5F0) sets from the same list. Its
  call now compares each returning member's online bit before and after
  and fires UNIT_CONNECTION on a flip; party members are skipped, since
  AddPartyMember ran first.

isConnected is a real boolean, pushed through FireValues.
2026-10-31 03:50:09 -05:00
Brues 26c201b95b fix(event): a named unit field gets a watch-copy slot first
Every unit-field watcher keeps a mirror of its bytes in the object's
watch copy, at the slot UnitWatchedIndex (0x0047DB20) finds for the field
in the table at 0x00839E48. A field not in the table gets 0xB6, past the
unit's 170-slot copy. UNIT_MOD_CAST_SPEED (139), named for
UNIT_SPELL_HASTE, is such a field, so every watcher on it wrote the
field over memory past the copy: a pet's cast-speed update on its
owner's logoff put a 1.0f over a list link, and ClntObjMgrRelease
crashed on the next SMSG_DESTROY_OBJECT (ERROR #132 at 0x00464A02).

The table holds 166 fields and one spare entry (0xB6, the copy's last
slot, which no field asks for); UnitWatchedIndex is its only reader and
nothing writes it. EngineName now writes a field without a slot into
that spare before naming its slot, and refuses the name once the spare
is taken. Field 139 takes it, so UNIT_SPELL_HASTE keeps the engine's
watcher for every unit.
2026-10-31 03:47:17 -05:00
Brues 09693af5b9 feat(unit): UNIT_POWER_UPDATE, UNIT_POWER_FREQUENT and UNIT_MAXPOWER
1.12.1 calls type-wide field observers for every unit whose watched
bytes change: ClntObjMgrSetTypeMirrorHandler (0x00468070) puts a record
on the global list of a (bank, field), and CGUnit_C::RegisterFieldWatchers
(0x006041F0) uses it for the engine's own unit handlers, among them
OnPowerFieldChanged on the power block, which only refreshes usability.

Two handlers join those lists, one record per POWER1..5 and MAXPOWER1..5
slot, so the callback's field offset is the power type. They fire
UNIT_POWER_UPDATE and UNIT_POWER_FREQUENT, or UNIT_MAXPOWER, with
(unitTarget, powerType) once per token of the unit. Every client power
change is a server update, so FREQUENT fires with UPDATE.

Each in-world registration pass removes and re-adds the records through
0x00468240: the first pass of a session runs in CGGameUI::InitializeGame,
after MirrorInitialize (0x0047F840) has rebuilt the tables a record's
copy offset comes from, and the removal keeps /reload from stacking a
second record. The list array has no other writer, so nothing frees a
record behind us.

A group member the client cannot see has no unit to watch; its power
comes in the party member stats packet. ReadPartyMemberStats (0x005E5110)
and ComparePartyRecord (0x005F0B80) end in SignalPartyRecordChanges
(0x005E5720), which fires the per-type power events for the changed
record bits. Both E8 calls now reach a function that calls it and then
fires the generic events for the same bits, the member's and its pet's.
2026-10-31 03:44:28 -05:00
Brues f24b7e594b feat(unit): UNIT_SPELL_HASTE fires when a unit's spell haste changes
1.12.1 turns unit-field changes into events by index: FUN_0051bbb0
watches unit field i when slot i of the static event-name array at
0x00BE1198 is named, and FUN_0051bd50 signals event i once per token of
the unit. UNIT_MOD_CAST_SPEED, the field UnitSpellHaste reads, is index
139 (OFF_UNIT_MOD_CAST_SPEED / 4), and slot 139 has no name, so the
engine never watched it.

Event::Custom::EngineName names slot 139, and the engine's own watchers
fire the event for every token. Nothing else signals 139 by number: it
is above the glue band and not in the chat-type event table.
2026-10-31 02:33:12 -05:00
Brues 35c8ba5688 docs(readme): list UNIT_TARGET 2026-10-31 02:28:00 -05:00
Brues e2a34bd18a feat(unit): UNIT_TARGET fires when a unit's target changes
1.12.1 already turns unit-field changes into events. FUN_0051bbb0
registers a watcher on unit field i for each named slot i of the static
event-name array at 0x00BE1198, and the watcher (FUN_0051bd50) signals
event i once per token of the unit through the broadcast FUN_00515e50.
The field index is the event id. UNIT_FIELD_TARGET is index 10, and the
watcher's size selector still gives it the 8 bytes of a GUID, but slot
10 has no name, so the engine never watches the field.

Event::Custom::EngineName names such a slot. It writes the name into the
static array at load, before any world init or unit watch. World init
copies the array into the live event table (0x0048FEA1), and the
engine's own watchers then fire the event for every token, with focus,
nameplateN, markN and focustarget included. The entry joins the
reservation list with a fixed slot, so it is documented, kept across
/reload, and not counted by Grow.

Slot 10 is in the glue band. Its one by-number signal is the glue
realm-list rebuild (0x0046E73D), which only CGlueMgr::Idle reaches.
2026-10-31 02:25:04 -05:00
Brues 2f787889f7 fix(animation): a frame's alpha group keeps its textures' gradients
When an alpha group starts on a frame, every region below it stores its
vertex alpha, and every update writes that alpha back. The colour getter
(0x77F8C0) reads a gradient back as white, and the setter (0x77F750)
shrinks a gradient's four entries to that one white entry. So a gradient
under a fading frame went flat at the first update and stayed flat after
the group ended. pfUI's easteregg night lost its fade to the bottom.

SetVertexAlpha now writes nothing when the alpha is unchanged. For one
colour entry the setter already does nothing then, so only the gradient
case changes. The frame's fade still reaches the gradient: a change of
the frame's alpha refolds each region's entries (0x77FAC0).

3.3.5's and 4.3.4's PreOnAnimUpdate drop the gradient the same way. A
texture that an alpha animation itself fades still loses its gradient.

Verified in game: a black gradient on a frame fading by -0.5 over 3 s
keeps its gradient during and after the fade.
2026-10-31 01:31:29 -05:00
Brues 9967cc0839 feat(lua): Spell objects, ContinuableContainer and TableBuilder
Ports from retail's Blizzard_ObjectAPI and SharedXML, in Blizzard's own
text, from the _forever_ build (the newest interface code on disk):
- Util/Spell.lua: Spell:CreateFromSpellID and SpellMixin.
- Util/ContinuableContainer.lua: one callback for a group of item and
  spell objects.
- Util/IndexRangeDataProvider.lua: CreateIndexRangeDataProvider, which
  ScrollBoxListView already expected.
- Util/TableBuilder.lua: CreateTableBuilder, for the existing
  ScrollUtil.RegisterTableBuilder.
- FrameXML/CallbackRegistrant: CallbackRegistrantMixin and
  CallbackRegistrantTemplate.
AsyncCallbackSystem.lua gets its ASYNC_SPELL type and SpellEventListener
back, so it is the _forever_ text again.

New in the DLL for SpellMixin:
- C_Spell.IsSpellDataCached, C_Spell.RequestLoadSpellData and
  SPELL_DATA_LOAD_RESULT. Every spell is client data, so a spell that
  exists is cached, and a request fires the event before it returns:
  (spellID, 1), or (spellID, nil) for an ID with no spell. Retail marks
  the event synchronous, and AsyncCallbackSystem relies on that.
- C_Spell.GetSpellDescriptionForItemLocation. The item tooltip expands a
  spell's text with the same arguments GetSpellDescription passes, so it
  returns that text. The item location is still required.

Verified in game: IsSpellDataCached(133) and (999999) are true and false,
Spell:CreateFromSpellID(133) calls back with (133, 1), a container with
item 19019 and spell 133 calls back, CreateIndexRangeDataProvider(5)
has size 5, and GetSpellDescriptionForItemLocation(133, slot 1) equals
GetSpellDescription(133).
2026-10-31 01:26:47 -05:00
Brues e47e881ae1 fix(event): FireValues applies RegisterUnitEvent filters
FireValues walks the subscriber chain itself and runs each OnEvent
through RunSlotWithValues, so it never reached the runner where
Frame::UnitEvent's gate sits. RegisterUnitEvent("UNIT_AURA_DELTA", unit)
fired for every unit's deltas.

Frame::UnitEvent::Accepts shares the gate's match. FireValues asks it
for each frame when the first value is a string, the same rule the
engine path uses for a %s arg1.
2026-10-31 00:21:18 -05:00
Brues d9da100110 feat(tradeskill): linked windows show the crafter's name
3.3.5's interface never shows whose profession a linked window holds.
Port 4.3.4's TradeSkillLinkNameButton and TradeSkillFrame_SetLinkName
to TradeSkillFrame and CraftFrame: "[name]" after the title, and a
click on it starts a whisper. The title moves left by half the name,
from its own anchor, so Turtle's -30 offset stays.
2026-10-30 22:48:40 -05:00
Brues 00cfe0c45b fix(smf): BackFill and RemoveMessagesByPredicate keep the engine's ring
A ring that is not full holds records 0..count-1: the engine's writer
fills them in order from an empty ring, and only a full ring wraps.
ScrollOffset and ScrollToOffset wrap by the count, and ScrollToTop
(0x00788690) lays out from record 0 unless the ring is full, so each one
is right only for that layout.

BackFillMessage wrote the new oldest message to the record before the
oldest, as 4.3.4's addToTop does. In a ring that is not full, that record
wraps to the end of the array. From then on, GetScrollOffset,
SetScrollOffset, ScrollByAmount and ScrollToTop read the wrong offset.
pfUI's chat wheel scrolled up into the backfilled lines and then could
not scroll back down.

RemoveMessagesByPredicate compacted from the oldest's record, so after a
removal from a full ring the kept messages began anywhere in the array.

BackFillMessage now rotates records 0..count by one, so the free record
comes round to 0, and writes the message there. RemoveMessagesByPredicate
first turns the ring so that the oldest is record 0, then compacts. Whole
records move, so every text keeps one owner. Clear leaves a free record's
old text for the writer to free. The extra-argument tables and the scroll
record (OFF_SCROLLINGMESSAGEFRAME_SCROLL_RECORD, +0x348) move with their
records. A scrolled-up frame is laid out again from its moved scroll
record, so the view stays.

A model of the engine's three functions agrees on 377,485 random
add, backfill, remove and scroll states. Not yet verified in game.
2026-10-30 22:36:53 -05:00
Brues d92464b86c feat(tradeskill): trade links follow 3.3.5
Profession links are now built and opened the way 3.3.5's
CGTradeSkillInfo does it. A received link opens in the engine's own
TradeSkillFrame. The ClassicAPI viewer is gone.

The link is 3.3.5's format:
trade:<spellID>:<rank>:<maxRank>:<GUID>:<bits>|h[<spell name>]. The
first field is the profession spell, not the skill line. The GUID
replaces the name. A reader whose name cache does not hold the linker
sends the name query and opens the link when the answer arrives. The
bits cover every SkillLineAbility row of the profession, as 3.3.5's link
run does. 1.12's DBC is sorted by ID and does not group a profession's
rows into one run, so the rows here are taken in ID order. A link opens
only when the reader's row count matches it.

The 1.12 list build (0x004FCA20) is 3.3.5's RefreshList without the
link branch. Three call-site patches add that branch:
- the spell list comes from the link,
- the ability rows use the linker's race and class,
- the rank is the linker's.
Two patches on TryCastSpell's toggle calls record the cast spell (3.3.5's
m_spellID). They also make a cast while a link shows open the player's
own list instead of closing the window. The game shutdown drops the link,
as 3.3.5's does.

Enchanting gets the same in the Craft window. Its rows are filtered by
castUI, because its recipes have no TRADESPELL bit. GetCraftListLink and
IsCraftLinked are the Craft window's twins of the 3.3.5 functions.
GetTradeSkillLine, GetCraftDisplaySkillLine and GetCraftName give the
linker's values while a link shows. Util/TradeSkillLink.lua now ports
3.3.5's linked mode, which hides Create, Create All and the count
controls, and keeps the link buttons.

Any spell whose Effect[0] is TRADE_SKILL can be linked. 1.12's
SkillLine.dbc has no canLink column.

Removed: C_TradeSkillUI.GetTradeSkillListLink, GetCraftListLink and
GetTradeSkillListRecipes. Old links no longer open.

Not yet verified in game.
2026-10-30 22:16:16 -05:00
Brues fec127c1af docs(item): DoesItemExistByID is true for any positive ID
The entry said a cache miss returns false and starts a load. The
function returns true for any positive item ID, cached or not, and
loads nothing. ContinueOnItemLoad depends on that.
2026-10-30 21:47:34 -05:00
Brues 37ee71c663 feat(item): C_PaperDollInfo.GetTemporaryEnchantmentInfo
Retail's per-slot temporary enchant, the function its deprecated
GetWeaponEnchantInfo is now built from. It reads the same temporary
enchant slot as C_Item.GetItemTempEnchantInfo, in retail's shape: an
INVSLOT_ number in, and a TemporaryItemEnchantInfo table out (enchantID,
remainingTimeMs, chargesRemaining, hasExpirationTime), or nothing when
the slot has no temporary enchant. A slot outside 1..19 also returns
nothing, so the engine never sees it.

hasExpirationTime is the descriptor duration gate that the shared reader
already tested before it asked for the time left.

C_Item.GetItemTempEnchantInfo stays as the ClassicAPI extension for a
weapon in a bag (#47). The docs link the two.
2026-10-30 21:20:05 -05:00
Brues 6259e22480 feat(lua): ItemUtil from retail
Util/ItemUtil.lua is now the ItemUtil table of retail
Blizzard_FrameXMLUtil/ItemUtil.lua, in retail's own text. As its header
lists, it leaves out ItemButtonUtil and DoesAnyItemSlotMatchItemContext
(retail drives them from frames this client does not have), the transmog
mixin, the currency path of GetItemDetails, and GetCraftingReagentCount
(reagent and account banks).

New for what it calls:
- Enum.BagIndex in the DLL, with Classic Era's names and this client's
  indices: Keyring -2, Bank -1, Backpack 0, Bag_1..4 = 1..4 and
  BankBag_1..6 = 5..10. Era's bank bags start at 6, after its reagent
  bag. The indices live in Offsets.h now, and container/Search.cpp drops
  its local copies.
- C_PaperDollInfo.GetInventorySlotInfoForInvSlot in the DLL. It takes the
  first PaperDollItemFrame.dbc row with that SlotNumber, and walks the
  rows the way the engine's GetInventorySlotInfo (0x004C81B0) does.
- C_Container.GetContainerNumSlots and C_Container.PickupContainerItem as
  Lua aliases of the stock globals in Compat.lua, next to
  C_ActionBar.ShouldShowKeyring, which is always true.
- ContainerFrame_GetContainerNumSlots and NUM_TOTAL_BAG_FRAMES from
  retail's ContainerFrame.lua, and GameTooltip_SuppressAutomaticCompareItem.
  Nothing reads that flag, because nothing compares items automatically.

docs/API.md covers all of it, plus Item objects and
C_Item.GetItemIDForItemInfo.

Verified in game: Enum.BagIndex.Keyring is -2, the backpack has 16 slots,
ShouldShowKeyring is true, slot 18 returns the ranged row with checkRelic
true, GetEmptyEquipSlotTooltip(1) is "Head", and FilterOwnedItems({6948})
finds a Hearthstone in the bags.
2026-10-30 21:12:37 -05:00
Brues 474da1a5b5 feat(lua): Item follows retail
Util/Item.lua is now retail Blizzard_ObjectAPI/Mainline/Item.lua in
retail's own text, and its listener is retail's AsyncCallbackSystem.lua
with the item and quest listeners. There is no spell listener: every
spell is client-side data here, so there is nothing to wait for. The one
other difference is that GetItemQualityColor reads ITEM_QUALITY_COLORS,
the same entry retail's ColorManager returns.

What follows retail now:
- Load callbacks get (id, success).
- An item callback also runs when the load fails, with success nil.
  TradeSkillLink's two callbacks now stop on a failure, because
  re-rendering would request the missing item again.
- C_Item.RequestLoadItemDataByID runs once per item, not once per
  callback.
- New methods: GetStackCount, ContinueWithCancelOnRecordLoad and
  IsRecordDataCached. ContinueOnItemLoad's usage errors name the bad
  itemID or link, and GetItemGUID returns the GUID an item was made from.

C_Item.GetItemIDForItemInfo is new in the DLL for ItemMixin:GetItemID's
fallback. It uses the resolver that GetItemInfoInstant uses.

Verified in game: Item:CreateFromItemID(19019) calls back with
(19019, 1), and C_Item.GetItemIDForItemInfo("item:6948") returns 6948.
2026-10-30 21:12:22 -05:00
Brues 6cee968a8a refactor(lua): ItemUtil.lua is Item.lua
The file holds retail's Item mixin (Blizzard_ObjectAPI/Mainline/Item.lua)
and its ItemEventListener, not retail's ItemUtil, so it takes Item.lua's
name. No code changes.
2026-10-30 21:12:07 -05:00
Brues 635c74d518 fix(smf): ScrollByAmount stops where ScrollUp stops
ScrollByAmount moved the offset straight to the clamped target, and the
clamp is retail's count - 1, where the oldest message sits alone on the
bottom line under empty space. 1.12's own ScrollUp (0x788610) stops
sooner, at +0x350 (4.3.4's m_atTop), which the layout sets once every
message back to the oldest fits the height (0x788A37). A chat wheel
built on ScrollByAmount (pfUI's) scrolled chat up until it was nearly
empty.

The engine has two scroll families, in 1.12 and 4.3.4 alike: ScrollUp
and PageUp stop at m_atTop, and ScrollToTop and SetScrollOffset go to
the oldest record. Retail defines ScrollUp as ScrollByAmount(1) and
ScrollToTop as SetScrollOffset(GetMaxScrollRange()), so ScrollByAmount
now steps the engine's ScrollUp / ScrollDown (0x788610 / 0x788650), the
loop PageUp (0x7885B0) runs, and SetScrollOffset / GetMaxScrollRange
keep count - 1. The clamped target still bounds the steps: a hidden
frame never lays out, so its ScrollUp never finds the top and wraps.

Verified in game: ScrollByAmount(1000) on ChatFrame1 stops with the
oldest message on the top line and an offset below GetMaxScrollRange().
2026-10-30 19:56:21 -05:00
Brues 260d40f49b fix(frame): let the engine runner parse script formats
Frame::ScriptArgs carried its own copy of the script runner's format
switch (0x704F10, %d/%u/%f/%s) so it could pass positional args.
SuperWoWhook extends the live switch at runtime: it points 'e' at a new
jump slot (0x7052CC) that pushes registry[ref] for a 4-byte ref, and
fires CREATE_CHATBUBBLE with "%e%s". Our copy skipped 'e' without
consuming its value, so %s read the ref as a string pointer and
crashed in lua_pushstring (0x6F38A5) for any handler that declares
parameters.

Both runners now run unchanged, and only their own lua_pcall is
redirected (0x705199, 0x704E79) through a thunk that reads the handler
ref, frame and arg count from the runner's frame. RunnerPCall reads
arg1..argN back from the globals the runner set and passes them as
(self, [event,] arg1..argN [, trailing]). The format parser and both
runner reimplementations are gone; RunCore remains for value fires.

Format fires now keep the runner's 19-argument limit and its
lua_gettable saves of this/argN, as vanilla handlers always had. No
engine or ClassicAPI format has more than 12 values; value fires
(FireValues, RunWithValues) are unchanged.

Verified in game: a RegisterAllEvents frame with a modern OnEvent
crashed on a chat bubble with the old build and prints
CREATE_CHATBUBBLE and the speaker GUID with this one.
2026-10-30 15:54:53 -05:00
Brues 8f6ff33a39 refactor(lua): CallbackRegistry in retail's own text
6cc9d0d already gave CallbackRegistry retail's behavior; the file is now
retail Blizzard_SharedXMLBase/CallbackRegistry.lua in retail's own syntax
(select("#", ...), `...` forwarding, retail's comments), with three
differences noted in the header:

- No AttributeDelegate: 1.12 has no taint or SetForbidden, so
  SecureInsertEvent and GetMutableCallbacksByEvent do the delegate's
  work directly.
- TriggerEvent calls securecallfunction from its own loops instead of
  handing secureexecuterange a vararg helper, which in Lua 5.0 would
  build an `arg` table per callback per event.
- UnregisterEvents uses table.wipe; 1.12 has no global wipe.

The one behavior change: TriggerEvent on a registry with no Event table
and undefined events disallowed now fails on self.Event as retail does,
instead of with the "doesn't exist" message. EventRegistry, and registries
derived from it, allow undefined events.

Verified in game: a closure gets its bound argument and a leading nil
payload, an erroring callback goes to the error handler while the others
run, a callback registered mid-dispatch runs from the next trigger, and
UnregisterEvents clears every callback.
2026-10-30 14:01:40 -05:00
Brues 5082f3c829 feat(lua): TableUtil follows retail
The file is now retail Blizzard_SharedXMLBase/TableUtil.lua in retail's
own syntax: the length operator, `...`, select, math.huge, table.wipe and
5.1's unpack(t, i, j) all work here now.

New from retail: TableUtil.SafeCountTable / SafeCountIndexTable,
tInvertToArray and CollectTableDifferences. Fixed by following retail:
TableUtil.Transform returned after the first value, ContainsAllKeys now
also fails on a key only the second table has, and SafeUnpack honors its
startIndex. TableUtil.ExecuteOnKeys stays as the one addition retail does
not have.

Verified in game: ContainsAllKeys, Transform, SafePack / SafeUnpack from
index 2, GetTableValueListFromEnumeration over ipairs,
CollectTableDifferences, SafeCountTable and ExecuteOnKeys all return the
expected values.
2026-10-30 13:57:09 -05:00
Brues 5d0568f759 feat(lua): Pools follows retail, with securecallmethod
Pools.lua is now retail Blizzard_SharedXMLBase/Pools.lua, on the
SecureTypes and ProxyUtil ports the Menu backport already uses.
CreateObjectPool, CreateFramePool and the rest alias the secure variants
as on retail, so they return proxies that expose only the pool methods.
CreateFramePool takes retail's (frameType, parent, template, resetFunc,
forbidden, postCreate, capacity); a table specialization goes through
FrameUtil.SpecializeFrameWithMixins; CreateObjectPool works without a
reset function; Pool_HideAndSetToDefaults is new. The ClassicAPI-only
CreateUnsecuredActorPool and CreateUnsecuredFontStringPoolCollection are
gone (nothing used them).

Two differences, noted in the header: no secret-value check on release
(1.12 has no secret values), and a forbidden pool makes normal frames
(no CreateForbiddenFrame).

The TOC loads SecureTypes and ProxyUtil before Pools, as retail's does;
Pools reads both at load.

SecurePoolCollectionMixin:Release calls securecallmethod, now in
src/baselib/SecureCall.cpp next to securecallfunction, on both Lua
states: object[method](object, ...) with a raw lookup, an error goes to
the error handler and the call returns nothing. That follows retail's
API documentation; it is not probed. docs/API.md covers it.

Verified in game: securecallmethod returns the method's result, a frame
pool hides its internals behind the proxy while acquire and release keep
the count, and a frame pool collection runs a table specialization's
OnLoad, acquires, and releases through securecallmethod.
2026-10-30 13:53:24 -05:00
Brues 9a78e159e7 feat(lua): FrameUtil follows retail
The file is now retail Blizzard_SharedXMLBase/FrameUtil.lua. New from
retail: FrameUtil.RegisterUpdateFunction / UnregisterUpdateFunction,
DialogStyleGlobalMouseDown, SpecializeFrameWithMixins /
ReflectStandardScriptHandlers, RegisterForVariablesLoaded,
FrameUtil.CreateFrame, UpdateScaleForFit / UpdateScaleForFitSpecific,
GetScaledCenter, FitToParent, RegisterForTopLevelParentChanged /
UpdateTopLevelParent and AnimTransitionMixin. RegisterFrameForUnitEvents
forwards `...` as retail does.

AnimTransitionMixin runs on retail's Blizzard_SharedXML/
ScriptAnimationUtil.lua, ported verbatim. Its ShakeFrame scales by
retail's ShakeStrengthUI cvar, which src/ui/ShakeStrength.cpp registers
with retail's help, category and default ("1.000000"); nothing in the
engine reads it.

Not ported: the fade and flash functions, which 1.12's own UIParent.lua
defines and UIParent's OnUpdate drives (Turtle has also changed them);
RegisterFrameForEventCallbacks and its two siblings (no
frame:RegisterEventCallback); ApplyDefaultScale (no GetDefaultScale).
SetParentMaintainRenderLayering does not carry the window: 1.12 has one.

README.md lists FrameUtil, ScriptAnimationUtil and the cvar.

Verified in game: SpecializeFrameWithMixins sets and calls OnLoad and
OnShow with the frame, a SlideLeft StartAnimIn ends at its anchor
(CENTER 0 0), and ShakeFrameRandom with ShakeStrengthUI at 1.000000
returns its cancel function.
2026-10-30 13:53:15 -05:00
Brues 503368623f feat(localization): BreakUpLargeNumbers, AbbreviateNumbers, AbbreviateLargeNumbers
Retail's number formatters (LocalizationDocumentation.lua) and
C_StringUtil.GetDefaultAbbreviationBreakpoints. Retail moved them from
FrameXML into C in 12.0.0, so the behavior is taken from probes of an enUS
retail client, recorded in src/localization/Numbers.cpp:

- BreakUpLargeNumbers drops the fraction of a whole number or one 1000 or
  more in size and groups it with LARGE_NUMBER_SEPERATOR while the
  breakUpLargeNumbers cvar (retail's, default on) is set; other numbers
  keep one decimal, rounded half away from zero. natural writes a million
  or more in words ("1.2 million", "123 million").
- AbbreviateNumbers walks retail's default breakpoints, or
  options.breakpointData, or the Asian table for options.locale koKR /
  zhCN / zhTW. Retail's defaults name THIRD_ and FOURTH_NUMBER_CAP_NO_SPACE,
  which its clients do not define, so billions and trillions carry no
  letter there and here.
- AbbreviateLargeNumbers walks FrameXML's old thresholds, rounds to a whole
  number outside the Asian locales, and falls back to BreakUpLargeNumbers.

The asian natural-word scales (1e4 / 1e8 / 1e12) are read off the strings,
not probed. options.config (CreateAbbreviateConfig) is not backported.

Every locale file, and a new koKR.lua, gets DECIMAL_SEPERATOR, FIRST/SECOND_NUMBER_CAP[_NO_SPACE]
and FIRST..FOURTH_NUMBER from the matching Classic GlobalStrings; the
German, Spanish and French words carry |7 plural tokens, which the grammar
pass does not expand yet.

FormattingUtil gains retail's GetCostString and GetItemCostString on top.

docs/API.md documents the four functions, the cvar and
Constants.MoneyFormattingConstants; README.md lists them.

Verified in game: every probed retail value reproduces exactly (BreakUp
with and without natural, AbbreviateNumbers with defaults, Asian locale
and custom breakpoints, AbbreviateLargeNumbers), the cvar toggles the
separators, and GetItemCostString shows the amount and item icon.
2026-10-30 13:33:40 -05:00
Brues 735d304a20 feat(currency): Constants.MoneyFormattingConstants and GetMoneyString's gold threshold
Retail exposes engine constant tables as Constants.<Name>, documented with
Type "Constants" and a Values list (MoneyConstantsDocumentation.lua).
Game::Lua::RegisterConstants builds Constants[sub] with the same integer
entries RegisterIntegerEnum takes, and the documentation recorder has a
constants kind next to the enum kind, so the API browser lists the table as
constants rather than as an enumeration.

Constants.MoneyFormattingConstants.GOLD_REWARD_THRESHOLD_TO_HIDE_COPPER is
10, retail's value. FormattingUtil's GetMoneyString now applies
checkGoldThreshold through retail's FormatDisplayCopper: above 10 gold the
copper is dropped.

Verified in game: the table is present, GetMoneyString(1234567, nil, true)
shows gold and silver only, and GetMoneyString(51234, nil, true) keeps its
copper.
2026-10-30 13:17:01 -05:00
Brues 29ddd78a80 feat(lua): FormattingUtil follows retail
The file is now retail Blizzard_SharedXML/FormattingUtil.lua (identical in
retail, Classic and Classic Era), in retail's own syntax: the length and
modulo operators and string methods all work here now.

New from retail: FormatValueWithSign (with SYMBOLIC_NEGATIVE_NUMBER "-%s" /
SYMBOLIC_POSITIVE_NUMBER "+%s", the same in every locale's GlobalStrings),
MoneyStringConstants, FormatPercentageRounded,
GetHighlightedNumberDifferenceString, FormatUnreadMailTooltip,
FormattingUtil.AddLeadingZeroes, ReplaceGenderTokens, and GetMoneyString's
color argument.

GetMoneyString gives the coin-icon form, retail's default; retail uses the
text-symbol form only under its colorblind mode, which 1.12 does not have.
checkGoldThreshold is still not applied (it needs
Constants.MoneyFormattingConstants), and GetCostString / GetItemCostString
wait on BreakUpLargeNumbers / AbbreviateNumbers. GetCurrencyString and
GetCurrenciesString are not ported: 1.12 has no currencies.

Verified in game: coin-icon money strings with and without thousands
separators, signed values, FormatLargeNumber, the highlighted number
difference, and gray leading zeroes.
2026-10-30 13:05:13 -05:00
Brues b6c21216e3 fix(lua): EventUtil follows retail; queued variables-loaded callbacks are error-isolated
TriggerOnVariablesLoaded ran the ContinueOnVariablesLoaded queue in a plain
loop, so one erroring callback skipped the rest, and the queue drains only
once, so they never ran that session. It now uses secureexecuterange as
retail does: each error goes to the error handler and the walk goes on.

AreVariablesLoaded reads UIParent.variablesLoaded, as on retail, instead of
a private flag. Retail's UIParent sets that field and calls
TriggerOnVariablesLoaded on VARIABLES_LOADED; 1.12's FrameXML does
neither, so EventUtil's own frame does both.

The header no longer says 1.12 lacks select, C_AddOns or
secureexecuterange; ClassicAPI provides all three. The unknown-event
message uses :format and IsEmpty uses #, as on retail.

Verified in game: AreVariablesLoaded and UIParent.variablesLoaded are
true, a late ContinueOnVariablesLoaded callback runs at once, IsEmpty
works, and ContinueAfterAllEvents rejects an unknown event.
2026-10-30 12:58:01 -05:00
Brues 6cc9d0db90 fix(lua): CallbackRegistry isolates callback errors and defers mid-dispatch registrations
TriggerEvent called each callback directly, so one error left the frame's
OnEvent script and skipped every callback after it in that dispatch. pfUI
now runs many listeners through one EventRegistry dispatch, so one failing
listener could silence the rest. Each callback now runs through
securecallfunction: the error goes to the engine's script error handler and
the loop goes on, which is retail's secureexecuterange contract. It is
called from TriggerEvent's own loop, not through a vararg helper, because a
vararg Lua function allocates an arg table per call on Lua 5.0.

A callback registered for an event while that event is dispatching now
waits in deferredCallbacks and joins after the outermost dispatch, as on
retail. Before, its key went into the table the pairs loop was walking.
UnregisterCallback clears only owners that are present, and drops pending
deferrals.

The rest now follows retail Blizzard_SharedXMLBase/CallbackRegistry.lua:
UnregisterEvents() clears every event and UnregisterEventsByEventTable
clears the listed ones; GenerateCallbackEvents checks its argument; the
file's own GenerateClosure copy gives way to FunctionUtil's global (one
table per call instead of two, with retail's owner + 4 argument limit).

EventRegistry:OnLoad keeps all instance state, since addons derive their
own registry from the instance (pfUI: CreateFromMixins(EventRegistry)).

Verified in game: an erroring callback reports to the handler and the next
one still runs; a callback registered mid-dispatch first runs on the next
TriggerEvent.
2026-10-30 12:49:21 -05:00
Brues c6c201e575 fix(text): auto-height font strings keep their last line past 4 KB
A font string with no height of its own is as tall as its text, and that
height (0x5C2070) is a product, n * fontHeight + (n - 1) * gap. FitText's
count of what fits (0x5C21C0) adds the lines up as a running float sum and
stops at the first line where blockHeight + 2^-20 < sum + fontHeight. Over
many lines the sum drifts from the product by more than 2^-20 at most UI
scales, the last line "does not fit", and FitText cuts the text to its
first 4092 bytes plus "...", with the rest of the box blank. A multi-line
edit box hit this once its text passed 4 KB (ScrollingEditBoxTemplate,
pfUI chat copy).

4.3.4 keeps the product and grows the margin per line: blockHeight +
numLines * 2^-20 (GxuFontGetMaxCharsWithinWidthAndHeight). Text::FitHeight
replaces the loop's fadd of the engine's 2^-20 with a thunk that adds
numLines times it. The first line keeps 1.12's margin; each further line
adds a millionth of the screen height, so real overflow is still cut. A
float32 model of the chain lost the last line in 1276 of 3000 multi-line
fits before and in none after; in game a 30783-byte copy box draws all of
its text.
2026-10-30 11:39:02 -05:00
Brues 77b304ae68 feat(smf): RemoveMessagesByPredicate
ScrollingMessageFrame:RemoveMessagesByPredicate(predicate), retail's: the
predicate is called with each message's GetMessageInfo values, oldest
first, and the messages it returns true for are removed; the rest keep
their order. It covers 4.3.4's RemoveMessagesByAccessID / ByExtraData,
whose int fields the retail-shaped records here do not have.

1.12's ring has no compaction of its own; the removal is 4.3.4's
RemoveLines loop over it: every kept record moves forward in ring order to
the first free slot (freeing the text it lands on, nulling the one it
left), the position moves back by the removed count, and the
extra-argument tables move with their records. Then the engine's own
layout (0x00788750) from the record at the kept scroll offset, clamped to
the oldest, and its re-arm (0x00788B80) - a layout at the bottom keeps the
fade state, so 4.3.4 re-arms after - or its Clear (0x007882B0) when
nothing is kept.

The predicate runs for every message before anything moves, through the
engine's error handler; a predicate that errors keeps that message, as
retail's safesecurecall does. GetMessageInfo shares its record lookup and
value push with it.
2026-10-30 02:14:08 -05:00
Brues c965e49117 feat(smf): BackFillMessage
ScrollingMessageFrame:BackFillMessage(text, r, g, b, ...), retail's: the
message becomes the oldest, for rebuilding a frame from history newest to
oldest (Blizzard_CombatLog's refilter adds each entry with it).

The ring's writer 0x00788150 has one slot rule: the one after the newest.
BackFillMessage writes the slot 4.3.4's AddMessage(..., addToTop) picks —
the free one before the oldest, (pos - count + 1) mod max once the count
has grown — and fills the record as the writer does: a Storm copy of the
text, AddMessage's colour (clamped, x255 + 0.5 truncated, alpha 0xFF; the
font's without r, g, b), shown, the frame's two times, id 0, and the extra
arguments kept for GetMessageInfo. Nothing already in the ring moves, so a
scrolled-up frame keeps its view; at the bottom the lines are laid out
again from the newest, as the writer does.

A frame at its line limit drops the message, as retail's CircularBuffer
PushBack does ("Won't overwrite front"); 4.3.4 overwrites the oldest slot
there, which Blizzard_CombatLog never reaches.
2026-10-30 01:45:47 -05:00
Brues ead52e79ce fix(editbox): caret, selection and click rows follow tall inline icons
A multi-line edit box places its caret, selection pieces and a click's
cursor by rows of one height (font height + spacing, pixel-aligned), while
the render moves a line holding an icon taller than the font, and every
line after it, down by the overflow, and the box grows to match. Below the
first tall-icon line the caret and highlight sat above their text, and
OnCursorChanged reported that y, so ScrollingEditBoxMixin's scroll-into-
view stopped short (pfUI chat copy with faction emblems).

4.3.4's CSimpleEditBox has the same fault: UpdateVisibleCursor,
UpdateHighlightArea and ConvertCoordinateToIndex are icon-blind too. So
this goes past 4.3.4, as editbox/CharClass does. EditBox::IconRows co-hooks
the three placers and gives each the render's move, from the new
Text::InlineTexture::LineIconShift over the box's own line table: the
click's y is mapped onto the uniform row before the engine reads it; the
selection piece and caret are re-anchored after, with the engine's own x;
the caret's OnCursorChanged is muted for the original call and fired once
with the corrected y through the engine's forwarder, with the same packing
PlaceCaret uses (verified in the disassembly and the binary's constants).

Also fixes the "caret positioner" misnomer for 0x77DE70 (the selection-
piece placer) in Offsets.h and the docs.
2026-10-30 01:15:01 -05:00
Brues 7cb6cda101 feat(smf): TOP insert mode
SetInsertMode(SCROLLING_MESSAGE_FRAME_INSERT_MODE_TOP) now shows the
newest message at the top, older ones below it, as retail's mixin does.

1.12's line layout anchors each line once, when it makes it, through one
SetPoint call (0x00788975). That call is redirected: lines of a TOP frame
take the TOP anchors, every other line keeps the engine's own arguments.
The layout remakes the lines when the frame resizes, so the redirect
covers that too. A mode change re-anchors the existing lines with the
layout's own steps and refreshes the display.

Insert mode moves out of Scroll.cpp into InsertMode.cpp.
2026-10-30 00:20:19 -05:00
Brues 5ab497f2c7 feat(smf): scroll offset, insert mode, display-refreshed callbacks
Retail's ScrollingMessageFrame SetScrollOffset, GetScrollOffset,
GetMaxScrollRange, ScrollByAmount, SetInsertMode / GetInsertMode with the
SCROLLING_MESSAGE_FRAME_INSERT_MODE_* globals, and
AddOnDisplayRefreshedCallback, which ScrollUtil's
InitScrollingMessageFrameWithScrollBar calls.

The offset is the engine's own: SetScrollFromBottom's body (0x00788700)
is 4.3.4's SetScrollOffset step for step, and GetCurrentScroll is
GetScrollOffset under retail's name. The setters clamp to
0..GetNumMessages()-1 first, as retail does; the engine wraps. 1.12's
layout stacks lines bottom-up only, so the insert mode is BOTTOM and
SetInsertMode raises an error for anything else.

The callbacks run after the frame's own update (0x00788460, OnUpdate then
the fader), where retail's OnPostUpdate runs them, for a frame the line
layout, AddMessage or ScrollByAmount marked. The layout hook moves out of
Text::InlineTexture into ScrollingMessageFrame::Layout, which owns it and
fans out to both.
2026-10-29 23:56:24 -05:00
Brues 205d1fd43b feat(smf): ScrollingMessageFrame GetMessageInfo
Retail's smf:GetMessageInfo(index): text, r, g, b, then every argument
AddMessage took after the colour. Index 1 is the oldest message, and an
index outside 1..GetNumMessages() returns nothing.

The text and colour come from the engine's record in the frame's message
ring, so UpdateColorByID's changes read back. The record keeps only an
integer id after the colour, so AddMessage is registered again over the
engine's: Storm's hash links a new method node at the head of its bucket
and the lookup takes the first match. It runs the engine's AddMessage,
then keeps the extra arguments for the record just written, in a
registry table reused per record.
2026-10-29 23:43:45 -05:00
Brues 950c9deb76 feat(death): C_DeathInfo self-resurrect options, SELF_RES_SPELL_CHANGED
C_DeathInfo.GetSelfResurrectOptions, C_DeathInfo.UseSelfResurrectOption
and Enum.SelfResurrectOptionType over what 1.12 already serves through
HasSoulstone and UseSoulstone. Both pick one option the same way:
PLAYER_SELF_RES_SPELL when the server set it, else the first carried
item whose on-use spell is a self-resurrect. The list holds that option
under HasSoulstone's alive gate, and using it calls the engine's
UseSoulstone. Nothing in 1.12 limits a self-resurrection, so canUse is
true, isLimited false and priority 0.

SELF_RES_SPELL_CHANGED is 4.3.4's watcher on PLAYER_SELF_RES_SPELL from
SetActiveMirrorHandlers. 1.12 watches no such field, so the watcher joins
CGPlayer_C::AddActiveWatchers and leaves before its removal, the lifetime
of the engine's own player watchers.
2026-10-29 20:37:40 -05:00
Brues e7ccc11309 feat(unit): UnitHasIncomingResurrection, INCOMING_RESURRECT_CHANGED
4.3.4's CGIncomingResurrection. SMSG_SPELL_START adds a resurrect cast
under its object target, a unit or a corpse. SMSG_SPELL_GO, the failure
packets and ClearCastingSpell (through Spell::Cast, Turtle's only
interrupt signal) end it. A cast whose caster leaves view never reports
its end, so it ends on the next world tick. Each change fires the event
for every token naming the target, or the corpse's owner. 1.12's class
resurrections carry effect 113, not 4.3.4's 18, so both count.

Object::Corpse::ByOwner, lifted from spell/Range.cpp, now skips bones as
4.3.4's ClntObjMgrFindCorpseByOwner does. Turtle's bones keep their
owner, so old bones hid a ghost's live corpse, from this API and from
the range check's ghost redirect.

HasEffect moves from CombatLog to Spell::Lookup, and the SpellCastTargets
object mask 0x8A02 becomes one Offsets.h constant.
2026-10-29 19:21:47 -05:00
Brues bab31b5f7b docs(unit): bound the GetShapeshiftForm example to the bar
GetShapeshiftForm returns the bar count + 1 for a form that is not on
the stance bar, as 3.3.5 and 4.3.4 do. The example passed that index to
GetShapeshiftFormInfo, which returns nils for it.
2026-10-28 23:31:49 -05:00
Brues e0e24bab34 feat(macro): SetMacroDisplay range unit
C_Macro.SetMacroDisplay(macroSlot, value [, unit]) takes the unit the
button's range check uses, so a publisher's [@unit] reaches the range
check as SetMacroSpell's target does. The token stays a token: each
lookup resolves it again, so the range follows a new mouseover, focus or
target with no republish. A token that names no unit leaves the target
in charge.

The engine's resolver vets the unit at publish and raises its "Unknown
unit name" error for anything else, as UnitExists does. It tells a
token's family from its spelling alone, so a token that passes once
never raises at a later lookup. The unit is ignored for false and for an
empty value, and a publish that changes only the unit updates it.
2026-10-28 23:19:36 -05:00
Brues a46d823b01 feat(quest): completed quests on Turtle-lineage servers
QueryQuestsCompleted, GetQuestsCompleted, C_QuestLog.IsQuestFlaggedCompleted,
C_QuestLog.GetAllCompletedQuestIDs and QUEST_QUERY_COMPLETE, on Turtle clients
only. The server answers `.queststatuses` with TWQUEST guild addon messages
from the player, split at 2000 characters; the shorter last message is the
end of the list, so no timers are needed.

The DLL sends the request itself on SMSG_LOGIN_VERIFY_WORLD (the earliest
request the server answers), after each turn-in, and from
QueryQuestsCompleted. It reads every answer at the packet funnel, checks that
the sender is the player, replaces the list and fires QUEST_QUERY_COMPLETE.
A turned-in quest goes into the list at once; the server's next answer takes
repeatable quests out again. The list lives through /reload.

Net::OutPacket replaces the two hand-built CDataStore senders (item cache
resend, SetPVP). Replaces the closed Lua collector of PR #86.
2026-10-28 21:42:15 -05:00
Brues 38337c841d feat(container): SetItemSearch, IsContainerFiltered
Port of 4.3.4's bag search (CGContainerInfo): C_Container.SetItemSearch,
C_Container.IsContainerFiltered and INVENTORY_SEARCH_UPDATE. An item
matches on its equipment sets' names, its suffixed name, its subclass
short name or its equip slot name, case- and accent-folded per locale.
The keyring is searched; non-ASCII search text is folded whole.

C_Container.GetContainerItemInfo now reports isFiltered and takes an
optional table to fill and return, so bag addons can read every slot
without a new table per call. Item::Location::ResolveBagArgs resolves
the caller's own bag/slot args without wiping the stack.
2026-10-28 20:56:52 -05:00
Brues 5a0b4f2e31 feat: GetTradeSkillDescription, GetTrainerServiceItemLink
Both mirror 3.3.5 (0x005DBE10, 0x00596290).

GetTradeSkillDescription: nil unless the row's recipe has a description
in the client's locale, then 1.12's spell-text parser with the arguments
GetCraftDescription passes. That call moves to Spell::Description::Expand,
shared with C_Spell.GetSpellDescription.

GetTrainerServiceItemLink: a 1.12 server sends the trainer spell that
teaches the recipe, not the recipe. Follow its first LEARN_SPELL or
LEARN_PET_SPELL effect as 1.12's GetTrainerServiceIcon (0x004D8F50) does,
then 3.3.5's gate: tradeskill trainer, effect 0 CREATE_ITEM, item cached.
3.3.5's other create-item effects are dropped: 1.12's 59 is
OPEN_LOCK_ITEM and 157 does not exist.
2026-10-28 20:11:12 -05:00
Brues 7d9dafbfcf feat(gossip): GetNumGossipOptions
3.3.5 pushes m_gossipOptionsCount; 1.12 keeps no count. Count the slots
1.12's Script_GetGossipOptions (0x4E28D0) pushes: every slot with a
non-negative index, no session check, so the count matches the list.
2026-10-28 18:53:12 -05:00
Brues 79d4b7f44d feat(faction): ExpandAllFactionHeaders, CollapseAllFactionHeaders
3.3.5 and 4.3.4 call CGReputationInfo::CollapseHeader(m_numFactions,
collapse); an index at the entry count sets every header. 1.12's
CollapseHeader (0x4D6400) has the same branch, so both make that call
with 1.12's entry count.
2026-10-28 18:49:32 -05:00
Brues 9b07ad15df feat(chat): IsChatAFK, IsChatDND
IsChatAFK reads 1.12's chat AFK mirror (0xB6E5CC), 4.3.4's CGChat::m_afk,
with the same writers: SetAfk, ClearAfk, the PLAYER_FLAGS change handler
and world entry. 1.12 keeps no DND mirror; its /dnd branch tests the
PLAYER_FLAGS DND bit, so IsChatDND reads that bit.
2026-10-28 18:44:19 -05:00
Brues 36d55ab305 feat(player): IsLoggingOut, IsPlayerInWorld
IsLoggingOut reads the current connection's logout-pending byte through
the engine's own ClientServices::GetCurrent / IsLogoutPending pair, as
4.3.4's CharacterLoggingOut does. IsPlayerInWorld reads VAR_IN_WORLD,
1.12's CGGameUI::s_inWorld. Both are in-game only, as in 4.3.4.
2026-10-28 18:34:20 -05:00
Brues ebe9b9b6de feat(friendlist): AddOrRemoveFriend
4.3.4's Script_AddOrRemoveFriend: removes the friend whose name matches
without case (1.12's RemoveFriendByName scan, then the engine's
SendRemoveFriend), else adds through FriendList::AddFriend. The note goes to
the client-side store once the server adds the friend: it waits by name
until FriendList::SetFriendName names the slot, via redirects of that
function's two call sites. The add reply can't be paired with the request,
since tortoise-wow sends none for an unknown name. Also lists
CanCancelAuction in the README.
2026-10-28 18:21:41 -05:00
Brues 4df29722d2 feat(auction): CanCancelAuction
4.3.4's Script_CanCancelAuction: nothing without an auctioneer, nil for an
owner-list index with no row, else 1. Gates mirror 1.12's own CancelAuction
(0x004D0260); 1.12 owner records have no sold flag, and the cancel-fee money
check stays in CancelAuction as in 4.3.4.
2026-10-28 18:10:08 -05:00
Brues 086b9f9fbb feat(range): 4.3.4 target gate for IsSpellInRange / IsItemInRange
C_Spell.IsSpellInRange and C_Item.IsItemInRange now run through
Spell::Range::CastVsUnit, a port of 4.3.4's Spell_C_RangeCheckSelected on
1.12's own target gate (CheckSpellTargetRange 0x6E4440, mirrored branch
for branch since it folds "can't target" into "in range"):

- nil for a unit the spell cannot be cast at (reaction, creature type,
  dead/alive state)
- spells aimed at the pet (implicit target 5) measure to the pet
- a resurrect (target word 0x8000) on a ghost measures to its corpse
- pet-book spells use the pet as caster; names take the book the
  engine's name resolver matched

UnitInRange measures from the active mover (VAR_ACTIVE_MOVER_GUID), as
4.3.4 does, so a controlled unit is the origin.
2026-10-28 16:20:00 -05:00
Brues bc2481395d feat(pvp): SetPVP, GetPVPDesired, GetPVPTimer, IsPVPTimerRunning
SetPVP / C_PvP.SetPVP send CMSG_TOGGLE_PVP with the state byte (3.3.5
Script_SetPVP); tortoise-wow and vmangos both honor it. The timer mirrors
3.3.5's GetPVPToggleTimer, with "running" derived client-side since 1.12
servers never set PLAYER_FLAGS 0x40000: armed by the engine's
ERR_PVP_TOGGLE_OFF notice while flagged, disarmed by the toggle-on notice,
the active player's UNIT_FLAG_PVP drop, or glue boot. Three call-site
redirects, no MinHooks. PVP_TIMER_UPDATE("player") fires on start/stop.
2026-10-28 15:47:39 -05:00
Brues daded912c2 feat(input): F13-F24 key support
The window procedure's key translator dropped VK_F13..VK_F24, so the
keys never reached bindings or frame scripts. Translate them to codes
0x2F4..0x2FF (the free range below F1; codes must stay under the
0x30E-entry key-taker array) and name them in the engine's three
code-to-name decoders by retargeting each one's UNKNOWN branch.
2026-10-28 15:26:25 -05:00
Brues a0c5c8a30c feat(input): GetMouseButtonName
Names come from the engine's own click-name literals, so an ID outside
1..5 is "UNKNOWN", as 1.12's OnClick names it.
2026-10-28 15:13:01 -05:00
Brues e26f8fb49e feat: ConsoleAddMessage, CursorHasMacro, GetMacroBody
GetMacroBody shares the index-or-name macro argument with SetMacroSpell /
SetMacroItem through the new Macro::Arg::Slot.
2026-10-28 15:07:29 -05:00
Brues da9e9b6f55 feat(spell): IsAttackSpell, IsAutoRepeatSpell, IsConsumableSpell 2026-10-28 15:02:02 -05:00
Brues a5e8a6f5b6 feat(spell): GetSpellBaseCooldown 2026-10-28 14:50:18 -05:00
Brues f191c53c2a feat(unit): CanBeRaidTarget 2026-10-28 14:43:38 -05:00
Brues 797fea90ed fix(spell): Resolve the has-range gate with a null target, as ActionHasRange does
PlayerVsUnit passed the real target to GetMinMaxRange (0x6E3480), which folds both units' combat reach into every non-melee range row. Self-range spells (Hearthstone, totems, professions) came back with max ~3yd, passed the gate, and IsSpellInRange / IsItemInRange answered false instead of nil past melee distance. The engine's ActionSlotHasRange (via ActionHasRange 0x4E75D0) always resolves with a null target; EngineHasRange now does the same.
2026-10-28 14:32:01 -05:00
Brues 026fe20a89 feat(pet): IsAtStableMaster 2026-10-28 14:25:10 -05:00
Brues 529bacd0cb feat(pet): IsPetAttackAction 2026-10-28 14:19:33 -05:00
Brues c16c3a90dc feat(merchant): GetBuybackItemLink; buyback getters skip the vendor gate
GetBuybackItemLink(slot) builds the link with the engine's own item
link builder. It and C_MerchantFrame.GetBuybackItemID share one
buyback-slot resolver with no vendor-GUID check, as 1.12's
GetBuybackItemInfo (0x004FB310) and 4.3.4's GetBuybackItemLink do.
2026-10-28 14:12:32 -05:00
Brues ab829e98c0 feat(action): IsItemAction, HasBonusActionBar 2026-10-28 14:03:58 -05:00
Brues 602840419b feat(quest): GetQuestLogCompletionText
Returns the quest objectives with $N-style tokens expanded, the branch
4.3.4 takes when a quest has no completion text; the 1.12 query response
carries none. Takes a log index or the selected quest.

The cache field at +0x129C is the quest's EndText, not completion text:
rename OFF_COMPLETION_TEXT to OFF_END_TEXT and GetQuestDetails' key to
endText. Quest::Cache::ExpandText now owns the token-substitution call
that the quest hyperlink tooltip used to define locally.
2026-10-28 13:53:26 -05:00
Brues 40cd25315d feat(player): GetCritChance, GetRangedCritChance
Read PLAYER_CRIT_PERCENTAGE / PLAYER_RANGED_CRIT_PERCENTAGE from the
CGPlayer sub-struct, the same way the engine's GetDodgeChance reads its
neighbouring field.
2026-10-28 13:42:27 -05:00
Brues 984dc236ab feat(dressup): try on what a recipe makes
4.3.4's TryOnWithVisual swaps a recipe item (no inventory type, a spell
that teaches a CREATE_ITEM spell) for the item it makes; 1.12's worker
shows ERR_NOT_EQUIPPABLE instead. TryOnItem adds the swap in front of the
worker for DressUpModel:TryOn and, via a call redirect, for the worker's
item-cache callback, so Control-click on a pattern opens the dressing
room even before the pattern is cached. The recipe walk is shared with
IsDressableItem (Item::Dressable::RecipeItem).
2026-10-28 13:12:47 -05:00
Brues cdc3506cdd feat(item): IsEquippedItemType, IsCurrentItem, IsDressableItem, IsHelpfulItem, IsHarmfulItem
Ports of 4.3.4's item predicates. IsEquippedItemType runs the engine's
inventory search over the equipment slots by equip location, item class
or subclass name; the [equipped] macro condition now calls it instead of
a Lua rebuild. IsCurrentItem reads the in-flight cast item that 1.12's
IsCurrentAction checks. IsHelpfulItem / IsHarmfulItem classify the
on-use spell with the IsHelpfulSpell / IsHarmfulSpell classifier.

Shared: Item::Location::IDForArg (GetItemIDByName, was copied in three
files) and Item::Location::Walk over FUN_INVMGR_WALK.
2026-10-28 13:06:48 -05:00
Brues 6347bdd6c5 feat(expansion): GetExpansionLevel, GetAccountExpansionLevel, GetMaxPlayerLevel
Both expansion levels answer the shared kCurrentExpansionLevel (0), the
value LE_EXPANSION_LEVEL_CURRENT and GetClassicExpansionLevel give.
GetMaxPlayerLevel is a constant, as 4.3.4's is (85): 60, the cap 1.12's
own FrameXML keeps in MAX_PLAYER_LEVEL.
2026-10-28 12:49:57 -05:00
Brues ff4a9ffd5a feat(macro): SetMacroSpell, SetMacroItem, macro range unit
SetMacroSpell and SetMacroItem publish a spellbook spell or an item as
a macro's display, like 4.3.4: a name that resolves to nothing greys
the button, and the claim lasts until the macro's body is edited.

Each macro now keeps the unit its spell is aimed at (4.3.4's
MACRONODE::m_target): the target those functions name, or the [@unit]
of the clause a #showtooltip or /cast line matched. Action::Range
redirects IsActionInRange's call to the slot range function and, for a
macro slot with a unit, passes that GUID to the engine's range check
in place of the selection, as CGActionBar::HasValidTarget does.
2026-10-28 12:46:56 -05:00
Brues 9541dc2949 feat(macro): RunMacroText, GetRunningMacro, GetRunningMacroButton
RunMacroText copies the text into the body of a zeroed stack macro entry
and hands it to the engine's macro runner, as 4.3.4 does with a stack
MACRONODE. The runner reads only the body, so each line goes the
engine's way: EXECUTE_CHAT_LINE to MacroEditBox, with # lines skipped
and /stopmacro honored.

Macro::RunBody keeps the running entry and button per run, saved and
restored around nested runs. GetRunningMacro maps the entry's ID to its
index; GetRunningMacroButton returns the button. [button] now matches
the running macro's button as well as the clicked one.

Macro::Execute drops its Lua ChatEdit_ParseText path and the addon
RunMacro preference. The secure button's macro verb and the MACRO
binding run through the engine runner with the clicked button and
"LeftButton".
2026-10-28 12:28:29 -05:00
Brues 1340cc75c7 feat(chat): SendSystemMessage
Shows a local CHAT_MSG_SYSTEM line through the engine's chat line
function, called as the game-message display calls it for a chat-kind
message: chat type 10 and ten zero arguments.
2026-10-28 12:08:58 -05:00
Brues 9c50a90d34 feat(currency): GetCoinText
GetCoinText(amount [, separator]) and C_CurrencyInfo.GetCoinText: the
non-zero gold, silver and copper parts, each from its GOLD_AMOUNT /
SILVER_AMOUNT / COPPER_AMOUNT global string, joined by the separator
(default ", "). Zero is the empty string.

The three strings are backported to every embedded locale.
2026-10-28 12:03:24 -05:00
Brues 1942383494 feat(group): InviteUnit, UninviteUnit, PromoteToLeader
Group verbs that take a unit token or a name in one call. Each one
calls the engine's own group sender on the active player:

- InviteUnit(targetName): name only, with the ERR_INVITE_SELF check
  and the invite tutorial flag.
- UninviteUnit(name): a unit token resolves to a GUID; any other
  string is sent as a name.
- PromoteToLeader(name [, exactNameMatch]): a unit token resolves to
  a GUID; a name goes through the engine's by-name search in
  PromoteByName's mode.
2026-10-28 11:58:42 -05:00
Brues 0f37ddc48d feat(aura): CancelUnitBuff
CancelUnitBuff(unit, index [, filter]) cancels the player's own aura at
the given index. The index counts in FindNthSlot order (4.3.4's
GetSortedAuraSlot), so it matches the C_UnitAuras by-index getters; the
filter defaults to HELPFUL. The cancel gate is the engine's: the slot's
cancelable bit or the spell's AttributesEx 0x4.
2026-10-28 11:43:19 -05:00
Brues ac118d5305 feat(unit): GetShapeshiftForm
Returns the stance-bar index of the active form, walking the bar from the
last entry as 4.3.4's CGSpellBook::GetShapeshiftForm does: count + 1 for a
form not on the bar, 0 for requireForm with no form byte. Each index is
tested through the engine's Script_GetShapeshiftFormInfo, which holds
1.12's only full "bar spell is active" check.

The [stance] / [form] macro conditions now use GetShapeshiftForm(true),
as Blizzard's EvaluateStance does, so a paladin aura no longer counts as
a stance.
2026-10-28 11:35:26 -05:00
Brues cf645a30af feat(spell): CastSpellByID
Casts the exact spell ID from the player's or the pet's spellbook at the
current target, or at the unit an optional token names, through the
existing exact-ID dispatch. Returns true once dispatched and nothing for
an unknown spell or a token that names no unit. Macros calling it tag
their primary spell like CastSpellByName macros.
2026-10-28 11:22:17 -05:00
Brues fcd7e52be0 docs: SetBagPortraitTexture, SetInventoryPortraitTexture 2026-10-28 11:22:16 -05:00
Brues 886a4cb140 feat(container): SetBagPortraitTexture, SetInventoryPortraitTexture
Register the client's misspelled SetBagPortaitTexture under its correct
name and as C_Container.SetBagPortraitTexture. Fix the engine's
SetInventoryPortaitTexture, which reads the unit token from argument 1
(the texture) and so only ever cleared the texture, by patching that
index to 2, and register it as SetInventoryPortraitTexture.
2026-10-28 10:25:29 -05:00
Brues e30da939ec fix(lossofcontrol): let immunity-granting spells through their CC
GetSpellLossOfControlCooldown treated Polymorph (and every stun, fear,
confuse, charm) as blocking every spell, so a druid form reported a
lockout while polymorphed. The forms grant Polymorph immunity, and the
client's caster validator lets such a spell through via its per-arm
crowd-control scans. Blocks() now asks that arm's engine scan instead of
restating the gate.

Fixes #114
2026-10-28 02:25:06 -05:00
Brues 6e4efb39f7 feat(lua): Blizzard_Menu
Menu, MenuUtil, MenuTemplates, the Compositor and the DropdownButton
intrinsic, ported from retail with SecureTypes, ProxyUtil and RegionUtil,
and the Vanilla/Classic variants. The engine pieces are the earlier
commits: motion focus and propagation, the click/motion split,
IsMouseMotionFocus, SetTextToFit, SetToDefaults and region scale.

Port changes:
- The Compositor calls 1.12's frame __index function instead of indexing a
  method table.
- 1.12's script SetFrameLevel leaves children behind, so the menu takes its
  level before Open() raises the elements above it, and scroll mode brings
  the ScrollBox and ScrollBar up through SetParent(nil) then SetParent(menu).
- 1.12's SetScript does not turn mouse input on, so the menu, its elements
  and the auto-hide button do it where they set the mouse scripts.
- One window: no GetWindow/SetWindow. No taint: no SetForbidden or secure
  delegate.
- A submenu opens past its parent's right inset, at the parent's edge, as
  1.12's dropdowns do; retail's atlases hide the overlap that 1.12's opaque
  borders show.

The Classic atlases are 1.15 art, so the styles are drawn with 1.12's:
dropdowns with UIDropDownMenuTemplate's label frame and scroll-down button,
the filter dropdown with the stretched panel button, MenuStyle1/2 with
DropDownList's dialog and tooltip backdrops (cleared when a menu frame is
released), the dropdown check, the radio button sheet and the help frame
divider's middle slice. Insets and 10 of row padding keep arrows, swatches
and text clear of the opaque borders. ColorSwatchTemplate's texture
sublevels become layers. WowStyle2 and the highlight radio are left out
until they have 1.12 art.

Retail's global nop, assertsafe and CallErrorHandler (EnvironmentUtil,
ErrorUtil) replace the local copies in FunctionUtil, Pools and LinkUtil.
Also GameTooltip_SetTitle, LIST_DELIMITER, IsScrollingMessageFrame and
UIResetButtonTemplate.
2026-10-28 02:13:05 -05:00
Brues 8c21ab4b04 fix(region): give a region its frame's scale when it gets the frame
Vanilla gives a texture or font string its frame's scale only when it links
the region into a draw layer, which happens once the frame is visible. Until
then the region keeps scale 1.0: a region made on, or moved to, a hidden
frame lays out in the wrong units and GetLeft/GetRect report its position
divided by the wrong scale. Probed under a 0.91-scale UIParent: on a hidden
row a texture anchored to the row's left edge reported 454,446 against the
row's 499,498, the same ratio after moving the row; on a shown row the two
matched. Retail regions carry their frame's scale shown or hidden, and
Blizzard_Menu measures its rows from their regions while they are hidden.

CScriptRegion::SetRegionParent's call to CSimpleFrame::AddRegion now also
makes the call AddRegionToLayer would make later: the region layout's own
scale setter with the frame's layout scale, unforced. The draw layer is
still joined at show.
2026-10-28 02:12:52 -05:00
Brues 7ec3829eb5 feat(region): SetToDefaults
Retail's contract, probed on 5.5.4: a frame, texture or font string goes
back to the state its class constructs it in, not the one it was created
in, so template values, a font string's creation font and a button's
construction-time mouse input are lost. The parent, keyboard and wheel
input, registered events, child regions and Lua fields stay. 1.12's
constructor values agree with the probed reset (MEDIUM, parent level + 1,
no font, white text, black shadow at 0,0, CENTER/MIDDLE, gradient -1).

Values reset through each object's own methods, looked up through its
vtable's method lookup, so neither table fields nor a replaced metatable
(Blizzard_Menu's Compositor replaces them) are consulted and every backport
keeps its state in step. Engine paths where no method expresses the
default: every script slot released and emptied as SetScript(nil) does;
Frame::Attributes::ClearAll, firing no OnAttributeChanged; the text of a
font string or button label through the font string's SetText member; the
font unlinked and cleared through the engine's own no-font store; the
follower mask and alpha gradient back to their constructor values.

Verified against the retail snapshot property by property on 1.12. Not
copied: retail leaves a hidden frame IsShown() but not IsVisible() after
the reset; this one shows it.
2026-10-28 01:15:46 -05:00
Brues 86bfd881a9 feat(fontstring): SetTextToFit
Retail's contract, probed on 5.5.4: set the text, then the explicit width
becomes the text's unbounded width, whether the old width was smaller or
larger and whatever the max lines; the height is not touched; no or empty
text leaves the width unset. The text goes through the engine's own Lua
SetText, so conversions, grammar escapes and the "Font not set" error are
SetText's; the width through CLayoutFrame::SetWidth with the same substring
measure GetUnboundedStringWidth uses.
2026-10-28 01:00:07 -05:00
Brues cd55ce9139 feat(frame): separate mouse clicks and mouse motion
frame:SetMouseClickEnabled / SetMouseMotionEnabled / IsMouseClickEnabled /
IsMouseMotionEnabled and SetPropagateMouseClicks / CanPropagateMouseClicks,
with enableMouseClicks, enableMouseMotion and propagateMouseInput="Clicks"
in XML. Retail (probed on 5.5.4) routes the two separately: motion goes to
the top motion-enabled frame, a press to the top click-enabled frame, so a
click on a motion-only frame reaches the frame under it and a click-only
frame takes clicks without ever taking the motion. A frame that propagates
clicks passes the press on; each gets it and then the release, top-first.

The engine's one mouse bit stays "click or motion"; Frame::MouseInput keeps
the frames with one half off. The focus pass's probe call skips frames with
motion off. The press handler's focus read becomes the click walk, which is
that same read while no frame uses the split or click propagation; the press
and release dispatches run each extra target's button slot after the
engine's.

EnableMouse sets both halves. IsMouseEnabled is both halves and still
answers 1 or nil as the engine does: pfUI compares it with SpellIsTargeting.
2026-10-28 00:50:56 -05:00
Brues 1f8042088c feat(frame): mouse motion propagation and the motion focus list
Retail's motion focus is a list (probed on 5.5.4): the walk takes the top
mouse-enabled frame under the cursor and keeps going while the last frame
taken propagates motion; the next frame is the next one under the cursor,
not the parent. Every listed frame is focus, a frame that stays listed
across a change gets neither leave nor enter, and the ones that drop out
leave before the ones that join enter, each top-first.

The three blocks that write the UI context's focus (+0x7C) - the focus
pass's commit, the mouselook focus setter and the input removal - now call
Frame::MotionFocus, which keeps the list and keeps +0x7C as its first
frame. A propagating pick resumes the engine's walk through the same
per-frame probe. A removed frame leaves wherever it is in the list and asks
for a re-pick; hiding a frame removes it before its children, which gives
retail's outer-first leave order.

- frame:SetPropagateMouseMotion / CanPropagateMouseMotion /
  IsMouseMotionFocus, and propagateMouseInput="Motion"|"Both" in XML.
- GetMouseFoci returns the list (one frame unless frames propagate), as
  retail does, instead of every frame under the cursor.
- EnterLeaveMotion offers motion to the frame MotionFocus is notifying.
- Common::ReplaceWithCall takes up to 64 bytes; it refused anything over
  16 without a word.
2026-10-28 00:37:13 -05:00
Brues a86d5ec48f feat(lua): BackdropTemplate
Port retail's Blizzard_SharedXML/Backdrop: the BackdropTemplate template,
BackdropTemplateMixin, and the BACKDROP_* tables (verbatim). Retail draws
the backdrop with nine textures of its own because its frames lost the C
backdrop; 1.12's frames still have it and it lays out the same nine slices
(benilla-re ui/backdrop), so the mixin keeps retail's state and methods
(backdropInfo, HasBackdropInfo, ApplyBackdrop, ClearBackdrop, GetEdgeSize,
the OnLoad key values) and draws through the engine's SetBackdrop.
SetBackdrop with the table already applied keeps the colours, as retail's
does. GetBackdrop and the colour methods stay the engine's own.

SetBorderBlendMode and backdropBorderBlendMode are not ported: Lua cannot
reach the engine's edge textures.
2026-10-27 23:56:10 -05:00
Brues 70dadf0449 fix(aura): player aura duration after login
SMSG_UPDATE_AURA_DURATION carries the holder's remaining time. On login
the server sends it for auras the character already held, so their
duration read as the time left instead of the total. Flag those slots
(no player object yet on a fresh login; occupied slot with no earlier
duration on a reconnect) and report the spell's base duration instead,
or the remaining time where a caster modifier stretched it past the base.
2026-10-27 23:40:30 -05:00
Brues 5363434439 build: standard section layout, no writable code
/SECTION:.text,EWR made the code section writable and the .rdata merge
put constants in it. Nothing needs either: engine patches make their
target writable through Common::PatchBytes, and a scan of every
function in the DLL finds no write into .text or .rdata. A writable,
executable section is a common antivirus heuristic. Same file size.
2026-10-27 23:24:17 -05:00
Brues 9bac760195 build: gzip the embedded addons and compile for size
The embedded addon Lua/XML and Bindings.xml were stored as raw RCDATA,
924 KB of the 2.38 MB DLL. Each resource is now gzipped at build time
(cmake/gzip_file.cmake, CMake's own ARCHIVE_CREATE) and inflated with
the engine's zlib on first use, so Embed::Resource keeps its contract:
the same bytes, valid for the life of the DLL. Encoding::Compress now
exports the Inflate it already had for C_EncodingUtil.

/O1 replaces /O2 /Ob2: 280 KB less code. /GL + /LTCG made it larger.

2,380,288 -> 1,430,016 bytes.
2026-10-27 23:24:17 -05:00
Brues bd02983a08 feat(lua): WowTrimHorizontalScrollBar
Retail's horizontal bar is its vertical one with x and y swapped. Classic
Era has no horizontal bar and this client no horizontal scroll bar art, so
the template is WowClassicScrollBar with every anchor, size and inset
swapped, and retail's horizontal atlas names (UI-ScrollBar-EndCap-Left/
Right, _UI-ScrollBar-Center, UI-ScrollBar-ScrollLeft/RightButton-*, ids
from the 1.15 member table) bind to the Classic art transposed: the top cap
is the left cap, the up arrow the left arrow. Transposing keeps the art's
top-left lighting, which a quarter turn would move. The square knob takes
the swapped crop of the same file.

Atlas entries gain a transposed flag: SetTexCoord composition maps sprite x
down the file rect and y across it. An inline |A icon is one axis-aligned
rect, so a transposed atlas is not drawn there.
2026-10-27 23:01:36 -05:00
Brues 852cf44b7d feat: frame:SetAlphaGradient and frame:DesaturateHierarchy
SetAlphaGradient(index, gradient), ClearAlphaGradient and HasAlphaGradient,
what ScrollBox's SetEdgeFadeLength calls. As probed on retail: index 0 fades
in from the left and top edges, index 1 from the right and bottom, and the
fade shows only while the frame clips its children, its own regions
included.

Each index is one texture stage over the draw: a 2x2 ramp texture, filtered
and clamped, whose alpha multiplies in (preset 1). Coordinates come from the
camera-space position through a projected texture matrix that maps clip
space to the screen and then to the ramps, reloaded on every projection and
viewport set while a gradient draws. Textures, text (drawn in pixels under
its own projection) and clipped draws fade on the same screen spot.
ClipChildren now batches regions by nearest clipping frame and nearest
frame with a gradient; Texture::Mask takes its stages above the gradient's.
D3D only; a desaturated or masked texture does not fade.

DesaturateHierarchy(desaturation [, excludeRoot]) sets the desaturation of
every texture of the frame and of the frames under it, through
Texture::Desaturation.
2026-10-27 22:53:15 -05:00
Brues e59f9de5a8 feat(lua): SOUNDKIT constants
Verbatim port of Classic Era's Blizzard_SharedXML/Vanilla/SoundKitConstants.lua.
PlaySound already plays by SoundKitID, so the scroll bar arrows'
SOUNDKIT.U_CHAT_SCROLL_BUTTON now resolves and clicks.

109 of the 383 ids exist in 1.12's SoundEntries.dbc, with matching names
(1115 = UChatScrollButton, 850 = igMainMenuOpen); the rest are later sounds
and play nothing.
2026-10-27 21:37:51 -05:00
Brues 59164e3575 fix(lua): scroll bar knob drag and bottom end cap
ScrollBar's thumb drag and track paging read the cursor through
InputUtil.GetCursorPosition, which was never ported, so both handlers
errored on their first line. Port retail's InputUtil.lua and the
GetAppropriateTopLevelParent family it uses into FrameUtil.lua.

UI-ClassicScrollBar-EndCap-Bottom used UI-Character-ScrollBar's upper
bottom cap, whose 3-row border put the Forward stepper over the cap's
separator. Bind it to the lower cap (rows 227..255), whose 4-row border
and 17-row well fit the template's stepper exactly.
2026-10-27 21:31:47 -05:00
Brues 711c810b72 feat(lua): retail's ScrollBox, with Classic Era's scroll bar
Port Blizzard_SharedXML/Shared/Scroll (ScrollBox, its views, ScrollBar,
ScrollUtil, ScrollController, ScrollTemplates, TrimScrollBar.lua) and the
helpers it needs (Flags, FrameFactory, TemplateInfoCache,
TreeListDataProvider, ButtonStateBehavior). Verbatim except:
- TemplateInfoCache asks C_XMLUtil directly; retail's forbidden delegate
  is only taint isolation.
- Textures without <Anchors> get setAllPoints="true". Retail's loader
  fills such a texture to its parent (probed); 1.12's does not, and
  cannot be made to without breaking its own UI, whose TalentFrame
  anchors unanchored branch textures with one SetPoint.

The scroll bar is Classic Era's WowClassicScrollBar. Its atlases are
Blizzard's repack of vanilla's scroll bar art, bound in AtlasData.h to
the 1.12 files that carry it (UI-Character-ScrollBar for the track, the
UI-ScrollBar-Scroll*Button files for the steppers, each arrow measured
at the member table's 19x17). Its highlights draw with ADD, as the
client's own scroll buttons draw that art. WowTrimScrollBar and
MinimalScrollBar, whose art the client does not have, are
WowClassicScrollBar.

Also TextureKitConstants, and Pools.lua's AddSourceLocationExclude.
2026-10-27 21:22:22 -05:00
Brues dceec8b74c feat: engine pieces for retail's ScrollBox
What the ScrollBox port needs from the DLL, and three engine bugs it hit.

Fixes:
- GetWidth / GetHeight answer a rect-derived size over the layout scale,
  as 4.3.4 does. 1.12's getters leave the division out, so an anchored
  region under a UI scale read scaled (a 160-high track at 0.91 answered
  145.6, and the scroll bar thumb stopped short). GetRect and
  GetScaledRect use them.
- A <Size>, <Anchor> or <Offset> with only `x` applies. The engine's
  dimension reader decides "no attributes" from `y` alone; a co-hook
  answers as 4.3.4 does. Xml::Anchors' "0" attribute workaround goes.
- KeyValue type="global" walks a dotted path, as retail's own templates
  need (ScrollControllerMixin.Directions.Decrease).

New:
- <Texture atlas="..." useAtlasSize="...">, applied as SetAtlas.
- securecall / securecallfunction / secureexecuterange, as probed on
  retail: results returned, errors to the error handler, the range walk
  goes on after one.
- AddSourceLocationExclude(fileName): GetSourceLocation steps over that
  file's levels.
- region:AdjustPointsOffset(x, y) / ClearPointsOffset(), re-setting each
  anchor through the engine's SetPoint. Retail, probed: Clear zeroes the
  offsets rather than undoing adjustments.
- Enum.InputContext.
2026-10-27 21:22:22 -05:00
Brues 9edce4a9f9 feat(xml): intrinsic frame types, script binding types, EventFrame
A top-level frame element with intrinsic="true" defines a frame type:
<EventFrame> and CreateFrame("EventFrame") build a frame of the element's
own type with the definition applied first (its mixins, content and child
frames, then the templates and the element's own). Retail's EventFrame,
EventButton, EventEditBox and EventScrollFrame are ported verbatim;
ScrollBox and its scroll bars are EventFrames.

The builder keeps a definition instead of building it, detached from its
document the way the template registrar keeps a virtual node, and
registers its name with FrameXML_RegisterFactory. The one factory for
every intrinsic name builds the base type, for the node the builder hook
is building.

An intrinsic's scripts are its intrinsic bindings. Each script now has
retail's three (LE_SCRIPT_BINDING_TYPE_INTRINSIC_PRECALL, _EXTRINSIC,
_INTRINSIC_POSTCALL), as probed on retail:

- SetScript and GetScript read and write the extrinsic binding, so
  SetScript(script, nil) keeps the intrinsics.
- GetScript(script, binding) reads one; HookScript(script, hook) hooks
  the extrinsic, so the hook runs before the postcall, and
  HookScript(script, hook, binding) hooks an intrinsic.
- An intrinsic element without intrinsicOrder binds the precall.

A slot with intrinsic bindings holds a dispatcher closure over the three,
which runs each in its own context under the script error handler. Every
writer of a slot releases its old handler first, so after SetScript and
after each XML node load a new handler moves into the extrinsic binding.
The check compares the closure, not the ref number: luaL_ref hands the
released number straight back. Frame::ScriptArgs looks inside the
dispatcher as it does the HookScript wrapper.
2026-10-27 20:18:13 -05:00
Brues 4e3a18cdd1 feat(frame): clipChildren and SetClipsChildren/DoesClipChildren
A frame that clips its children draws every frame under it only inside
its own rect, and the mouse reaches them only there. Retail's ScrollBox,
talent tree and settings list rely on it.

Retail keeps clipped frames in their own strata and levels (the talent
tree puts a button's glow at the button's level - 1 inside a clipping
frame), so the clip applies per level instead of drawing the subtree in
one piece as 1.12's ScrollFrame does:

- The level rebuild's per-frame layer call (0x007659E7) is redirected.
  A frame under a clipping frame fills an engine batch of its own, one
  per level batch and nearest clipping frame, and the level batch gets
  a render callback that draws it right after the level's own regions.
- That callback is the ScrollFrame's draw (0x00787220) with the clip
  rect: save the transforms, intersect with the current viewport, set
  the ortho transforms, narrow the viewport, draw, restore.
- A ScrollFrame's own subtree draw calls each child at 0x0076B511; that
  call is redirected too, so a clipping frame inside a scroll child
  clips. Nested clips hold because each draw intersects with the
  viewport already in place.
- The hit test also misses outside every clipping ancestor's hit rect.
- Turning the clip on or off and SetParent mark the moved frames'
  layers changed, since SetParent does not relink a frame whose level
  and strata stay the same.

Offsets.h gains the batch, device-transform and call-site entries, and
the level-rebuild comment now says what the function actually does.
2026-10-27 19:44:43 -05:00
Brues fc8fba65cc refactor(frame): share the SetParent hook through Frame::ParentChange
MinHook allows one hook per address, and clipping needs to follow a
frame's parent as Frame::Alpha does. Frame::ParentChange now owns the
SetParent hook and runs its listeners after the engine moves the frame,
the way Frame::Destruction owns the destructor. Frame::Alpha is its first
listener, with the same behavior.
2026-10-27 19:44:42 -05:00
Brues f01a059cc0 feat(frame): useParentLevel and SetUsingParentLevel/IsUsingParentLevel
A frame that uses its parent's level draws at the parent's level instead
of one above it. Retail's ScrollBox and TrimScrollBar templates rely on it
for their scroll target and backgrounds.

4.3.4 keeps this as frame flag 0x100000, and its level setter replaces any
level it is given with the parent's while the flag is on. 1.12's setter
(0x0076A4F0) is the same function without that test; a hook adds it, so
SetParent, a parent moving its children, and SetFrameLevel all land on the
parent's level. Setting the flag moves the frame and its children to the
parent's level, as 4.3.4's SetUseParentLevel does.

The XML attribute is read after the node loads, when the frame has its
parent, and only when present, so a node's value overrides its template's.
2026-10-27 19:17:03 -05:00
Brues 8d22876c01 fix(debugtools): seat the table inspector's close button in its title bar
The stock 32x32 UIPanelCloseButton overhung the 19px title bar and sat on
the border. Size it 24x24 at the same inset as OpenParentButton so both
title-bar buttons share one centre line.
2026-10-27 18:56:18 -05:00
Brues 39a14054fe feat(frame): AnchorUtil and LayoutFrame, with their region methods
Port retail's AnchorUtil, GridLayoutUtil and LayoutFrame (Lua and XML
templates) to !!!ClassicAPI. They are verbatim except PrintAnchorGraph,
which prints to chat since 1.12 has no C_Log. GetUnscaledFrameRect and a
GMError that does nothing (a player client is never a GM client) come
along.

The region methods they call:
- GetPointByName(point) through GetPoint's own pusher.
- ClearPoint(point): ClearAllPoints (0x767620) for one slot, dropping
  the dependent bit through 0x767FA0 and deleting the node.
- IsRectValid(): the stock edge getters' steps, so it is true exactly
  when GetLeft answers a number.
- GetScaledRect() on every region.
- GetScale/GetEffectiveScale on textures and font strings: the layout
  scale the frame hands each region, and 1.
- ignoreRect on GetWidth, GetHeight and GetSize: a 0 explicit size stays
  0 instead of falling back to the rect.
2026-10-27 18:49:24 -05:00
Brues 7e1edce462 feat(xml): inherit="prepend"/"append" on <Scripts> handlers
A handler element with inherit="prepend" now runs the inherited
template's handler first and then its own; "append" runs its own
first. Vanilla's loader let the node's handler replace the template's.

Template nodes load onto the same frame before the node's own content,
so the handler a template set is captured when that template's load
returns, then joined with the node's handler (body, function= or
method=) in a C closure that calls both with the same arguments.
Elements apply in document order. The function= binding skips scripts
that ScriptInherit sets.

Also binds luaL_unref as Game::Lua::Unref and drops an unused local
typedef for it.
2026-10-27 18:23:40 -05:00
Brues e7b6c39ace feat(debugtools): port retail's table inspector
Replace the minimal /tinspect window with retail's Blizzard_TableInspector
and its anchor and attribute providers. The window lists a table's
anchors and its fields grouped by type, with child frames and regions,
editable numbers, strings and booleans, a filter, back and forward
history, open-parent, duplicate, and Show / Highlight / Dynamic Updates
toggles. The provider XML is retail's, unchanged.

1.12 changes to the main window: a backdrop and plain title bar replace
the gear-manager art, the scroll-up and plus buttons replace two retail
textures, and the scroll frame and filter box are small unnamed templates.
Windows come from a frame pool and have no names, so the stock
InputBoxTemplate's $parent-named border and UIPanelScrollFrameTemplate's
named scroll bar would be shared by every window.

/tinspect works as on retail: a table result opens on it; otherwise it
opens on the frame under the cursor, or UIParent. Ctrl in /fstack opens
TableAttributeDisplay. The frame highlight (AnchorHighlightMixin,
FrameHighlightTemplate) comes from retail's Blizzard_DebugTools.

!!!ClassicAPI gains retail's TruncatedTooltipScriptTemplate and
PanelDragBarTemplate, GetAppropriateTooltip, GameTooltip_AddNormalLine
and GameTooltip_AddColoredLine.
2026-10-27 18:06:55 -05:00
Brues 9027e22e4f feat(xml): <Anchor> x/y and relativeKey, parentArray
Retail templates write anchor offsets as attributes and name anchor
targets by key path. 1.12's anchor loader reads point, relativePoint,
relativeTo and an <Offset> child only, so those anchors landed on the
parent with no offset.

After each frame, texture and font string loads, Xml::Anchors re-sets
every <Anchor> that has relativeKey or x/y. The target is the key path,
or the one the engine's own anchor node resolved. The offsets go through
the engine's XmlReadDimension (0x006F1EB0), the reader the loader uses
for <Offset>. The point is set with the engine's setter.

A frame loads its layers before its child <Frames>, so a layer anchored
to a child frame cannot resolve at load. Such anchors are queued and
retried once a frame's children are built, before its OnLoad, and again
when the outermost build returns, which reports what is still missing.

parentArray="Name" appends the region to parent.Name in load order.
2026-10-27 18:06:45 -05:00
Brues 7add0fc88f feat(frame): region:GetDebugName([preferParentKey])
Retail's debug name for a region: its global name; else its parent's
debug name, a dot, and the key that holds it in the parent's Lua table,
or its address in hex when no key holds it; "" for an unnamed region
with no parent. preferParentKey puts the key path ahead of a global
name. The key comes from the parent's table, so a plain Lua assignment
resolves once the region is parented, as on retail.

The frame stack tooltip prints names through it, which removes the
debug tools' local _DebugName. Game::Lua::ObjectName exposes the
engine's GetName virtual for unnamed-aware callers.
2026-10-27 18:06:38 -05:00
Brues 04ce033907 feat(lua): retail SharedXML utilities and GetTickTime
Port six retail SharedXML files to !!!ClassicAPI: DataProvider,
CircularBuffer, EasingUtil, Interpolator, EnumUtil and StringUtil. Five
are verbatim. CircularBuffer drops retail's securecall and SecureTypes
wrappers, since 1.12 has no taint system. CallbackRegistry and
IconDataProvider now use EnumUtil.MakeEnum in place of inlined tables.

GetTickTime() returns the frame delta that OnUpdate receives, which
Interpolator needs. The engine keeps no copy of it after the frame
pass, so the UI render hook latches the value before any OnUpdate runs.
Events and C_Timer callbacks run earlier in the tick and see the
previous frame's value.
2026-10-27 18:06:17 -05:00
Brues 1f3ce9229d refactor: move the embedded addons into src/embed/AddOns
Users saw AddOns/!!!ClassicAPI at the repository root and downloaded it,
thinking the mod is only an addon. The addons are source code for the
DLL, so they now live next to the resource loader in src/embed/. The
README says that the DLL contains them and that the folder is not for
copying into the game.

Remove the AoELootTest dev addon.
2026-10-27 16:44:30 -05:00
Brues 091d2204a6 feat(debugtools): embed the debug tools in the DLL, load on demand
The DLL now embeds a list of addons instead of only !!!ClassicAPI. The
debug tools ship as ClassicAPI_DebugTools, a hidden, always-enabled
LoadOnDemand addon. /dump, /fstack, /etrace, /tinspect and /luaerrors
are stubs in !!!ClassicAPI that load it on first use, the way retail's
chat frame loads Blizzard_DebugTools.

The Blizzard_ name is not usable: the engine moves loose
Interface\AddOns\Blizzard* folders aside at startup and refuses a
Blizzard_* TOC without a signature.
2026-10-27 16:13:09 -05:00
Brues d93861d746 feat(tooltip): frame stack highlight, anchors, and GetSourceLocation
Retail's frame stack tooltip marks one entry and, after the list, prints
its anchors and the script that created it. Port both halves.

SetFrameStack now takes (showHidden, showRegions, highlightIndexChanged)
and returns the highlighted entry, as the current client does. The
marked line opens with "-->", regions list after their frame in
FRAMESTACK_REGION_COLOR, and ANCHORS / SOURCE sections follow the list.
The formats are the client's own, read from its string table; the
non-highlight indent and the ANCHORS header are inferred from it. Stratum
0 prints as WORLD, which 4.3.4's FrameStrataToString names and 1.12's
table does not. OnTooltipSetFrameStack now carries the highlighted entry
as its argument.

region:GetSourceLocation() (9.2.5) records where each frame was built:
a Lua CreateFrame takes the caller's "file:line" from lua_getstack /
lua_getinfo "Sl" inside the call, stepping over C levels, with the
chunk name as luaO_chunkid writes it; an XML frame takes the file
FUN_XML_LOAD_FILE is processing. Regions answer for their parent frame.
The XML file tracker moves out of Xml::ScriptPath into Xml::FileStack so
both consumers share it.

GetPoint on a screen anchor: CSimpleTop is a bare CLayoutFrame, and
Script SetPoint stores it as the relative layout for a nil relativeTo.
The stock reader forms `layout - 0x24` for it and reads the 36 bytes
before the top object as a region header. Frame::GetPointGuard now
implements GetPoint itself and pushes nil for the top, as 3.3.5 and
4.3.4 do; the frame stack's anchor lines test for it the same way. The
guard's header drops the claim that the engine never clears dependents'
anchors: CLayoutFrame::DestroyLayout does.

DebugTools: the frame stack runs the modern FrameStackTooltip on the new
method. Left/Right Alt move the mark, Ctrl (released) opens the marked
entry in the TableInspector, Shift adds texture information, fsobj is
set after an Alt press, and /fstack reads [showHidden [showRegions]]
through StringToBoolean. The modifier keys come from
MODIFIER_STATE_CHANGED instead of retail's polled KeyCommand table. The
green FrameStackHighlight cover and showAnchors are not ported: the
cover frames sit at TOOLTIP strata under the cursor and become the top
entry themselves.
2026-10-27 15:11:09 -05:00
Brues d9827852c7 docs(readme): fold Lua 5.1 into one Highlights table
Condense the six-row Lua 5.1 section into two rows of a single
Highlights table, and trim the soft targeting, combat log, and
#showtooltip rows. Full detail stays in docs/API.md.
2026-10-27 12:32:37 -05:00
Brues 2e75812339 fix(loot): stop unanswered loot requests from blocking all looting
The engine holds the player's loot target as it sends CMSG_LOOT, and
CanLootNow refuses every later loot while it is held. With no window
open only a server reply clears it, so a request the server never
answered locked looting until relog. LootAllCorpses while mounted hit
this reliably: the engine's right-click skips looting while mounted,
but FUN_CMSG_LOOT_UNIT has no such gate.

All loot senders now go through Loot::Request, which refuses while
mounted, reports whether the engine actually sent, and on timeout
releases a still-held target the way the release response does.

Fixes #113
2026-10-27 12:21:40 -05:00
Brues 1454dbe00c feat(spell): report isOnGCD from C_Spell.GetSpellCooldown
The engine's cooldown reader keeps the latest-ending of a history
record's spell, category and global legs. isOnGCD is true when a live
global leg carries exactly the start and duration it reported.
2026-10-27 12:08:47 -05:00
Brues 259071b647 fix(spell): report GetSpellInfo ranges through the engine resolver
GetSpellInfo and C_Spell.GetSpellInfo read the raw SpellRange.dbc row, so
range talents, spell mods, the ranged-item scale and the 0x404 flat range
were missing. Read min/max through FUN_GET_MIN_MAX_RANGE for the caster
(player, or pet for a "pet" book slot), and report 0/0 for a melee row,
as 4.3.4's Script_GetSpellInfo does.
2026-10-27 12:03:05 -05:00
Brues 2d887df71c fix(compat): stop Outfitter's minimap button acting as if dragged
Outfitter never initializes OutfitterMinimapButton.IsDragging, so a read
before the first drag falls through to the region:IsDragging() method
and is truthy. Its update frame then calls UpdateDragPosition every
frame with an unset CursorStartX. Set the field to false on load.
2026-10-27 10:19:15 -05:00
Brues 317539dbd8 fix(cooldown): keep a reverse frame's swipe full while its flash plays
A reverse sweep covers the icon as time passes, so at the end the icon is
fully dark. The sweep's end switched the frame to its flash state, where
UpdateColors cleared the swipe for both directions, and the flash's first
key has alpha 0. For the frames between the client-side end and the
aura's removal from the server (pfUI buffs with reverse timers), the bare
icon showed bright before the button hid.

3.3.5 and 4.3.4 never show this: they pin a reverse cooldown at
duration - 1 and never flash or hide it, so the icon stays covered until
the addon hides the button. The port took retail's timer semantics for
reverse (OnCooldownDone, flash times, hide after the flash) and dropped
the swipe with the hold.

Keep the retail state machine and 4.3.4's look: in the flash state a
reverse frame draws the full fan (what 4.3.4's flash branch draws for
reverse), set every tick so a timer already over at its first update does
not draw ResetVerts' zeroed fan, and UpdateColors keeps the swipe colour
for a reverse frame. The edge still goes with the flash, as in 4.3.4.

The docs/API.md line for SetReverse (direction corrected: the sweep starts
empty and becomes full) went in with 85b1365.
2026-10-27 01:16:47 -05:00
Brues 10d71371dd fix(equipmentset): pack main-bank locations as inventory slot ids
C_EquipmentSet.GetItemLocations encoded an item in the main bank as
BANK | bankSlot (1..24). The engine form, in both 4.3.4 and 3.3.5
Script_GetEquipmentSetLocations, is BANK | inventorySlotId: the value
BankButtonIDToInvSlotID returns (id + 39 in 1.12, verified), so bank
slot 3 is 0x40002A, not 0x400003. FrameXML relies on that form -- a
location without the BAGS bit goes straight to
GetInventoryItemID("player", slot) in
EquipmentManager_GetItemInfoByLocation, so the old code made the
shared helpers (and our EquipmentManager_GetLocationData) read the
paperdoll instead of the bank.

Add INVSLOT_BANK1 = 40 to Offsets.h, pack through it in PackMainBank
and invert it in UnpackContainer so UseEquipmentSet keeps swapping
from bag -1 with the 1-based slot Item::Swap::FromBag takes. Docs now
show the inventory-slot form and the 24-slot main bank.
2026-10-27 01:16:10 -05:00
Brues 4959c2c38c docs(sound): stop naming a file count for PlaySoundFile
API.md said only two files from PlaySoundFile can play at once. That is
the engine's on-disk cap for its bus, but it is not what the client
enforces here: SuperWoW's UncapSounds cvar lifts it, and a probe on this
client played 16 files at once. Describe the limit without a number and
keep the part that is true everywhere: a file holds its place until it
ends, a fading file still counts, and the call returns false at the limit.
2026-10-27 00:23:33 -05:00
Brues cece5a4214 feat(string): add strlenutf8, strcmputf8i, strsplittable and strconcat
The four Blizzard string globals still missing from the base library.
strlenutf8 and strconcat are 4.3.4's (a count of non-continuation bytes,
and lua_concat over the whole stack); strcmputf8i and strsplittable are
the newer clients'. Text::Utf8 mirrors 4.3.4 Storm's SStrLenUTF8 and
SStrCmpUTF8I, decoder and case fold included, since 1.12's Storm has
neither. strsplit and strsplittable share one scan; the table form never
grows the Lua stack. string.concat is the by-value twin of strconcat, as
string.split is of strsplit. Adds the lua_concat binding (0x006F44E0).
2026-10-26 23:49:10 -05:00
Brues 9daf3960c4 feat(combatlog): add SPELL_AURA_REFRESH, overkill and overhealing
SPELL_AURA_REFRESH is 4.3.4's "same spell in the slot, duration updated".
Aura::Source gains a Refreshed change: the player's SMSG_UPDATE_AURA_DURATION
for an occupied slot whose duration was already known (an application's
packet comes before the descriptor write, so its slot reads empty; the login
burst — Map::ExistingPlayerLogin, the one path that re-sends every duration
— finds no earlier duration because the table is cleared with the glue
screen), and for other units the recast the cache refreshed or a server
refresh mechanic it mirrors. Pending refreshes resolve at the world tick
against the descriptor, so a slot that changed hands in the same tick is an
application, not a refresh. The tick-speed compression nudge and duration
reductions do not count.

Overkill and overhealing follow 4.3.4's predicted health. The server sends
each damage and heal message before the tick's health update, so the target
still shows the health before it (verified live: 148, 113, 91, 63, 37, 10
under Fireballs of 34, 22, 27, 26, 27, then the kill); the messages since the
field was last read are kept as a delta so a tick's second hit counts its
first. A unit whose health the server hides (maximum 100, the stock
ShowHealthValues setting) gets 0.

Verified live: Frost Armor recast -> SPELL_AURA_REFRESH, nothing at login or
on a zone change; a 772 Fireball on a 194-health boar -> overkill 578.
2026-10-26 21:29:50 -05:00
Brues 39ab9eb1ee feat(combatlog): name the damage shield, the dispelling spell and the instakill caster
Three values 1.12's messages leave out, read from what the client already
holds at the moment each message arrives.

DAMAGE_SHIELD: the owner's one damage-shield aura (EffectApplyAuraName 15)
of the damage's school names the shield — Thorns, Fire Shield, Retribution
Aura. Two of one school on one owner, or an owner out of view, keep the
unnamed form.

SPELL_DISPEL, SPELL_DISPEL_FAILED and SPELL_INSTAKILL: the server sends each
from the spell's effect handler, in the same tick as and after that cast's
SMSG_SPELL_GO. CombatLog::RecentCasts keeps the last second of hit lists,
fed from Casts.cpp's existing SPELL_GO parse, and names the caster's newest
cast at the target with a dispel effect (38, 108), or the caster of the
newest cast of the instakill spell at the victim. A dispel from an aura
(Abolish Poison) has no cast and stays unnamed.

Verified live: Remove Lesser Curse -> SPELL_DISPEL 475 "Remove Lesser Curse"
"Curse of Tongues"; a druid's Thorns -> DAMAGE_SHIELD 9910 "Thorns".
2026-10-26 20:55:52 -05:00
Brues e8bd35d8e4 feat(combatlog): log immune damage and summons from packets 1.12 already sends
SMSG_SPELLORDAMAGE_IMMUNE (0x263) becomes DAMAGE_SHIELD_MISSED / IMMUNE
(SPELL_PERIODIC_MISSED when the debug byte is set), the mapping 4.3.4 and
3.3.5 use. 1.12 writes its IMMUNESPELL line from the handler's own
formatter, not the miss writer Miss.cpp hooks, so the event never fired.

SMSG_SPELLLOGEXECUTE: read the summoned GUID the server writes for the
summon-family effects (tortoise Spell::SendLogExecute), which 1.12's reader
leaves unread in the buffer. A unit is SPELL_SUMMON, a game object or
dynamic object SPELL_CREATE. Portals stay silent: every portal spell has
Attributes 0x100, the hide-from-log bit both the engine's lines and 4.3.4
honor.

Verified live: Healing Stream Totem -> SPELL_SUMMON, Fishing -> SPELL_CREATE
"Fishing Bobber", Fireball on an immune Fireguard Destroyer ->
DAMAGE_SHIELD_MISSED IMMUNE.
2026-10-26 20:46:09 -05:00
Brues f4d8f56c59 feat(editbox): add history lines at the end of the ring, as retail does
The engine's history ring uses one position for writing and for Up/Down
browsing, so a line sent after browsing overwrote the line the browsing
reached, and later sends overwrote the newer lines after it. Keep each
box's write position beside the engine's field and put it back before
every add, so a new line always lands at the end and the next Up starts
from it. Like retail, a line equal to the newest one (case-sensitive) is
not added again.
2026-10-26 19:29:12 -05:00
Brues 3f33320724 feat(item): add IsDualWielding and drop the OffhandHasWeapon override
IsDualWielding() ports 4.3.4's Script_IsDualWielding (0x00452A50): true
when the off-hand item is weapon class and the player can dual wield.

OffhandHasWeapon is a native 1.12 global (0x004C9570, same body as
3.3.5/4.3.4: off-hand item class 2 -> 1, else nil). Our override
returned booleans and tested inventory type instead, so remove it and
let the engine's own function stand.

Item class IDs 2 (Weapon) and 12 (Quest) are now used in more than one
file, so they move to Offsets.h as ITEM_CLASS_WEAPON / ITEM_CLASS_QUEST
(verified against ItemClass.dbc).
2026-10-26 18:55:56 -05:00
Brues 492085ac0c feat(aura): add aura instance IDs and the UNIT_AURA_DELTA event
1.12 has no aura identity: a unit's descriptor holds 48 spell IDs and
nothing that tells one application from the next. Aura::Instance gives
each visible aura an ID when it lands in a slot and keeps it until the
aura leaves; IDs are never reused. One sync step (recorded slot vs live
descriptor) drives everything: the existing Aura::Source add / remove /
stacks observers sync the slot they name, the getters sync before
answering, and a per-frame reconcile catches bulk clears and rebuilt
objects. No new engine hooks.

UNIT_AURA_DELTA(unitTarget, updateInfo) carries retail's UNIT_AURA
payload under its own name, so the engine's UNIT_AURA is untouched. It
fires once per unit per frame, per token, with instance-ID lists only,
in four reused tables, so a fire allocates nothing. With no listener,
no change sets are kept. Timing-only refreshes (cache rewrites, the
player's duration packet) are reported as updated.

Also:
- auraInstanceID on every AuraData table and on C_LossOfControl CC
  entries
- C_UnitAuras.GetAuraDataByAuraInstanceID(unit, id [, buf]); the buf
  form fills the caller's table
- Game::Lua::Ref, the shared luaL_ref binding, replacing two local
  typedefs in the animation code
2026-10-26 18:39:03 -05:00
Brues 7b3b61de15 fix(lossofcontrol): take CC timing from the server's player aura timer
The CC scan read its timing from the cast-observation cache, which holds
a client-side estimate: base duration for another caster's spell, and no
diminishing returns at all. For the local player the server sends the
applied duration in SMSG_UPDATE_AURA_DURATION, and the engine keeps its
expiry in the player buff expiration table.

Record that packet's duration per slot and expose both through
Aura::Data::PlayerAuraTiming. C_LossOfControl uses it for every CC
debuff, and C_UnitAuras now reports the applied duration for the
player instead of the base or cached estimate.
2026-10-26 18:03:12 -05:00
Brues 77efe8d796 fix(unit): read feign death from the dynamic flags, as 3.3.5 does
UnitIsFeignDeath tested UNIT_FIELD_FLAGS bit 29. tortoise-wow sets that
bit next to UNIT_DYNFLAG_DEAD, but vmangos sets only the dynamic flag,
so the getter always returned false there. 3.3.5's
Script_UnitIsFeignDeath (0x0060F3D0) tests UNIT_DYNFLAG_DEAD.
2026-10-26 17:56:10 -05:00
Brues 8378f3c350 chore(doc): drop the per-pass registration count log
Every install wrote "[doc] <env> pass: N registrations recorded, M
undocumented" to classicapi_debug.log on each glue and game pass. It
helped no one, and _classicapi_UndocumentedAPI() already answers the
question on demand. Removes the line and the counter that only fed it.
2026-10-26 17:35:54 -05:00
Brues 1a2f806f16 fix(event): skip the slots the engine fires by number
A NULL name in the event table did not mean the slot was free. The
engine fires events by id, and two NULL-named in-game ids still fire:
the glue band (ids 0..25, including ADDON_LIST_UPDATE at 6, which the
SMSG_ADDON_INFO listener fires whichever table is installed) and chat
type 89's id 540. Our low walk put the 5th custom event on slot 6.

Claimable() now requires an id past GLUE_EVENT_COUNT that is not in the
engine's chat-type id table, read live. Both the claim walk and Grow's
headroom count use it. Verified against benilla-re's fire-site census
and this exe's own name initializer; a live dump puts our 77 events at
31..110 with nothing below 26.
2026-10-26 17:33:12 -05:00
Brues 90be617700 fix(equipmentset): play the drop sound when a held set is cleared
1.12's cursor clear plays INTERFACESOUND_CURSORDROPOBJECT from a kind
table that stops at 10, so the set (13) dropped silently. Co-hook it
with 4.3.4's set arm: reset the ID and play the sound, then run the
engine's shared tail.
2026-10-26 17:18:45 -05:00
Brues 45b54e89ba fix(equipmentset): drop a held set on right-click
The world input hook's right-press clear tests the engine's payload
globals rather than the cursor type, and an equipment set has none, so
the press fell through. Co-hook it to clear and consume for our type.
2026-10-26 17:11:00 -05:00
Brues 35b8eaa376 feat(tooltip): grow the line pool on demand, as 4.3.4 does
Replace the scan-time grow to a fixed 60 lines with 4.3.4's
CGTooltip::AddLine grow: co-hook the add-line gate (FUN_00530270, which
every Lua method and native builder goes through) and, when the line
about to be added takes the last slot, build the next TextLeft/Right
pair and append it through the engine's own AddFontStrings body
(FUN_00529940). The pool keeps one spare line after every add, with no
cap, and tooltips no longer pre-build 30 unused line pairs.

New lines start hidden (the clear only hides lines below numLines) and
take the engine's line gap constant instead of a literal.
2026-10-26 16:44:34 -05:00
Brues f5082cedee fix(texture): keep NPOT out of the recycle caches, allow sides below 8
The dimension gate routes NPOT textures around the recycle pool on
allocation, but the free path filed them anyway: TexturePoolRelease
buckets by each side's power-of-two factor with no POT test, so a freed
48x48 landed in the 32x32 bucket and was handed to the next 32x32
request. Pool on free exactly what the allocator pools (POT, no larger
than the pool max), as 4.3.4's GxTexReusable does.

The decoded-buffer cache (TextureAllocMips / TextureFreeMips) buckets
the same way, so an NPOT BLP on the model/character cache path could be
given a smaller cached buffer and decode past it. NPOT sizes now take
the engine's own uncached alloc and free.

The create validator's 8px minimum is lowered to 1, so 1x1 and 4x4
textures load. A failed D3D create leaves the texture blank.
2026-10-26 16:31:10 -05:00
Brues cca8ff3c55 feat(frame): pass 3.3.5's click down and enter/leave motion
3.3.5 runs OnClick/PreClick/PostClick as (self, button, down) and
OnEnter/OnLeave as (self, motion). 1.12's runners carry only
%d/%u/%f/%s, and neither value reaches the script.

Frame::ScriptArgs gains AutoTrailingBool: a provider supplies one boolean
that becomes the last argN and positional argument of a run on the
positional path. Handlers that declare no parameters keep vanilla's
globals.

- down: the click vmethod gets (mask, fromScript) and never learns press
  or release, but its callers do. The six 3.3.5 maps onto -- the press
  handler (down = 1), the release handler (0) and Script_Click's four
  name branches (StringToBOOL(L, 3, 0), as 3.3.5's Click reads it) --
  each `call [edx+0x94]`, now replaced with a thunk that records
  {button, down} and jumps through the same slot. The click detour takes
  the record for its own button and offers it to that button's
  OnClick/PreClick/PostClick runs.
- motion: the mouse-focus pass 0x007660D0 is 3.3.5's OnMouseMove. Its
  re-pick passes the context's saved event (+0x1104), the same test
  3.3.5 uses for motion. A co-hook records {context, old focus, motion}
  for the pass; its own leave (old focus) and enter (new focus at +0x7C)
  get motion, and every other enter/leave gets false.

Verified in-game: enter/leave on a mouse move give true, and a hide and
show under a still cursor give false. A press and release on a button
registered for both give down true then false, Click("RightButton",
true) gives true, and Click() gives false.
2026-10-26 16:04:23 -05:00
Brues b4256406f5 fix(frame): match 3.3.5's script runner on arg count, global saves and event
Three differences from 3.3.5's FrameScript_Execute (0x00819EA0):

- No argument limit. The engine runner sets only arg1..arg19 (0x704F10
  stops at the 19th spec, 0x704F73), and our parser copied that limit for
  the positional args too. 3.3.5 sets every argN. The parser is replaced by
  a cursor over the format, and a fire with more than 19 values takes the
  reimplemented path even for a handler that declares no parameters.
  argN names come from snprintf; the old two-digit builder misnamed arg100
  onward.
- Raw saves. The old this/argN values and the positional `event` are read
  with rawget, as 3.3.5 does, so a `_G` __index (a strict-globals guard)
  no longer runs for an unset argN.
- `event` per handler. The engine dispatchers set `event` once for the
  whole dispatch, so a handler that assigned the global changed it for
  every listener after it. Each OnEvent run now saves `event` before the
  handler and restores it after, on both runners and RunWithValues, as
  3.3.5 does per handler. No new hooks; off while SetModernScriptArgs is
  false.

Verified in-game: two listeners that each print `event` and then set it
both print PLAYER_TARGET_CHANGED, and a `_G` __index sees no `this` read
from a modern handler's run.
2026-10-26 15:51:01 -05:00
Brues 2adabbbd70 fix(frame): pass positional script args to C-function handlers
The arity gate on Frame::ScriptArgs sent every C closure except the
HookScript wrapper through the original no-arg runner, on the premise
that C functions never read positional args. Frame methods do: they take
`self` from argument 1 and raise "Attempt to find 'this' in non-table
object" without it, never falling back to the `this` global. So the
common modern idiom

    f:SetScript("OnDragStart", f.StartMoving)

errored, where 3.3.5's FrameScript_Execute passes (self, ...) to every
handler.

Treat any C closure as wanting args. This cannot regress a working
vanilla addon that binds a frame method, since that call already errored.
The Lua-closure gate from a4d6290 stays as is.

Verified in-game: a frame with OnShow = f.Hide stays hidden, a param-less
vanilla handler still sees this/arg1, and OnDragStart/OnDragStop bound to
f.StartMoving/f.StopMovingOrSizing drag the frame.
2026-10-26 15:41:48 -05:00
brues-code 42ed0d27c7 Port the later clients' Cooldown API (#112)
* Add retail Cooldown methods and OnCooldownDone

Port the post-4.3.4 Cooldown API onto the native CGCooldown frame:
Clear, Pause/Resume/SetPaused/IsPaused, GetCooldownTimes,
GetCooldownDuration, GetCooldownDisplayDuration, SetCooldownDuration,
SetCooldownFromExpirationTime, the modRate argument, SetDrawSwipe,
SetDrawBling, SetSwipeColor, SetEdgeColor, the drawSwipe/drawBling XML
attributes, and the OnCooldownDone script (via Frame::ExtraScripts).

Behavior follows retail probes, not the generated doc strings: the
getters report the end flash once the sweep ends, modRate scales the
flash and the display duration but not the sweep, and a reverse
cooldown flashes and hides like any other.

Add CooldownFrame_Set, CooldownFrame_Clear and
CooldownFrame_SetDisplayAsPercentage to the embedded addon.

* List the new Cooldown methods in the README table

* Add Cooldown swipe, edge and bling textures

SetSwipeTexture, SetEdgeTexture and SetBlingTexture, and the
<SwipeTexture>, <EdgeTexture> and <BlingTexture> XML elements, split
4.3.4's star texture into three slots. An empty file is the engine's
solid texture tinted by the slot colour, and Interface\Cooldown\edge
maps to the built-in edge texels. A setter without r, g, b keeps the
colour, as retail does. Slots left unset get 4.3.4's textures at the
first SetCooldown, so the defaults stay 4.3.4's. The swipe's texcoords
now map its positions over the frame so a custom texture lines up.

* Add Cooldown rotation

SetRotation / GetRotation and the XML rotation attribute (degrees) move
where the sweep starts, clockwise from the top, as retail does. The
sweep is now one polygon along the frame's outline in place of 4.3.4's
four octant functions, with the same timing (each half side an eighth
of the duration) and, at rotation 0, the same shape. The one difference
is 4.3.4's reverse octant 1, which drew one triangle twice.

* Add Cooldown countdown numbers

Every Cooldown gets a countdown font string (FRIZQT__ 16 OUTLINE,
centred), shown while retail's countdownForCooldowns CVar is 1; the
CVar defaults to 0, so the default look stays 4.3.4's. The text
follows retail: seconds, then m:ss below the abbreviation threshold,
then whole minutes, hours and days rounded up, and nothing for
cooldowns no longer than the minimum duration or during the flash.
Adds SetHideCountdownNumbers / GetHideCountdownNumbers,
GetCountdownFontString, SetCountdownAbbrevThreshold /
GetCountdownAbbrevThreshold, SetMinimumCountdownDuration /
GetMinimumCountdownDuration and the hideCountdownNumbers and
minimumCountdownDuration XML attributes.

* Add the Cooldown countdown milliseconds threshold

SetCountdownMillisecondsThreshold / GetCountdownMillisecondsThreshold:
below the threshold the numbers show tenths, rounded up, as retail
does (threshold 5: 4.973 shows 5.0, 3.24 shows 3.3, 0.039 shows 0.1).
The default is 0, so the numbers stay whole seconds.

* Fix the Cooldown review findings

- A zero-length timer (a new frame, SetCooldown(t, 0)) hides without the
  bling flash or OnCooldownDone, instead of flashing and reporting
  (now, 1000) from the getters.
- Countdown text rounds up with integer math (700 ms read "0.8") and
  picks its unit on the rounded-up seconds (59.4 s read "60", not "1:00").
- SetMinimumCountdownDuration and minimumCountdownDuration clamp to the
  uint32 range.
- The edge texcoord rotation uses the guarded done fraction (0/0 gave NaN).
- Texture slots are one array with per-slot tag, default file and draw
  layer (Offsets::DRAWLAYER_*), replacing the ternaries and bare 2/3.
- The header lists where the state machine follows retail over 4.3.4.

edge.blp is now served to every texture load by texture/Builtin.cpp, a
hook on TextureCreateFromBlp that falls back to the DLL's texels only when
SFile has no such file; TextureCreate caches and ref-counts it like a file.
Cooldown loads it by path and drops its edge special case.

Frame::Region::CreateTexture / CreateFontString replace the hand-rolled
pool-alloc + ctor copies in Cooldown, LinePool, BarTexture, SoftTargetIcon
and InlineTexturePool.
2026-10-26 15:21:34 -05:00
Brues 0d19deaee0 Add ItemHasRange global and C_Item.ItemHasRange
Global returns 1/nil like 3.3.5; namespaced form returns a bool. Both resolve the item to its on-use spell and use the shared SpellIDHasRange engine check. Verified in-game: ItemHasRange(1251) -> 1, C_Item.ItemHasRange(6948) -> false.
2026-10-26 00:38:59 -05:00
Brues abd5367533 feat(nameplate): exempt plate subtrees from inherited alpha, add selected/non-selected alpha CVars
Default nameplates and anything parented under them keep vanilla alpha semantics, so third-party overlays like pfUI's are never dimmed by the engine fade or multiplied by a parent. The plate fade emulates the original setter but spares children with an explicitly-set alpha. nameplateNotSelectedAlpha (0.5) and nameplateSelectedAlpha (1) resolve the fade's legacy 0x7F/0xFF writes; both defaults are byte-identical to vanilla.
2026-10-25 19:54:51 -05:00
Brues 3e83827ae9 fix(spell): Route spell has-range gate through the engine's GetMinMaxRange
SpellIDHasRange now calls 0x6E3480 and tests both bounds against the ActionHasRange epsilon instead of reading raw SpellRange.dbc values, covering Attributes & 0x404 spells, melee reach folding, and the stationary/item/modifier bonuses. Centralizes the SpellRange record min/max offsets in Offsets.h (used by GetSpellInfo). Updates API.md (SpellHasRange mechanism, Fireball 35yd).
2026-10-25 02:30:14 -05:00
Brues 443c78c453 Backport TOTAL_MEM_*_ABBR and ADDON_MEM_*_ABBR locale strings 2026-10-25 00:31:22 -05:00
Brues a97909e36c Route non-Turtle spell links to SetItemRef; one SetItemRef hook
Turtle's SpellChatLinks.lua overrides ChatFrame_OnHyperlinkShow and
handles spell: links itself, so those clicks never reach SetItemRef --
and its spell:(%d+):(%w+):(%w+) pattern silently drops anything shaped
differently, including our own spell:<id>:0 links (GetSpellLink).
Wrap ChatFrame_OnHyperlinkShow to route those back through SetItemRef
(the Spell handler shows them); Turtle-shaped links pass through.

Also folds TradeSkillLink's second SetItemRef override into a
LinkUtil.RegisterLinkHandler, leaving exactly one override to chain.
Adds a GetSpellInfoFromHyperlink helper.
2026-10-24 23:17:00 -05:00
Brues 89f8932b35 Add FlashClientIcon([briefly]) system API
Flashes the client taskbar button via FlashWindowEx on the engine's own
game window (OsGuiGetWindow(0), 0x00435C30). Default flashes until the
client is focused; briefly=true flashes three times. No-op while WoW is
foreground. Documented in docs/API.md + README reference table.
2026-10-24 18:15:27 -05:00
Brues 829b1cfed3 fix(bindings): hide a key's modifiers only around direct actions
v1.16 ran 4.3.4's key-state override around every key binding, so a Lua
binding on SHIFT-E saw IsShiftKeyDown() as nil inside its own handler.
1.12 addons that bind modified keys and read the modifier there
(Puppeteer) cast their unmodified action instead.

The override now covers only SPELL / ITEM / MACRO / CLICK, the commands
1.12 never had; Lua bindings see the held keys, as before v1.16.
2026-10-24 09:41:00 -05:00
Brues 33804bb66d fix(playercache): load account settings before reading the cache toggle
The name hook, Lookup, LookupByName and Remember read g_enabled
directly, so the cache stayed off all session unless something else
loaded the account settings first. Only an IsEnabled/SetEnabled call
or a custom GlueXML's GetSavedCharacterOrder did, so with stock
GlueXML the persistent cache never saved or answered until the options
panel was opened. Route every gate through IsEnabled().
2026-10-23 20:57:25 -05:00
Brues 80d3e5d8d7 refactor(playercache): drop the visible-object scan, import the engine cache on enable
The scan read names through CGUnit_C::GetUnitName, whose only filled
rows come from the NameCache writer the module already hooks, so it
re-read data the hook had mirrored. The one real gap was rows the
engine resolved while the cache was off; enabling now imports them by
walking the engine NameCache (Unit::Identity::ForEachCachedPlayer).

Removes C_PlayerCache.SetScanEnabled/IsScanEnabled, the
NameCacheScanEnabled setting and the "Scan nearby players" option.
2026-10-23 20:54:05 -05:00
Brues bfcd95504e fix(addon options) Correct header 2026-10-23 20:37:25 -05:00
Brues bea82687a4 refactor(addon options) Move Player Cache settings to their own subcategory 2026-10-23 20:36:47 -05:00
Brues 63078578b4 refactor(game): route every SStrCmpI call through Game::StrCmpI
Twelve files each declared their own SStrCmpI function-pointer type and
cast FUN_SSTR_CMP_I at the call. One wrapper in Game now owns the
__stdcall signature (a __cdecl copy drifts ESP by 12 per call) and the
"whole string" length default. Tooltip::Hyperlink's prefix test moves
from the CRT _strnicmp to the same wrapper, which the engine's SStrCmpI
calls anyway.
2026-10-23 20:01:37 -05:00
Brues c7bb90895f feat(playercache): resolve names through the engine name cache
C_PlayerCache.GetPlayerInfoByName now searches the engine's session name
cache (every player it has named since world entry) after the friends
list, so past chat senders resolve with the persistent cache off. The
engine has no by-name lookup, so Unit::Identity::GuidForCachedName walks
the cache's node list the way NameCacheSave (0x0055EC70) does.

The persistent NameCache now matches names ignoring ASCII case, the same
rule as the engine's SStrCmpI, so every lookup step behaves alike.
2026-10-23 19:58:23 -05:00
Brues cd7f830697 feat(target): highlight the soft-interact object in reach
softinteract glows like the mouseover object while the player can interact
with it right now, through the engine's own CGObject_C::SetLight/ClearLight
on a light bit of its own (bit 2, past the target's 0 and the mouseover's 1).
2026-10-23 18:39:53 -05:00
Brues 557dc2f454 docs(readme): merge the soft-target rows and add a combat log row 2026-10-23 17:43:15 -05:00
Brues 6c5269e3e6 feat(profiling): add per-addon memory and CPU usage
Backport UpdateAddOnMemoryUsage / GetAddOnMemoryUsage and the script
profiling family (scriptProfile, GetFunctionCPUUsage, UpdateAddOnCPUUsage,
GetAddOnCPUUsage, GetFrameCPUUsage, GetEventCPUUsage, GetScriptCPUUsage,
ResetCPUUsage), mirroring 3.3.5's engine mechanism.

- Gc::Hooks owns the GC lifecycle hooks (luaC_link, newlstr,
  luaS_newudata, freeobj); Gc::Tag stamps each new object with the
  engine's context word (3.3.5's lua_tainted rule) and sums sizes with
  the engine's own free sizes.
- lua_gctag pins: the addon load window (two call patches in
  FUN_ADDON_LOAD_ONE) and template application (engine single-name
  sites + Xml::Inherits lists).
- Profile::Cpu keeps 3.3.5's per-closure Profile records through Lua's
  own call/return hook, installed only when scriptProfile is 1; tail
  calls, error unwinds and coroutines handled.
- ScriptArgs observers time every handler run; signals counted at each
  dispatcher (call-site redirect inside FUN_FIRE_EVENT, not a MinHook).
- Frame::ScriptSlots enumerates a frame's script slots without creating
  them, for GetFrameCPUUsage.
- Add the unordered_dense submodule (v5.3.2); share ResolveRecord via
  addons/Registry; fix the AddOnEntry inline-name comments.
2026-10-23 15:31:39 -05:00
Brues b5aed30a5d feat(chat): add GetCurrentChatEvent
Returns the event name and arguments of the CHAT_MSG_* event being fired,
read from the fire itself rather than the event/arg globals, which 1.12's
ChatFrame_OnEvent depends on and any earlier handler or hook can overwrite.
Nested chat events restore the outer payload when they return.
2026-10-23 03:05:09 -05:00
Brues 9755cd3e09 feat(gossip): fire DYNAMIC_GOSSIP_POI_UPDATED and document the POI API
Diff the gossip marker's x, y and expiry once per frame: each set
rewrites them and both clears (10 yards, 480 s) zero them. The map
rebuild that every change runs also runs on each map view change, so it
is not a usable trigger on its own. Add the two POI functions and the
event to README.md and docs/API.md.
2026-10-23 01:44:22 -05:00
Brues 604d87b9fc feat(gossip): add C_GossipInfo.GetPoiForUiMapID and GetPoiInfo
Read the gossip marker from static blip record 1, where the
SMSG_GOSSIP_POI handler stores it, and place it on a map with the world
map's own test (0x004A7360): same map id and inside 0..1. The packet
carries no POI id and the engine holds one marker, so its id is 1.
2026-10-23 01:37:53 -05:00
Brues 6b0a74ec4b fix(gossip): gate C_GossipInfo on the greeting-pending flag and walk visible options in SelectOptionByIndex
The gossip GUID is latched before the greeting resolves, so GUID != 0 alone
served a window that had not shown yet, with the previous NPC's text. Honor
the engine's pending flag (0xBBB670), the same one its option selector checks.

SelectOptionByIndex used orderIndex - 1 as the storage slot; it now skips
hidden slots the way GetOptions numbers them.
2026-10-23 01:30:06 -05:00
Brues 165ccf3e9c refactor(lua): share the engine's flag readers as Game::Lua::ToFlag and Game::StringToFlag
Twenty modules each declared their own typedef or wrapper for
FUN_LUA_TO_BOOLEAN_LOOSE (4.3.4's StringToBOOL(L, index, default)) or
FUN_XML_ATTR_TO_BOOL (StringToBOOL(const char *)). Route them all
through one helper each.

frame/Cooldown.cpp had a C++ copy of both that read unknown attribute
text as true; the engine's reader, which 4.3.4's XML loader uses, reads
it as false. SetReverse/SetDrawEdge now also truncate numbers like
every other 1.12 flag method.
2026-10-23 01:15:38 -05:00
Brues ce4f80518f fix(tooltip): match 4.3.4's SetSpellByID and AddSpellByID
Take (spellID [, isPet [, showSubtext]]), pass the spell's remaining
cooldown to the engine builder as 1.12's SetSpell does, and return 1
when the cooldown line shows, else nil. The rank is now off by default
(showSubtext turns it on), and a bad ID raises 4.3.4's
"Invalid spell ID in %s:SetSpellByID".

AddSpellByID rewrites the builder's "Next rank:" header through the
engine's add-line, so showSubtext works when appending, and leaves a
recipe's created-item tooltip untouched.
2026-10-23 01:07:00 -05:00
Brues 3009c6d8d2 fix(addon): splice the AddOn Options menu button on first show
Addons that load after us insert their own game menu buttons by taking
Key Bindings' anchor too. ShaguTweaks anchors "Advanced Options" under
Interface Options, which put it on top of our button. Waiting for the
menu's first show lets every addon place its buttons first, so ours goes
right above Key Bindings wherever it ended up.
2026-10-22 23:05:22 -05:00
Brues b83bb5b52b feat(frame): draw the Cooldown sweep natively, as 4.3.4's CGCooldown
A Cooldown was vanilla's indicator Model with CooldownFrameTemplate loaded
into it, so SetReverse and SetDrawEdge stored flags that changed nothing,
and every cooldown paid a Model's per-frame cost.

Cooldown is now a CSimpleFrame subclass built the way CGCooldown::Create
builds it: one SMemAlloc block, the engine's frame constructor, and copies
of CSimpleFrame's two vtables with 4.3.4's overrides in their 1.12 slots
(update, layer emit, alpha, size change, LoadXML, identity, destructor).
It runs 4.3.4's sweep / flash / reverse state machine and queues the star
fan, flash and edge as layer-batch strips animated in place.

- The five methods live in a class method hash of their own, so only a
  Cooldown has them; it is released after CGGameUI's unregister pass.
- GetObjectType / GetFrameType answer through the engine's virtuals; the
  Lua re-registrations are gone.
- star4.blp ships with 1.12; edge.blp does not, so its 16x16 image is
  created in memory through TextureCreateWithCallback.
- A Cooldown inheriting the stock Model CooldownFrameTemplate applies
  4.3.4's template (setAllPoints, hidden); reverse / drawEdge XML
  attributes are read.
- CooldownFrame_SetTimer calls SetCooldown on a Cooldown and keeps 1.12's
  body for the Models stock buttons use.
- Mask.cpp's path loader moves to texture/Load; frame/RenderBatch queues
  quads into a layer batch.

Verified in-game: sweep, flash and hide; reverse with the edge line;
stock action-button cooldowns unchanged; repeated /reload.
2026-10-22 22:15:17 -05:00
SkeewirtandBrues f30efb29b1 feat(gossip): add GetNumGossipAvailableQuests and GetNumGossipActiveQuests (#95)
* feat(gossip): add GetNumGossipAvailableQuests and GetNumGossipActiveQuests

The 2.0+ globals count the quests GetGossipAvailableQuests /
GetGossipActiveQuests list. Vanilla sizes those lists with two engine
counters (0x004E2430 / 0x004E2580: walk the gossip quest array, split
by status 3|4), so push those counters and the counts always match the
lists. Zygor Guides Viewer's auto-accept/turn-in loops over them.

Not verified in-game yet beyond both functions existing. The testkit
compares the counts with the lists (two values per quest, as 1.12's
GossipFrame reads them) the next time a gossip window with quests opens.

* docs(gossip): move GetNumGossip*Quests to the end of the section

* docs(gossip): reword GetNumGossip*Quests without version or impl notes

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-22 19:40:11 -05:00
SkeewirtandBrues 19b6232e43 feat(addon): backport the Interface Options panel for addon categories (#85)
* feat(addon): backport the Interface Options panel for addon categories

Later clients list addon option panels in InterfaceOptionsFrame; addons
register them with InterfaceOptions_AddCategory (Ace3's AddToBlizOptions
does it for every Ace3 addon) and open them with
InterfaceOptionsFrame_OpenToCategory. Vanilla has neither, so Ace3 addons
fail while initializing - Zygor Guides Viewer 2.0's OnInitialize stopped
there, before its waypoint arrow and taxi data were set up.

FrameXML/InterfaceOptions.lua/.xml in the bundled addon: the frame with
its background as first region, the AddOns category list (buttons /
buttonHeight / update, a FauxScrollFrame named
InterfaceOptionsFrameAddOnsList), an empty Categories list, the panel
container, Okay / Cancel / Defaults, InterfaceOptionsListButtonTemplate,
and the later-client panel protocol (name, parent nesting with collapse,
okay / cancel / default / refresh). Names match later clients because
addons and libraries use them directly. Vanilla's own options stay where
they are.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
Zygor's AceConfigDialog-3.0 panels register under AddOns and open, and
their pages were used throughout testing (with the SetParent level and
scroll-clip fixes, sent separately). Not checked specifically: Okay,
Cancel and Defaults calling each panel's handlers, and collapsing a
category with children.

* feat(addon): open Interface Options from the game menu, Escape cancels

The backported InterfaceOptionsFrame had no way in for the player and
closed on Escape without calling any panel's cancel. Wired the way
3.3.5 does it, with one code path for Stock and Turtle:

- AddOn Options button in GameMenuFrame. It takes over Key Bindings'
  anchor (Interface Options on Stock, Options on Turtle) and Key
  Bindings moves under it, so pfUI's top-of-menu buttons are untouched.
  Not "AddOns": later clients use that for the addon list. The window
  title shares the new ADDON_OPTIONS string.
- Native center panel via UIPanelWindows + Show/HideUIPanel instead of
  UISpecialFrames; closing returns to lastFrame (the game menu), like
  Turtle's own OptionsFrame.
- Escape clicks InterfaceOptionsFrameCancel after static popups, the
  3.3.5 ToggleGameMenu order.
- Shown panel kept in InterfaceOptionsFramePanelContainer.displayedPanel,
  where addons read it.

Verified in-game on Turtle with pfUI: button placement and menu sizing.

* feat(addon): add a ClassicAPI page to AddOn Options

Registers ClassicAPI in the backported InterfaceOptionsFrame with
Controls, Combat and Text To Speech pages under it:

- ClassicAPI: player cache (C_PlayerCache.SetEnabled / SetScanEnabled;
  scan is greyed out while the cache is off).
- Controls: Enable Interact Key, Interact Key Icons, Auto Stand, Auto
  Dismount, Auto Cancel Form.
- Combat: Enable Action Targeting, Enable Friendly Action Targeting,
  Cast action keybinds on key down, Stop Auto Attack.
- Text To Speech: voice, rate, volume.

Where retail's Settings has the option, the label, tooltip and value
mapping are copied from Blizzard_SettingsDefinitions_Frame (soft
targeting toggles 3 = Any / 1 = Gamepad; Interact Key Icons drives the
same four cvars as retail's three presets). The 18 retail strings are
added to every locale from Blizzard's own translations. Player cache,
cast settings and friendly soft targeting have no retail labels, so
those strings are ClassicAPI's own (English).

Changes apply at once; Cancel / Escape restores each page to what it
held when first shown, Defaults resets the shown page via
GetCVarDefault.

Not yet verified in-game.

* docs(readme): drop the InterfaceOptions row from the API table

The table lists engine API; the InterfaceOptions functions are FrameXML.
They stay documented in docs/API.md.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-22 19:20:45 -05:00
Brues bbac6b9cac fix(cvar): match SetCVar and honor staged cvars in SetTempCVar
A value lua_tostring cannot convert now becomes "0", and the read-only
error says "read-only", both as Script_SetCVar does. Staged cvars (gx*,
Sound*) park a set at +0x38 and dirty the config unconditionally, so the
temp value reached Config.wtf; the tracked value and the config-writer
swap now cover the staged slot too.
2026-10-22 18:10:07 -05:00
Brues e48e4e2361 fix(spell): land only the reticle our own cast opened
CastAtCursor, UseAtCursor and UseAtUnit could commit a reticle the
player had armed by hand: the cast dispatcher returns nothing and an
attempt the engine refuses early leaves the old placement up. Placing
calls now cancel any open placement first (0x6e4900, the engine's own
new-cast cancel), and item calls commit only when CGItem::Use reports
the spell began.

The commit now honors 0x6e60f0's result: placed means bound AND no
target left, since the engine sends the cast only when the targeting
word empties. A spell still wanting a target is cancelled.

UseAtUnit gains placeGroundSpell, returns true for a unit-target item
used on the unit, and resolves the token once, matching CastAtUnit.

The shared placement and dispatch code moves to Spell::Placement; item
use goes through one Item::Use::UseItem; one macro extractor tags both
spellIDs and quoted names for CastAtCursor, CastAtUnit and
CastSpellNoToggle. UseAtCursor and UseAtUnit get doc descriptors.
2026-10-22 17:59:11 -05:00
Brues 09cd9040f7 fix(item): open wrapped gifts in IsItemOpenable
The tooltip's <Right Click to Open> test has a second arm we missed:
template flag 0x200 (wrapper) with the instance's wrapped bit 0x08.
Unused wrapping paper carries 0x200 too, so the arm needs the bit.

Also corrects the Offsets.h claim that descriptor bit 0x08 is
"broken" -- GetInventoryItemBroken uses durability and only excludes
wrapped items with that bit.
2026-10-22 17:29:16 -05:00
Brues 8f79084c57 feat(item): add IsEquippableItem and resolve item names
Port the rest of 3.3.5's Script_IsEquippableItem. The global
IsEquippableItem returns 1/nil, and C_Item.IsEquippableItem keeps its bool.
Both share one check (any non-zero inventory type), and both now resolve a
carried item's name through Item::Location::IDForName, like 3.3.5's
GetItemIDByName. Before, a name always read false.

Add doc descriptors for both names and correct the header, which said there
was no name lookup and that inventory types end at 23.
2026-10-22 17:02:53 -05:00
Brues 597b16cb74 fix(item): port 3.3.5's IsConsumableItem
The old test was "item class 0, or ammo/thrown", a rule no client uses.
Explosives and quest items that are used up (Rough Dynamite, Thorium
Grenade) read false, and class-0 items that are not used up read true.
3.3.5's Script_IsConsumableItem, 4.3.4's (minus ammo) and this binary's own
ActionSlotIsConsumable (0x004E5250) all walk the on-use spells instead. An
item is consumable when it is ammo or thrown, or when an on-use spell has
negative charges or costs reagents. Port that.

The global IsConsumableItem now returns 1/nil as in 3.3.5, and
C_Item.IsConsumableItem returns a bool. Both resolve a carried item's name,
like 3.3.5's GetItemIDByName. Move that lookup from item/Count into
Item::Location::IDForName so GetItemCount and both functions share it.

Retail's IsConsumableItem is currently broken (false even for potions), so
3.3.5 is the reference.
2026-10-22 16:56:48 -05:00
Brues 60ef54b4a6 refactor(cvar): register cvars the way the engine registers its own
CVar::Factory::Register now takes a help line and a console category. The
registrar's EDX slot is the help line, not a spare zero, and category 9 (what
Script_RegisterCVar passes) matches none of the nine console categories. So
our cvars had no help and were listed under no category in `help <category>`.
Every backported cvar now passes retail's exact help string and category
(from Ketho's C_Console.GetAllCommands dump). The bag-sort and TTS cvars have
no retail counterpart and get no help line.

GetInt and the new GetFloat read the integer and float the setter stores on
every change, as the engine's own readers do. They no longer re-parse the
string. SoftTarget's atof copy and Nearest's raw read are gone. Info, Bool,
Set and Bitfield now go through the Factory (Find, GetString, the new
IsReadOnly) instead of their own lookups and field reads.

The read-only bit on scriptMemory is no longer a mystery. FUN_0063E030 sets
it on realmList, realmName and scriptMemory from CGGameUI::InitializeGame,
before the interface loads, and ShutdownGame clears it. So
CVar::ScriptMemory's in-game hook could never write. Drop it and keep the
glue one.

Also correct the Offsets.h comments: FUN_SET_CVAR_VALUE is __thiscall, and
the registrar's callback contract is now documented.
2026-10-22 16:27:11 -05:00
Brues 0e8b002af9 fix(action): let a spell replace a macro that casts it
PlaceAction compared the cursor spell against the slot's resolved spell
without checking the slot type, so dropping Dispel Magic on a
"/cast Dispel Magic" macro was taken for a duplicate and only cleared the
cursor. Gate the compare on the slot holding a spell action, as 4.3.4's
CGActionBar::PutActionInSlot does with IsSpell.
2026-10-22 15:58:31 -05:00
Brues 8bc43b455c fix(unit): trace UnitInLineOfSight like the server's LoS check
The server traces one segment with each end at its own unit's collision
height. The UnitXP_SP3-derived level-look pass traced both ends at the
shorter unit's height first and returned "in sight" when that cleared, so
segments slipping under overhangs read clear while casts still failed with
SPELL_FAILED_LINE_OF_SIGHT. Keep only the server's trace.

Also correct the docs: the 0x100111 class word already tests doodads and
game objects.
2026-10-22 15:43:50 -05:00
Brues 923cf943e3 fix(tracking): match 3.3.5 GetTrackingInfo and SetTracking
SetTracking() with no number now cancels the active tracking aura, as
3.3.5 does, through the same CMSG_CANCEL_AURA path as vanilla's
CancelTrackingBuff. The engine's aura rebuild then clears the tracking
word and fires PLAYER_AURAS_CHANGED.

GetTrackingInfo returns active as 1/nil instead of a boolean, and the
active tracker shows its activeIconID when the spell has one.
2026-10-22 15:32:05 -05:00
Brues 3a06590add feat(addons): add C_AddOns.GetAddOnInterfaceVersion
Reads the engine's parsed ## Interface: value (record+0x1C, the field
CanLoadAddOn compares against the client version). TocRewrite now
collapses a comma-list to retail's pick, the closest value at or below
the client version, so the stored value matches retail; loadability is
unchanged since the pick is 11200 iff 11200 is listed.
2026-10-22 15:24:03 -05:00
Brues c1086189f7 fix(loot): match 5.4.8 C_LootHistory and the engine's roll decode
Roll packets now decode as WriteRollLine does: a greed vote was read
as a pass, so greed voters on an item a need voter won stayed passed.
A START_ROLL always opens a new entry and later packets match the
newest one, so a respawned mob or chest no longer merges into its old,
finished roll. The winner's roll and type come from SMSG_LOOT_ROLL_WON
too, and the START_ROLL hook returns the original's result.

GetItem returns 5.4.8's isMasterLoot and isCurrency (both false) in
place of the timestamp, which 5.4.8's LootHistory UI read as master
loot. GetPlayerInfo returns a nil roll when no dice were rolled.
2026-10-22 15:13:32 -05:00
Brues e827e319be fix(unit): match 4.3.4 UnitIsInMyGuild resolution order
Try the engine's by-name search first (party then loaded players, exact,
mode 3, as 4.3.4's ClosestObjectMatch call) and decide a loaded hit on
the guild key, so a nearby guildmate's name works before GuildRoster().
Tokens resolve to a name through the NameCache and go to the roster,
which now compares names ignoring case (SStrCmpI).
2026-10-22 14:58:09 -05:00
Brues d3667797b5 fix(input): gate L/R modifiers on the engine's held-key list
The per-side modifier state was a parallel tracker that could disagree
with IsShiftKeyDown & co.: it stayed down while WoW was in the
background, and MODIFIER_STATE_CHANGED fired before the engine had
seen the key.

Reads are now the side bits gated by EventIsKeyDown for the merged
key. The event fires from handlers on the engine's key-down, key-up,
key-repeat and activation events, after the dispatch has updated the
held-key list, and that pass drops side bits the engine no longer
holds. The GetAsyncKeyState resync and its WH_CALLWNDPROC hook are
gone.
2026-10-22 10:05:22 -05:00
Brues e1ae53488b feat(fontstring): add GetFontHeight and SetFontHeight
FontString and Font get retail's pair. The getters push the height
through the same engine calls as GetFont, so they equal its second
value. The setters call the engine's own SetFont with the current file
and flags. Also map the Font method registry to SimpleFontAPI so Font
methods show in the API browser.
2026-10-22 09:01:31 -05:00
Brues b1a58f0d08 fix(luaenv): match 5.1 setfenv and getfenv
setfenv now returns the function it changed and no longer refuses an
environment marked with __environment; the marker only hides the env from
getfenv, as in 4.3.4/3.3.5 lbaselib. getfenv reads only the metatable
__environment field; the stock 5.0 raw __fenv fallback is removed.
2026-10-22 08:38:48 -05:00
Brues a61ff06e9a feat(unit): add UnitSelectionColor and UnitSelectionType
4.3.4's selection colour is one ladder over a GUID with an extended flag:
the unit's virtual calls it with 1, Script_UnitSelectionColor with 0.
Retail exposes the flag as useExtendedColors and names each rung
(UnitSelectionType 0 Hostile .. 9 Dead). 1.12 inlines the extended
ladder into CGUnit_C::GetSelectionHighlightColor and has no Lua surface.

Both globals walk that ladder rung for rung with the engine's own
predicates (CanAttack, IsPVPUI, CGPartyInfo::IsMember, UnitReaction,
health) plus the friend rung, so the extended colour is the one the
circle and the name draw. A GUID with no unit object takes 4.3.4's
no-object branch, with the PvP bit from the group stats block that
Script_UnitIsPVP reads.

FriendNameColor.cpp becomes SelectionColor.cpp so the engine-side
friend patches and the Lua ladder share one colour table.
2026-10-22 08:12:31 -05:00
Brues 3d2ac4d944 fix(friendlist): gate afk/dnd on connected, scan ignore holes
A logoff (SMSG_FRIEND_STATUS result 3) runs SetFriendStatus (0x5AEB30),
which clears only the online byte and leaves the AFK/DND status byte,
so an offline friend kept reporting afk/dnd = true. Gate both on
`connected`, as the engine's GetFriendInfo does for its status text.

Removing an ignore (0x5AF650) zeroes its slot and re-sorts only when no
ignore name lookup is pending, so the GUID array can have holes. Our
walks stopped at the first zero and missed later ignores. IsGuidIgnored
now calls the engine's FriendList::IsIgnored (0x5AE5A0), which scans
all 25 slots, and the name path skips zero slots instead of stopping.

Cleanup: IsFriend routes GUID input through the engine's IsGuidFriend
(names resolve via GuidForName) and drops the speculative name fallback;
Who.cpp reads ticks through Time::Clock.
2026-10-22 03:53:26 -05:00
Brues 167815f27b feat(unit): color friends' names light blue
4.3.4's selection colour checks the friends list after the party for a
player-controlled unit neither side can attack, and gives it #53C8FF.
1.12's CGUnit_C::GetSelectionHighlightColor has the same ladder without
that rung, so its two not-in-party exits now return the friend colour
for a friend. The name above the head and the selection circle both
take it. FRIENDLIST_UPDATE marks every name record's colour dirty
through the engine's own mark-all, so a change shows at once.

AutoPrepare's 6-byte call patcher moves to Common::ReplaceWithCall,
which takes any instruction length.
2026-10-22 03:31:24 -05:00
Brues 80af00f0c7 fix(softtarget): keep the soft target steady through the whole frame
After a few minutes in game the soft-target icons flickered: an addon's
UnitBuff, polling every ~250 ms, names each aura caster's unit token, which
reads softenemy / softfriend / softinteract. That read ran after the world
tick advanced the frame counter but before the scene drew, when the paint
has reset every node's cull state to culled, so IsEntityDrawn saw nothing
and the empty pick was cached for the frame (probe: every empty pick on
frame = drain frame + 1, stack UnitBuff -> Aura::Data::Push ->
Unit::Identity::TokenFromGUID).

- Take "drawn" from the drain's pass-1 list itself: the cull walk clears
  +0x94 exactly as it moves an entity to the draw list the drain calls with
  pass 1, so the list is the engine's verdict kept until the next drain.
- Key the cached pick on the drain count, not the world frame counter, so
  a read anywhere in the frame gets the same answer.
- InView (the locked target) checks the GUID against that list.
- Drop VAR_WORLD_FRAME_COUNTER, now unused.
2026-10-22 03:18:51 -05:00
Brues 15e1e21c8c fix(frame): read RegisterUnitEvent membership from the frame's event list
RegisterUnitEvent resolved the event-table entry before delegating to
Script_RegisterEvent, but the RegisterEvent hook runs
Event::Custom::RetryClaims inside that call. A custom event claimed there
was registered with its unit filter dropped and returned false, and a
Grow left the saved entry pointer dangling.

Membership now comes from the script object's own registered-event list
(+0x18 count / +0x1C indices), the list Frame::UnregisterEvent walks: a
longer list means a fresh registration and its last index names the
event. This drops every event-table scan and chain walk from
RegisterUnitEvent and IsEventRegistered.

Also check self before the event argument (engine order) and remove the
unreachable non-frame delegate, and test the free %s spec before reading
_G.event on the OnEvent gate.
2026-10-22 03:10:15 -05:00
Brues 8318daa74a fix(tooltip): match SetHyperlinkCompareItem to the 4.3.4 contract
Return 1 or nil instead of a slot count. 0 is truthy, so callers that
test the result (our GameTooltip_ShowCompareItem, retail FrameXML) showed
empty or stale shopping tooltips.

Show stat deltas only when comparisonTooltip is passed, and take the
compared item from that tooltip's live CGItem first. shiftButton no
longer gates deltas (in 4.3.4 it only affects the merchant offset-3 case).

Pick the equipped item with 4.3.4 SetCompareItem's rules: multi-slot
types count filled slots, weapons follow the main/off-hand rules, and an
off-hand item falls back to an equipped two-hander. Slot masks are read
from the engine's own table (0x809200) instead of a hand-written switch.

Require itemLink, add the blank spacer before the delta header, and wrap
the header line.
2026-10-22 02:45:46 -05:00
Brues fc4a983644 fix(nameplate): pass the NAME_PLATE_CREATED frame as a real argument
The frame went out by setting _G.arg1 around an empty-format fire, so a
modern function(self, event, namePlate) handler got nil. Fire it through
Event::Custom::FireValues instead: the argument runner sets arg1 and
passes the frame positionally.
2026-10-22 02:20:06 -05:00
Brues cd5d38d921 perf(lossofcontrol): find control-loss debuffs in one aura walk
The per-frame list asked FindNthSlot for the 1st, 2nd, ... harmful aura,
and each call rescanned all 48 slots. Walk the harmful order once with
the same filter instead: the same slots in UnitDebuff's order, one pass
instead of up to n x 48 checks. Entries and events are unchanged.
2026-10-22 02:11:40 -05:00
Brues 51b8a47d7a perf(nameplate): diff plates with flat arrays
The per-frame diff rebuilt an unordered_map every frame, one node
allocation per visible plate, and looked plates up in three hash
containers. The engine shows a few dozen plates at most, so flat
arrays searched linearly do the same work and allocate nothing once
warm.

Events, slot numbering and the reload behavior are unchanged; plates
that appear in the same frame now fire NAME_PLATE_UNIT_ADDED in the
engine's plate order instead of hash order.
2026-10-22 02:08:49 -05:00
Brues 8801b8ce35 perf(timer): skip C_Timer frames with nothing due
The world tick walked every pending timer and allocated a vector each
frame while any timer existed, due or not, and swept finished timers
with one erase each.

- Track the earliest deadline of a live timer; a frame before it reads
  the clock and returns. Scheduling lowers it, the sweep recomputes it.
- Reuse one vector for the IDs due in a frame.
- Sweep in one compacting pass.

Callback order and timing are unchanged.
2026-10-22 02:08:48 -05:00
Brues 128186288a perf(softtarget): pick from the scene's drawn entities, once a frame
The soft enemy, friend and interact picks scanned every live object
through ClntObjMgrEnumObjects (bag items included, ~870 a scan in a
city) and ran again for every reader in a frame: the circles, the
icons and each Lua token read.

- Pick at most once per side per frame, keyed on the engine's world
  frame counter s_frameCounter (0xC7B2C8), the counter its scene code
  keys per-frame work on. A target change or a soft-target cvar change
  (a cvar change callback) repicks at once.
- Take the candidates from the scene: hook DrawEntityModels (0x683DD0)
  and its per-entity callback WorldObjectRenderCallback (0x481540) to
  collect the pass-1 (in sight) entities, and publish the list when the
  drain returns, so a scan never reads one still filling. Probe in
  Stormwind: ~200 pass-1 and ~360 pass-2 entities a frame, no pass-2
  entity ever drawn, and no drawn object missing from the list.
- Keep each entity's object from AddPickCandidate (0x4815D0) and use it
  while it is certain to be live: until the next incoming packet (the
  destroy message and pool reuse only happen while one is handled)
  and under the same object manager. Outside that window the GUID is
  looked up as before.

Stormwind, all three soft targets and icons on: UI-frame subscriber
time from ~101 to ~27 us a frame, one pick from ~30-38 to ~8-12 us.
2026-10-22 02:08:48 -05:00
Brues b46b0cd503 fix(timing): match the engine's spell, aura and enchant timing math
- C_Item.GetWeaponEnchantInfo / GetItemTempEnchantInfo read the item's
  expiry clock (0x5D9D00) like the stock getter, so time left counts
  down; an enchant is present whenever its id is set.
- GetSpellInfo / C_Spell.GetSpellInfo report the effective cost and cast
  time through the engine helpers, divide by the power display divisor
  (rage in whole points), report per-second cost as isFunnel, and give
  passives a cast time of 0, as 3.3.5 and 4.3.4 do.
- Aura base duration follows the server (abs(base), -1 infinite, no
  per-level term); duration and expirationTime are reported together or
  as 0, 0, matching 4.3.4's PushUnitAura.
- C_Spell.GetSpellCooldown reads the pet's history for a pet-book spell.
- Route the remaining raw tick compares in Aura::Source and Spell::Cast
  through Time::Clock.
- Merge duplicate SpellDuration offsets; name the engine helpers' pet
  parameter consistently.
2026-10-22 00:48:10 -05:00
Brues 1e81acf277 fix(totem): match 3.3.5's totem slot behavior
Track each slot's totem creature by GUID the way 3.3.5's
CGGameUI::m_totems does, instead of rescanning the object manager by
entry every time.

- TargetTotem calls CGGameUI::Target on the stored GUID.
- A slot empties when its creature stops resolving (3.3.5's
  CGUnit_C::Disable -> DestroyTotem); the duration is only a fallback
  for a creature that was never seen. Leaving the world empties every
  slot; a UI reload keeps them.
- GetTotemInfo: haveTotem is true while a totem is up, the name is the
  creature's name (nil until seen, PLAYER_TOTEM_UPDATE on arrival),
  start/duration are whole seconds (3.3.5 divides as integers), and the
  empty icon is "". modRate and spellID stay as returns 6 and 7.
- GetTotemTimeLeft and GetTotemDuration return whole seconds.
- GetTotemInfo, GetTotemTimeLeft, GetTotemDuration and TargetTotem
  raise "Totem slot must be in range of 1 to 4".
- GameTooltip:SetTotem shows the creature name and always adds the
  time line.
2026-10-21 23:58:32 -05:00
Brues a0ee633397 fix(equipment): fire UPDATE_INVENTORY_DURABILITY on every alerts recompute
4.3.4 fires the event unconditionally at the end of
CGCharacterInfo::UpdateInventoryAlerts. Vanilla's recompute (0x004C7EE0)
has the same seven callers, including the engine's own type-wide
ITEM_FIELD_DURABILITY watcher (0x005D97C0), so firing after the original
is enough. Remove the per-slot {guid, durability} diff and its seed
latch: they hid the login fire and missed bag-item durability changes.

Correct the Offsets.h notes. FUN_005D9A90 is the enchantment refresh,
not a handler for every item update, and item-field watchers do work
through the type-wide registrar 0x00468070. Drop the unused
DESC_OBSERVER_BANK_ITEM / OFF_DESC_ITEM_DURABILITY constants.
2026-10-21 23:39:37 -05:00
Brues 792cd4c62b docs(readme): list StopSound and PlaySoundFile under Sound 2026-10-21 23:25:49 -05:00
Brues bdd9e8faad fix(item): port GetItemCount to the engine's inventory search
C_Item.GetItemCount now follows 3.3.5's Script_GetItemCount on 1.12's
own CGBag_C::FindItem ancestors (0x622130 stack count, 0x622180 charge
count, 0x6223F0 walk), which share 3.3.5's search-flag bits.

- Counts equipped bags and the keyring, skips broken items, and reads
  the bank through flag 0x08 without an open bank window.
- includeUses uses 3.3.5's gate (non-stackable, negative base charges)
  and its reagent-uses override.
- A name resolves to the ID of the first carried match, as 3.3.5's
  s_itemByName does.
- Flags are read with the engine's StringToBOOL, so "0" is false.

Item::Count::InInventory uses the same engine count, so IsUsableItem,
the totem tool check and GetSpellCastCount now count what the engine's
reagent and totem gate (0x6E4000) counts. GetSpellCastCount no longer
stops at the first empty reagent slot.
2026-10-21 23:21:06 -05:00
Brues b39e95bc66 fix(addons): match stock arg handling and stack check in GetAddOnOptionalDependencies
Mirror stock GetAddOnDependencies (0x0048E5E0, identical to 4.3.4's
GetAddOnOptionalDependencies): lua_isnumber first so numeric strings are
indices, the engine's own range error with the addon count for an
out-of-range index, and lua_checkstack before pushing the names.
2026-10-21 22:59:44 -05:00
Brues e83307d4c5 docs(readme): move cvars into their own CVars section 2026-10-21 22:49:44 -05:00
Brues 628b1c347e refactor(equipment): fire PLAYER_EQUIPMENT_CHANGED from the engine's slot observer
The engine already watches the equipment GUID fields: AddActiveWatchers
(0x5DD8A0) registers OnInventorySlotChanged (0x5DDCF0) on inventory
slots 0..22. That handler is the ancestor of 4.3.4's InventoryUpdate,
which fires PLAYER_EQUIPMENT_CHANGED right after unlocking the arriving
item. Co-hook it post-original instead of registering 19 of our own
observers from the FUN_004F8CC0 setup.

The engine now owns the node's registration and lifetime, so the
unregister-then-register guard against /reload stacking goes away, and
ITEM_LOCK_CHANGED fires before our event, as in 4.3.4. Like 4.3.4, no
event fires when the player GUID does not resolve.
2026-10-21 22:43:53 -05:00
Brues ed8f0ba851 fix(target): soft enemy and friend arcs default to the camera's front
SoftTargetEnemyArc / SoftTargetFriendArc defaulted to 2 (any direction),
so softenemy / softfriend was just the nearest unit. Default both to 0,
the interact arc's: the unit in front of the camera.
2026-10-21 22:20:48 -05:00
Brues 15a36827cd feat(target): selection circle under softenemy and softfriend
Retail draws a dimmer, smaller selection circle under the soft enemy and
the soft friend. It follows SoftTargetEnemy / SoftTargetFriend and the
engine's ObjectSelectionCircle; a soft unit that is also the target keeps
the engine's own circle.

The circle is drawn at the base per-frame step 0x614A90, where the engine
draws the target's (so it lands before the unit's blob shadow), by a
mirror of the unit's slot 12 (0x608E00) with the radius scaled 0.85 and
the colour's alpha byte at 0x80. Both are from retail screenshots of one
unit as softfriend and as target at the same zoom: width 64 vs 75 px,
brightness over the grass +116 vs +207 (additive blend).

The soft units are picked on the UI frame tick, after the scene: the scan
takes only objects the scene drew, so a pick before it found none.
2026-10-21 22:14:19 -05:00
Brues 52e17d05c1 feat(item): per-school spell damage, penetration and statTable in GetItemStats
Single-school MOD_DAMAGE_DONE equip spells now land on per-school keys
(ITEM_MOD_FIRE_SPELL_DAMAGE_DONE_SHORT, ...) instead of reading as
generic spell damage; an all-magic mask stays on
ITEM_MOD_SPELL_DAMAGE_DONE_SHORT. Damage and healing stay split, as the
server sums them from separate auras (13 by school, 135 alone).

Newly decoded equip auras:
- 123 MOD_TARGET_RESISTANCE, split by mask: armor bit ->
  ITEM_MOD_ARMOR_PENETRATION_RATING, magic bits ->
  ITEM_MOD_SPELL_PENETRATION (both positive)
- 158 MOD_SHIELD_BLOCKVALUE -> ITEM_MOD_BLOCK_VALUE
- 161 MOD_HEALTH_REGEN_IN_COMBAT -> ITEM_MOD_HEALTH_REGEN

GetItemStats / GetItemStatDelta take the engine's optional statTable
(filled in place, not wiped), return nothing on a cache miss, and the
delta is now item1 - item2, matching the 3.3.5 and 4.3.4 binaries.

Labels for the nine new keys in all seven locales, plus English
fallbacks for the compare tooltip.
2026-10-21 21:44:16 -05:00
Brues 00bad65103 fix(sortbags): gate bank on the banker, wait on the engine's item lock
- SortBankBags with the bank closed planned moves for the main bank,
  whose GUIDs sit in the player's invMgr from login, and the server
  refused each one. ViewForBag now hides the bank unless a banker is
  open, the same check as the engine's slot reader 0x6228a0.
- Phase two waited for the first BAG_UPDATE_DELAYED. If the server
  refused every merge, none came: later sorts were ignored and the
  placement ran at the next unrelated bag change. Both phases now lock
  the items they relocate and wait on the world tick until the engine
  clears those locks (slot change, refusal, or merge destroying the
  source). A 3 s deadline that restarts on each answer releases any
  stragglers.
- Phase one sized transfers for uncached items as 0 - count, a uint32
  underflow that poured every stack into the first. Uncached items are
  now skipped.
- Locked items (cursor, trade, in-flight move) are pinned in place
  instead of being moved and having the server refuse the move.
- The autosort exclusions passed a stack-local bag list that the
  deferred placement read after it was freed. The active list is now
  owned.
- A login or /reload resets an in-flight sort, so it can't resume on
  the next character's bags.

Also add doc descriptors for all eight C_Container registrations,
report locksReleased from _classicapi_SortBagsStats, rewrite the stale
comments, and update docs/API.md.
2026-10-21 21:12:28 -05:00
Brues 8e800502e1 fix(swap): release a held item before sending a swap
FUN_INVENTORY_SWAP is the drag-drop sender: after sending it clears the
cursor with returnItem 0, which drops a held item but keeps it locked
until the server answers for it. Our swaps never move the held item, so
no answer came and it stayed greyed out and unpickable. This hit every
Item::Swap caller (C_Container.SwapItems, equipment sets, whole-stack
MoveItem, SortBags). All three call sites now go through SendSwapPacket,
which first releases a held item through FUN_CURSOR_CLEAR(1, 1), the
form ClearCursor() uses.
2026-10-21 21:12:28 -05:00
Brues da7be7a50a fix(luasyntax): leave the engine-skipped # first line alone
luaX_setinput skips a first line starting with `#` (0x006FF5CD). The
transpiler read that `#` as the length operator and put its preamble in
front of the line, so the engine no longer skipped it. SkippedHead now
covers the BOM plus that line; only the rest is transpiled, and the
head is put back ahead of the preamble, which starts line 2.

Also drop the 0x1B bytecode pass-through: this client never undumps
(lua_load always takes the parser), so it could never matter.
2026-10-21 20:43:56 -05:00
Brues 9ba66e147c perf(table): read borders through luaH_getnum directly
Each slot probe in Table::Border was lua_rawgeti + lua_type + lua_settop,
three API calls per slot, on every transpiled `#t` and every luaL_getn
heal (table.insert / getn / remove / unpack / `...`). Resolve the Table*
once with luaA_indexAcceptable and probe with the engine's own raw
integer read, luaH_getnum, which is what lua_rawgeti resolves through.

Find now mirrors 5.1's luaH_getn: a nil in the last array slot bisects
inside the array part, otherwise unbound search from the array size.
Holey constructors now match real 5.1 (`#{1,nil,3}` is 3, was 1).
The getn heal's answers are unchanged. 100k `#t` on a 1000-entry table:
0.011s -> 0.004s.
2026-10-21 20:37:19 -05:00
Brues 7614a50aa4 fix(config): register launch switches with the engine parser
1.12's switch parser stops at the first switch it does not know, so any
engine switch written after -config, -gluescript or -gamescript (such as
-console) was ignored. Register ours in the engine's switch list before it
parses, as 4.3.4 does with -config, and read -config and the script file
paths back through the engine. Inline script code still comes from the raw
command line, which now skips quoted text.
2026-10-21 20:13:40 -05:00
Brues 53af083339 build: embed the addon and bindings as RCDATA resources
The embed step hex-encoded every file in a CMake while loop at build
time (7.6 s, a 2.4 MB generated header). Configure now writes an .rc
that points rc.exe at the files directly, plus a path-to-ID header.
Embed::Resource reads the bytes from the DLL image at runtime.

The .toc version stamp moves to a configure-time copy. Editing the toc
reconfigures, and editing any other file recompiles only the .rc.
2026-10-21 15:56:34 -05:00
Brues 718e5a31fe refactor(addons): drop dead embed code and duplicate offsets
- Stop writing DefaultState on the embedded entry: the entry
  constructor (0x5205b9) already stores 1, and the enable-resolver hook
  forces it on.
- Ask the original exists check for the dev marker instead of reading
  and freeing the whole file.
- Remove FUN_STORM_SMEMALLOC/SMEMFREE, which duplicated
  FUN_STORM_SMEM_ALLOC/FREE; Event::Custom uses the main names.
2026-10-21 15:45:44 -05:00
Brues 4554c3a5f5 fix(addons): register the embedded addon before the scan
Pre-hook the add-on scan (0x51c760) instead of post-hooking its caller.
The registry is empty there, so !!!ClassicAPI is the first record and
loads first without a list move, and the scan's LoadWith pass sees it.

The exists check now answers for embedded files the same way the read
hook serves them. Embedded owns the one FUN_FILE_EXISTS hook and chains
FlavorBindings::TryExists.
2026-10-21 15:20:10 -05:00
Brues 7240688008 feat(bindings): try every modifier subset and add GetBindingByKey
A key press now looks up its binding the way 4.3.4's
GetReducedKeyBinding does: every subset of the modifiers in its fixed
order (ALT-SHIFT-Q tries ALT-SHIFT-Q, SHIFT-Q, ALT-Q, Q), an override
before the saved binding for each. 1.12 tried only the pressed key and
the key minus its first modifier.

A binding to a command that does not exist is skipped, as 4.3.4's
GetKeyBinding does; the command-table lookup mirrors the walk the
engine inlines in FUN_BINDING_COMMAND_EXECUTE.

GetBindingByKey(key) returns the command a press of the key runs.
2026-10-21 14:52:52 -05:00
Brues f8e242639b feat(cvar): add C_CVar.SetCVar
Sets a cvar and returns true, or false for a read-only cvar. An unknown
name returns nothing. A missing value sets "0".
2026-10-21 14:38:39 -05:00
Brues 81c4aedb06 feat(target): show icons over the soft enemy and soft friend
SoftTargetIconEnemy and SoftTargetIconFriend draw the hover cursor image
over softenemy and softfriend, beside the soft interact icon. One unit
gets one icon. SoftTargetLowPriorityIcons lets the plain pointer count as
an icon image.

SetUnitCursorTexture now honors includeLowPriority (defaulting to
SoftTargetLowPriorityIcons) and clears the texture when it returns false,
as retail does.
2026-10-21 14:23:12 -05:00
Brues f08e360f10 feat(target): cast at the soft target and add loose targets
With no target, a harmful spell goes to softenemy and a helpful spell to
softfriend, through the engine's own range check, as in retail. A spell
that only the caster can receive still goes to the caster.

A harmful spell that goes off on the soft enemy makes it a loose target.
SoftTargetForce moves a loose target to each new soft enemy (1) or soft
friend (2), and clears it when none is left. It never changes a chosen
target and never selects one from nothing. Add IsTargetLoose().

SoftTargetMatchLocked and SoftTargetWithLocked now count only a chosen
target, and the attack's own selects keep a loose target loose.
2026-10-21 13:52:49 -05:00
Brues 8d1402dc83 feat(target): attack the soft enemy with no target
With no target, AttackTarget, the Attack Target key, /startattack and
StartAttack swing at softenemy, and the target stays empty, as in retail.
With no soft enemy, 1.12's own behavior stays: the nearest enemy becomes
the target. The engine's state checks and errors are unchanged.

Add SoftTargetWithLocked: 0 gives no soft enemy and no soft friend while
there is a target.
2026-10-21 12:46:00 -05:00
Brues 81eaf24748 feat(target): add the soft enemy and soft friend
Add the softenemy, softfriend, anyenemy and anyfriend unit tokens, the
PLAYER_SOFT_ENEMY_CHANGED and PLAYER_SOFT_FRIEND_CHANGED events, and the
SoftTargetEnemy*, SoftTargetFriend* and SoftTargetMatchLocked cvars, with
Classic Era's defaults. anyleftinteract is the same as anyinteract.

The soft-target scan moves to Target::SoftTarget, shared by interact,
enemy and friend. Its arc now follows the camera, not the character.
2026-10-21 02:15:10 -05:00
Brues bac67038ea feat(target): add SoftTargetIconGameObject
A game object's soft-interact icon now also needs SoftTargetIconGameObject,
as in retail. It defaults to 0, the value of retail's Default option.
2026-10-21 00:59:48 -05:00
Brues c8880444f4 docs(readme): list soft interact in the modern client behaviors 2026-10-21 00:51:06 -05:00
Brues 3e4db9279e perf(debugtools): stop the event trace churning memory
The trace kept 1000 entries under an index that only grows, so each of
its 22 column tables rehashed and reallocated every few events. Entries
now go into a ring of fixed slots.

An event no longer redraws the list (OnUpdate redraws it once per frame
while shown), packs its arguments into a table, or formats its time and
marker text; that text is built when a row is drawn. /etrace clear now
rebuilds all 19 argument columns.
2026-10-21 00:26:02 -05:00
brues-code 62cabb2acb Add the combat log: COMBAT_LOG_EVENT, filters and kept entries (#108)
* feat(combatlog): add COMBAT_LOG_EVENT and CombatLogGetCurrentEventInfo

Port 4.3.4's combat log events (UnitCombatLog_C.cpp) in its argument
layout: timestamp, subevent, hideCaster, source and dest GUID, name,
flags and raid flags, then the spell prefix and the subevent suffix.

- Swing, range, spell and periodic damage, misses, heals, energize,
  drain and leech, damage shields, split damage and environmental
  damage, read from the combat log messages through
  Net::PacketDispatch.
- Spell misses from the one function every miss goes through, so a
  missile's miss is sent when it arrives.
- Object flags and raid flags from the fields 4.3.4 reads. Names follow
  the 1.12 combat log namer's steps.
- CombatLogGetCurrentEventInfo returns the values only while the events
  are being sent, as on Classic Era.
- Event::Custom::FireValues sends an event with Lua values, so booleans
  and nils land where 4.3.4 puts them.
- COMBATLOG_OBJECT_* constants in the addon.

Overkill, overhealing and healing absorbs are 0: the server does not
send them.

* feat(combatlog): add casts, auras, dispels, interrupts and deaths

Port 4.3.4's layer 2 combat log subevents: SPELL_CAST_START/SUCCESS/
FAILED, SPELL_AURA_APPLIED/REMOVED and their _DOSE forms, SPELL_DISPEL,
SPELL_DISPEL_FAILED, SPELL_INTERRUPT, SPELL_EXTRA_ATTACKS, SPELL_DRAIN,
SPELL_LEECH, SPELL_RESURRECT, SPELL_DURABILITY_DAMAGE(_ALL),
SPELL_INSTAKILL, UNIT_DIED, UNIT_DESTROYED and PARTY_KILL, plus proc
resists as SPELL_MISSED.

Casts come from SPELL_START / SPELL_GO and the cast-fail log line, effects
from SPELLLOGEXECUTE as the 1.12 client reads it, auras from the engine's
aura handlers through a new Aura::Source change observer that carries the
bound caster, and deaths from the death presentation.

* feat(combatlog): add filters, kept entries and CombatLog_Object_IsA

Port 4.3.4's UnitCombatLog_C_Scripts surface: CombatLogAddFilter /
ResetFilter, the kept-entry functions (GetNumEntries, SetCurrentEntry,
GetCurrentEntry, AdvanceEntry, ClearEntries), the retention time with its
combatLogRetentionTime CVar, and CombatLog_Object_IsA. COMBAT_LOG_EVENT now
fires only for entries that match the filters. Entries and filters clear on
the return to the login screen. Adds the COMBATLOG_FILTER_* masks from
4.3.4's Constants.lua.

* docs(combatlog): move the combat log events into the Events section

* fix(combatlog): bound the execute-log loop and the retention time

- Stop an execute log's target loop at an effect that carries nothing,
  so a huge target count cannot spin.
- Clamp the retention time to what the wrap-safe age test can measure.
- Bound GetCurrentEntry's index by the entry count.
- List ENCHANT_APPLIED and ENCHANT_REMOVED among the subevents that do
  not fire, and note why effect 59 casts log SPELL_CAST_SUCCESS.
2026-10-20 23:01:29 -05:00
Brues 81e1396f81 perf(target): pick the soft-interact target on demand
The pick no longer runs every frame. Reading softinteract or anyinteract
picks fresh, which covers the Interact Key and UnitGUID. The UI frame
tick re-picks only while a frame is registered for
PLAYER_SOFT_INTERACT_CHANGED, and the icon reads the token only while
SoftTargetIconInteract is on. With neither, nothing runs per frame.

SoftTargetInteract now defaults to 3, the value "Enable Interact Key"
writes, since the key does nothing until bound. SoftTargetIconInteract
defaults to 0, so the icon is opted into.
2026-10-20 19:27:38 -05:00
Brues cf5e9c8ee7 feat(target): add SetUnitCursorTexture and the soft-interact icon
SetUnitCursorTexture(texture, unit) sets a texture to the cursor image
the mouse shows over the unit, the Unable form when out of reach. It
takes the engine's own image: the cursor name table, or a game object's
record-named cursor through FormatGameObjectCursorFile.

The softinteract object now shows that image over it
(SoftTargetIconInteract, default 1; SoftTargetNameplateSize, default 19,
is its size). A unit's icon sits where 1.12 seats a nameplate, from
GetNamePlateScreenPos; an object's uses GetNamePosition's no-attachment
rule (1.25 x scale x box height) with the same 2/3-yard lift. The icon
is a texture on the world frame, anchored to its BOTTOMLEFT the way
SeatNamePlate anchors a plate, and hides off screen.
2026-10-20 19:09:19 -05:00
Brues 622478df04 feat(target): add the soft-interact target and Interact Key
Backports the Interact Key: the SoftTargetInteract, SoftTargetInteractArc,
SoftTargetInteractRange and SoftTargetInteractRangeIsHard cvars (Classic
Era defaults, so it is off until set), the softinteract and anyinteract
unit tokens, PLAYER_SOFT_INTERACT_CHANGED, and
C_PlayerInteractionManager.InteractUnit. INTERACTTARGET and
INTERACTMOUSEOVER now use Blizzard's bodies, which interact with
anyinteract.

The pick is the closest object the hover cursor would show an interact
cursor for: the unit and corpse cursor classifiers run with
SetCursorMode captured (Cursor::Hover), and game objects use GetCursor.
It also needs the tab-target collector's drawn test, the arc (arc 1 is
the collector's pi/6 front cone, arc 0 a 1.2-yard strip measured in
Classic Era) and the range capped by targetNearestDistance. It runs on
the UI frame tick, as on the world tick every world node reads as
culled. anyinteract is the target when it can be interacted with, else
softinteract, as probed on retail.

UnitTokenFromGUID now returns softinteract, last, in retail's order.
2026-10-20 19:09:13 -05:00
Brues 362669b071 feat(combat): add stopAutoAttackOnTargetChange
Backports 4.3.4's setting. At 1, a target change stops Auto Shot and
wand shots, and melee no longer moves to the new target. At 0, the
default, 1.12 behavior is unchanged.

Two call redirects in the target setter, at the point where 4.3.4's
CGGameUI::Target runs the test: the PLAYER_TARGET_CHANGED fire also
stops auto-repeat, and the melee restart on the new target is skipped.
2026-10-20 17:02:49 -05:00
Brues 929b6f5c60 feat(spell): add autoStand, autoDismount and autoUnshift
Backports 4.3.4's cast settings. With one set to 1, a cast that 1.12
refuses because the player sits, is mounted, or is in a form that the
spell excludes now stands, dismounts or leaves the form, then casts.

Mirrors 4.3.4's split: the caster check's mount, stand and form rungs
pass when the action is allowed and note it, and the cast request runs
the noted actions once every rung has passed. A form refusal for "only
in form" is never handled, and the usability check honors autoUnshift
so the button stays lit, as Spell_C_IsUsableAction does.

All three default to 0, so 1.12 behavior is unchanged until set.
CancelShapeshiftForm now shares the aura-cancel walk with the dismount.
2026-10-20 17:02:42 -05:00
Brues 3751b31cda fix(spell): read dual wield from the known-spell bitmap
The engine's CGPlayer_C::CanDualWield (0x005EAB70) reads a global that
the learn path sets and only the unlearn of the same spell clears.
Nothing clears it at logout, so after a character that knows Dual
Wield, every later character in the session reads true.

CanDualWield and GetAverageItemLevel now ask whether this character
knows spell 674, the only SPELL_EFFECT_DUAL_WIELD spell in Spell.dbc,
through a new Spell::Known module. Spell::Known::IsKnown replaces the
three copies of the known-spell bitmap read in spell/Info.cpp,
spell/Usable.cpp and aura/Source.cpp.
2026-10-20 16:25:19 -05:00
Brues 20c4312251 fix(item): port GetAverageItemLevel from 4.3.4
Rewrite GetAverageItemLevel as a port of 4.3.4's
CGCharacterInfo::CalculateAverageItemLevel:

- count only items the player can use (CGPlayer_C::CanUseItem)
- keep the best item level per inventory type, plus the second best
  ring, trinket and one-hand weapon
- take the better of the one-hand loadout over 17 slots and the
  two-hand loadout over 16, using the engine's own dual-wield check
  (FUN_PLAYER_CAN_DUAL_WIELD) to pick the off hand
- count what is inside containers, not the containers themselves

While item records load, return the last complete answer, and fire
PLAYER_AVG_ITEM_LEVEL_READY when they arrive. Item::Data gains a
LoadSubscriber for load completions, and WarmCache reports whether it
queued the item. Player::CanUseItem::Check is shared through a header.
2026-10-20 16:12:40 -05:00
Brues 7e6bfd70ad docs(readme): split the Frame and Item reference rows
The Frame row had grown to 124 calls across nine widget types in one
cell. Split it into one row per widget (Region, Frame, Button,
FontString, Texture, EditBox, StatusBar, Slider, Cooldown,
ScrollingMessageFrame, scripts), group related calls, pair Set/Get
methods, and link each row to its first heading in docs/API.md.

Split the Item row into C_Item, item info, inventory and item-ID rows,
and list the registered calls it was missing: C_Item.GetItemData,
C_Item.GetItemDataByID, C_Item.IsUsableItem, IsUsableItem and
IsConsumableItem.
2026-10-20 15:35:20 -05:00
Brues c1ac5109e5 feat(texture): add IsDesaturateSupported
Returns 1 when the engine's stock Desaturate shader is loaded and valid,
as 3.3.5's Script_IsDesaturateSupported does, through the same
FUN_00770620(1) gate that Script_SetDesaturated uses.
2026-10-20 15:29:02 -05:00
Brues 0b7076d330 feat(frame): add GetCurrentKeyBoardFocus, SetMaxAnimFramerate and GetMaxAnimFramerate
GetCurrentKeyBoardFocus returns the focused edit box, or nil.
SetMaxAnimFramerate / GetMaxAnimFramerate set and read the animation
step rate (default 30 per second), which was a fixed constant before.
Both mirror 4.3.4's SimpleFrameScript_Scripts.cpp. GetText moves to the
not-worth-it list.
2026-10-20 15:16:42 -05:00
Brues 1d3ca3db6e feat(statusbar): add reverse fill, rotated texture, fill styles, color fill and desaturation
StatusBar gains SetReverseFill / GetReverseFill, SetRotatesTexture /
GetRotatesTexture, SetFillStyle / GetFillStyle (with
Enum.StatusBarFillStyle), SetColorFill, and SetStatusBarDesaturated /
IsStatusBarDesaturated / SetStatusBarDesaturation /
GetStatusBarDesaturation.

1.12 draws the fill by cropping the bar texture from its bottom-left
corner. A bar with a mode on takes 4.3.4's layout instead: its
OnFrameUpdate co-hook sets the coordinates and moves the texture's four
points, with the crop flag off. A bar with every mode off runs 1.12's
own update. SetColorFill creates a bar texture the way
SetStatusBarTexture does when the bar has none, then fills it through
the engine's Texture:SetTexture handler. The desaturation methods use
the bar texture's Texture::Desaturation state, now exposed in
texture/Desaturation.h.
2026-10-20 15:06:57 -05:00
Brues f112a13695 feat(frame): add the OnMinMaxChanged script to Slider and StatusBar
SetMinMaxValues runs it with (min, max) when the range changes, before
the value is applied to the new range, as 4.3.4 does. The ExtraScripts
resolver now skips a script of the same name on another class instead
of stopping, so both classes can have one.
2026-10-20 14:31:06 -05:00
Brues 986f849b65 feat(slider): add Enable, Disable and IsEnabled
Enable and Disable set or clear frame flag 0x400 and run OnEnable or
OnDisable on every call, as 4.3.4 does. A co-hook on the slider's
mouse-down skips the drag while the flag is set and runs only the base
frame's mouse-down, so OnMouseDown still fires.
2026-10-20 14:11:53 -05:00
Brues 863cb61e8d feat(button): add RegisterForMouse
Sets which mouse buttons run a button's OnMouseDown and OnMouseUp
scripts. The engine fires both for every button through the script
runner, where the ClickEvents gate now skips unregistered ones, so drags
and clicks are unchanged. OnMouseUp also needs its down registered.
2026-10-20 13:54:56 -05:00
Brues 28bc2b3ee2 feat(button): add SetEnabled
Enables or disables the button through its Enable vmethod, the slot the
stock Enable and Disable methods call, so CheckButton's override and the
OnEnable / OnDisable scripts run the same way.
2026-10-20 13:42:11 -05:00
Brues f6ba0ff9a1 docs: mark XML KeyValues done, list KeyValues, mixin and method 2026-10-20 13:42:11 -05:00
Brues 1e2a36d630 fix(bindings): stop logging ModifiedClick nodes as unknown
The engine's Bindings.xml loader tests each root tag inline and logs
"Unknown node type" for anything but <Binding>, so every <ModifiedClick>
added a FrameXML.log line even though the actions load from the same
file. The loader now runs with a status that drops exactly that warning
for ModifiedClick nodes and forwards every other message.
2026-10-20 07:47:48 -05:00
Brues 2cab0dcb12 feat(xml): support mixin= and method= on XML elements
mixin="A, B" on frames, textures, font strings and animation groups
copies each global table onto the element's Lua table, as Mixin() does.
The outermost load of an object applies the whole inherits chain once,
templates first, before the engine loads any node, so KeyValues and
scripts build on the mixins instead of being overwritten by them. A
missing mixin logs a load warning.

Script elements take method="Name", binding self[Name] as the handler,
on frames, animation groups and animations.
2026-10-20 07:43:04 -05:00
Brues a2e3eed0de feat(xml): support <KeyValues> on XML elements
A <KeyValue key= value= type= keyType=/> entry sets object[key] = value
on frames, textures, font strings, animation groups and animations.
Types are nil, boolean, number, string and global, as in the later
clients' schema. Template entries apply first so an element's own
entries win, and all are set before OnLoad. Bad entries log a load
warning and are skipped.

C_XMLUtil.GetTemplateInfo now returns the template's own entries in
keyValues instead of an empty table.
2026-10-20 07:35:53 -05:00
Brues 9b01cca336 refactor(input): drive the global mouse API from the engine's event bus
GLOBAL_MOUSE_DOWN/UP came from a Win32 WH_GETMESSAGE hook with its own
held-button mask, which stayed "held" after an alt-tab and sent no
release when the window lost capture. Register two handlers on the
engine's mouse-down and mouse-up events with EventRegisterEx instead, at
a priority above the interface and below the console and the
loading-screen vetoes, and read IsMouseButtonDown from the engine's own
held-button mask.

Share the engine's button-name lookup as
Frame::ClickEvents::ButtonNameForMask. IsMouseButtonDown(nil) now means
any button, as documented. Add documentation descriptors and rewrite
the stale API.md sections.
2026-10-20 07:22:45 -05:00
Brues 1384160fb0 refactor(events): document quest and bag events, use engine names
Add documentation descriptors for QUEST_ACCEPTED, QUEST_REMOVED,
QUEST_TURNED_IN and BAG_UPDATE_DELAYED.

Quest::TurnedIn now reads its payload with the shared Net::Read and
restores the cursor itself, so FUN_PACKET_READ_UINT32 and
OFF_PACKET_STREAM_CURSOR go. It stays a hook on the engine handler so
the event still fires after the completion lines.

Rename the BAG_UPDATE emitter hooks to the engine's names
(RaiseBagEvents, RaiseBagUpdate, OnBackpackSlotChanged) and correct
their comments: RaiseBagUpdate takes a container GUID, and the
backpack watcher has the standard field-watcher ABI.
2026-10-20 07:14:03 -05:00
Brues 116a3b352c fix(item): stop flagging the half of a split stack as new
A split gives the split-off half a new item GUID, so the seen-set read it
as a fresh acquisition. Record the source stack when CMSG_SPLIT_ITEM is
sent and let the next unseen bag item with the same item ID claim it. The
record retires once the source stack shrinks or the server refuses the
move.

Also add documentation descriptors for C_NewItems and
BAG_NEW_ITEMS_UPDATED, and rewrite the API.md section without
implementation details.
2026-10-20 07:02:06 -05:00
Brues 56871fdebf feat(sound): mute every sound, add StopSound, and map channels
MuteSoundFile hooked Sound::Play2D, which only interface sounds and
files reach. Positional sounds (Play3D: creature voices, spell impacts,
server sounds) and loops (PlayLooped: ambience, emitters) open through
other routes, so they could not be muted and never reached
GetRecentSoundFiles. The hooks now sit on Sound::Play (0x007A5290,
behind both Play2D and Play3D) and Sound::PlayLooped (0x007A54D0).

StopSound(handle [, fadeoutTime]) calls Sound::Stop2 (0x007A5A10). It
stops only handles our play functions returned, because releasing a
record the engine holds in a slot would free it under that slot.

PlaySoundFile makes the engine's own Play2D(3, file) call, adds the
channel's category flag, and returns willPlay, soundHandle.

The channel argument now picks the volume category by name, as 4.3.4's
_PickScriptSoundBus does. This replaces the numeric bus, which exposed
the engine's per-bus concurrency caps. forceNoDuplicates sets the sound
definition's own duplicate bit for the call. SoundKit plays now respect
the interface-sound suppression count, as PlaySound(name) does.
2026-10-20 06:45:02 -05:00
Brues f96e46113e fix(combat): fire cast swing resets only while auto-attacking
The server resets both melee timers on every non-triggered cast with
SPELL_INTERRUPT_FLAG_AUTOATTACK, attacking or not, so a buff such as
Power Word: Fortitude fired PLAYER_SWING(MainHand) and swing bars showed
a swing that never came. The reset is still recorded, but the event now
fires only while CGUnit_C::HasAttackTarget (0x0060ECB0, the engine's own
attacking test) is set. An attack that starts while such a reset is still
running reports the remaining main-hand time.
2026-10-20 06:27:35 -05:00
Brues 0ee594b9e1 fix(frame): match 4.3.4's IsMouseOver edges and self errors
IsMouseOver now treats a cursor exactly on an edge as outside, as
CScriptRegion::IsMouseOver does with strict comparisons. IsMouseOver and
IsDragging raise the engine's "this" errors for a bad self, as
FrameScript_GetObjectThis does, in place of returning false.
2026-10-20 06:17:50 -05:00
Brues 943597ca0d feat(texture): load masks from XML and release mask textures
- <Texture mask="path"> applies texture:SetMask(path).
- <MaskTexture> in a <Layer> builds a MaskTexture, and its
  <MaskedTextures> entries (childKey or target) attach it to textures.
  xml/Layers.cpp replaces the engine's layer loader with the same loop
  plus a MaskTexture branch, so the engine no longer warns on the tag.
- SetMask closes the mask texture's handle on replace, clear, region
  reuse and reload, as SetTexture does with the texture it held.
- SetMask keeps its previous mask when the file does not load, using
  SetTexture's own status test, instead of masking with the opaque
  fallback texture.
- API.md documents the XML forms and that a mask with an opaque edge
  does not clip past its rectangle (the device has no border address
  mode).
2026-10-20 06:08:38 -05:00
Brues a446e4cf8c refactor(item): answer CanUseItem and IsUsableItem with the engine's checks
C_PlayerInfo.CanUseItem now calls CGPlayer_C::CanUseItem (0x5EA930),
the check 1.12 uses for every "can use" answer it gives Lua, instead of
rebuilding its level, mask, proficiency, skill, spell, PvP and
reputation tests by hand.

IsUsableItem / C_Item.IsUsableItem now follow the item leg of 1.12's
action-bar usable check (0x4E5050), which matches 4.3.4's IsUsableItem:
the item must be carried, its on-use spell must not be held, an item
with no on-use spell is usable while the player has control, and the
engine's spell test decides the rest. Level, class and race are no
longer checked here, as in both engines.
2026-10-20 05:48:15 -05:00
Brues a53a08be95 fix(item): resend item queries the server dropped behind a loading screen
The server drops CMSG_ITEM_QUERY_SINGLE while the player is not in the
world, and the item cache sends its query only when it creates the
pending node, so a query sent before login finished or during a transfer
left that item nil for the rest of the session. The settle gate was a
one-way latch, so every loading screen after the first could lose
queries.

Queries now go out only in the world, after a settle delay per entry.
Queries in flight across a transition, or unanswered for 5 s, are sent
again with Cache::Query::Send, which builds the packet as the cache's
GetRecord does. Timeouts are wall-clock instead of frame counts.
2026-10-20 05:34:23 -05:00
Brues 0668c37156 feat(text): add the |4 plural code to the grammar pass
1.12's grammar pass is 4.3.4's LanguageProcess with rules 1 and 2 only,
so |4singular:plural; reached the screen as written. The pass is now
4.3.4's loop: |1 and |2 still run 1.12's own functions, and |4 is
4.3.4's LanguageRule4 with its locale plural index. It applies wherever
1.12 runs the pass: SetText, button text, tooltip lines, chat lines,
chat bubbles and name plates.

A code is matched by its single digit, which is all a rule consumes, so
|01 no longer loops forever.

PushLocalizedFormatInt drops its gsub expansion; AddLine now expands |4.
2026-10-19 22:39:21 -05:00
Brues a37b18bdfd feat(button): add SetFormattedText, shared with the font string's
Frame::FormattedText formats with the engine's str_format under pcall and
hands the result to the type's own SetText, as 4.3.4 does:
CSimpleButton::SetText (0x778DC0) for buttons, which creates a label when
there is none, and the font string's SetText for font strings.

The font string's version moves here from FontString::Metrics and now
matches Lua SetText and 4.3.4: it passes expand = 1, so the |1 / |2
grammar escapes are rewritten, and raises "Font not set" on a string
with no font.
2026-10-19 22:12:29 -05:00
Brues 3d41c8a702 feat(button): add SetMotionScriptsWhileDisabled and GetMotionScriptsWhileDisabled
A disabled button with the flag set runs its OnEnter and OnLeave scripts,
with no highlight and no label refresh, as 4.3.4's
CSimpleButton::OnLayerCursorEnter/Exit do. Co-hooks the button enter and
leave (0x779490 / 0x7794E0). The flag is per button, set from Lua or the
motionScriptsWhileDisabled XML attribute, and cleared when the frame is
destroyed.
2026-10-19 22:00:25 -05:00
Brues 5db35619ca docs(todo): add Button methods and the script-object API sweep
Button: 4.3.4's MotionScriptsWhileDisabled and SetFormattedText, and the
later clients' SetEnabled, state atlases, Clear*Texture and RegisterForMouse.

The sweep diffs every 4.3.4 method table and script handler and retail's
generated API docs against 1.12 and what ClassicAPI registers: the 4.3.4 gaps
(Slider enable, OnMinMaxChanged, StatusBar fill options, ScrollingMessageFrame
message methods, GetCurrentKeyBoardFocus, Set/GetMaxAnimFramerate, GetText)
and the later-client candidates, with the larger pieces listed apart.
2026-10-19 21:41:14 -05:00
Brues 6b95c03888 docs(todo): add XML KeyValues
Record retail's contract (UI.xsd, XMLUtilDocumentation), where it fits in
1.12's frame load order so a parent's values are set before its children's
OnLoad, the plan (a shared region-load observer, a typed-value helper shared
with <Attributes>, GetTemplateInfo's keyValues) and what cannot be verified
without a retail binary.
2026-10-19 21:27:06 -05:00
Brues 1a47cb3215 feat(fontstring): add SetWordWrap, CanWordWrap and GetFieldSize
The FontString methods 4.3.4 has that 1.12 lacked.

SetWordWrap is 1.12's own SetNonSpaceWrap on 4.3.4's style bit 0x40 (set
when the text does not wrap). 1.12's text engine already honours the bit:
TextBlockCreate turns it into text flag 0x2, and the layout and line count
stop after one line on it. A change lays the string out again as SetText
does, shared with SetMaxLines as FontString::Layout::Invalidate; a rebuild
alone left a text-sized string at its old height, so the fit cut at a whole
word with no ellipsis.

GetFieldSize returns what 1.12 holds rather than 4.3.4's constant 8191: n - 1
bytes for a string with XML bytes="n" (SetText's SStrCopy keeps one for the
terminator), and infinity for a string with no fixed size, whose buffer
grows to any length.
2026-10-19 21:17:36 -05:00
Brues d243457ecf docs(todo): add texture tiling from 4.3.4
SetHorizTile / SetVertTile and SetNonBlocking are the texture methods 4.3.4
has that 1.12 lacks. Record how 4.3.4 tiles, what 1.12 already has (the wrap
argument to CSimpleTexture::SetTexture), where the rescale belongs and the
open questions.
2026-10-19 21:17:29 -05:00
SkeewirtandBrues e84496d036 feat(animation): the animation system - AnimationGroup, Animation, Alpha, Scale, Rotation, Translation (#89)
* feat(animation): the animation system - AnimationGroup, Animation, Alpha, Scale, Rotation, Translation

Later clients animate regions in the renderer; vanilla has none of it, and
ported UIs build on it everywhere (Zygor Guides Viewer 2.0: 25 XML groups
plus CreateAnimationGroup in its guide window's OnLoad, which stopped there).

- Util/Animation.lua (bundled addon): the runtime. Groups and animations
  with the later-client API (Play/Stop/Pause/Finish, progress and smooth
  progress, order/startDelay/endDelay/duration timeline, NONE/REPEAT/BOUNCE
  looping, NONE/IN/OUT/IN_OUT smoothing, maxFramerate, the group and
  animation scripts). One driver frame ticks playing groups; effects go
  through the region's own setters and the region's state is restored
  when the group ends, as later clients never persist them.
- animation/Bridge.cpp: CreateAnimationGroup / GetAnimationGroups /
  StopAnimating on the region base registry, forwarding to the runtime the
  bundled addon registers via _classicapi_SetAnimationRuntime.
- xml loaders: an <Animations> child becomes descriptor tables (attributes,
  <Scripts> bodies and function= names, <Origin>) handed to runtime.LoadXML
  before the builder finalizes. Adds OFF_XML_NODE_TEXT. This extends the
  node-loader hooks of the XML attributes change, which it builds on.

Known limits of the 1.12 renderer: Scale pivots on a frame's own anchor
point (exact when anchored by its center) and resizes textures anchored by
one point; Rotation needs texture:SetRotation (textures, font strings).
Group templates (inherits on an AnimationGroup, CreateAnimationGroup's
template argument) are not supported yet and are ignored.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
a probe XML <Animations> group builds with Play(); every AnimationGroup and
animation method exists; a Lua-built group plays through 12 updates to
progress 1.0 and fires OnFinished; Zygor's step flash group (Alpha) plays
and stops, and its guide window finishes its OnLoad. Not checked yet:
Scale, Rotation and Translation on screen (Zygor's own groups with them
load without error, but no one has watched them play), REPEAT and BOUNCE
looping, the smoothing curves, and maxFramerate.

* refactor(animation): port 4.3.4's CSimpleAnimGroup/CSimpleAnim to C++

Replace the Lua animation runtime with a C++ port of the 4.3.4 engine
classes. Groups and animations are real 1.12 script objects (engine
header from ConstructScriptObject, our own vtable), so GetObjectType,
IsObjectType, GetName/$parent globals, SetScript/HookScript and the
shared __index dispatch all go through the engine's mechanisms.

- Group/Anim: the 4.3.4 timeline (orders, delays, looping, cosine
  smoothing, 1/30 s throttle, pause/stop/finish) and every method.
- Region: per-region state ticked from a CSimpleFrame::OnFrameUpdate
  co-hook (shown frames only); 4.3.4's alpha model (store, reset each
  tick, add change, restore when the last alpha group ends, children
  included). CreateAnimationGroup, GetAnimationGroups, StopAnimating.
- Xml: <Animations> with 4.3.4's attribute set, inherits/templates,
  script bodies and function= through SetScriptObjectScript.
- Frame::Destruction: a shared hub over the frame destructor; groups
  die with their frame, and Frame::Alpha moves onto it.

Translation, Scale and Rotation keep their values and timing but do
not move anything yet.

* feat(animation): apply Translation to what regions draw

Port 4.3.4's AddAnimTranslation: a frame hands the offset to every
texture and font string below it (or only the target), a texture moves
the four corners its draw record points at, and a font string moves its
text block's string position. Rects, anchors and mouse areas stay put.

- StoreAnimPosition / PreOnAnimUpdate / ResetPosition mirror 4.3.4,
  with the base taken from the engine's own layout (the corner store
  for textures, inset x layout scale + rect corner for font strings).
- Co-hooks on the texture and font string OnFrameSizeChanged callbacks
  move the base when the layout moves a region mid-animation and keep
  the animation's offset, as 4.3.4's own legs do.
- A frame is marked while it plays a position group, so the end of its
  last one puts everything below it back.

Scale and Rotation still keep their values without drawing.

* feat(animation): apply Scale and Rotation to textures

Port 4.3.4's AddAnimScale / AddAnimRotation with GetOriginOffset,
ApplyScaleAnim and ApplyRotationAnim on the texture's drawn corners: the
origin point on the quad, its offset turned along the bottom edge, and a
counter-clockwise positive angle. Frames hand both to every texture
below them, or only the target. Font strings do not scale or turn yet.

* feat(animation): scale and turn font strings

Port CSimpleFontString's AddAnimScale / AddAnimRotation: the animated
rotation and x scale replace the string's for the update, and the text
is baked again when they change (the engine's node invalidate, as
4.3.4 invalidates the CGxString). After the bake, the glyphs are scaled
and turned about the node origin, where 4.3.4's InitializeTextLine turns
them, with the engine's half-texel UV inset for turned glyphs. The text
is stretched rather than drawn at a larger font size.

* feat(animation): add Path and ControlPoint

Port 4.3.4's CSimplePathAnim and CSimpleControlPoint: a Path moves the
region's drawing through its control points with AddAnimTranslation,
the points spread evenly over the progress, in straight lines (NONE) or
on 4.3.4's Catmull-Rom spline (SMOOTH). ControlPoint is its own script
object with offset, order and SetParent; BuildSpline keeps 4.3.4's
order shuffle when an order is taken. XML reads `curve` and
<ControlPoints>, with templates for CreateControlPoint and `inherits`.

One deviation from the decompiled CreateControlPoint: a point made
without an order takes the highest order + 1 (as SetParent does), so
points made one after another keep their creation order.

* fix(texture): keep shape changes made during a position animation

Texture:SetRotation and SetVertexOffset wrote the drawn corners, which
the next animation update replaced with the corners stored when the
group started. While a position group plays they now write the stored
corners, so the new shape shows with the animation on top and stays
after the group ends. FontString:SetRotation on text an animation has
turned or scaled bakes the glyphs again instead of re-turning them in
place, so the bake applies both.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-19 20:44:31 -05:00
Skeewirt 3ce2880c93 feat(lua): add the strmatch global for string.match (#62)
1.12's startup script makes globals of the 5.0 string functions
(strfind = str.find, strsub = str.sub, ...), so the 5.1 string.match that
ClassicAPI adds had no global form. 3.x clients have strmatch: 3.3.5's
FrameXML calls it 41 times and never defines it, and Zygor Guides Viewer
2.0 calls it in Profession.lua when it scans a trade-skill window.

Register string.match's function as strmatch too.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
strmatch("|Henchant:3275|h", "|H%w+:(%d+)") returns "3275", and Zygor's
trade-skill scan (Profession.lua:142) no longer errors when a trade-skill
window opens.
2026-10-19 18:44:36 -05:00
Brues 9f4e45551b feat(text): backport IndentedWordWrap
Set/GetIndentedWordWrap on Font, FontString, EditBox, MessageFrame,
ScrollingMessageFrame and SimpleHTML (optional "h1".."p" first), as
4.3.4 does them: style bit 0x20000, set on the font string itself (and
cleared from its settable mask) or on the class's font through
CSimpleFont_SetIndentedWordWrap. The font string constructor's settable
mask gains 0x20000 (0x3F -> 0x2003F), as 4.3.4's 0x2107F has it, so a
font's setting reaches the strings that follow it.

The text engine honours it as 4.3.4's does with its flag 0x2000: from
the second line on, every wrap loop narrows the width by 15 / render
width, and the layout places a left-justified line 15 px in and a
right-justified one 15 px further left. All by call-site redirects, no
new hooks: the font string's five calls into the engine note the bit
(and the node gets flag 0x2000), the three measure loops' stepper calls
narrow lines past the text's start, and two thunks in the draw builder
narrow and place each line from the node's line count before the x is
copied into a wrapped link's rect.
2026-10-19 15:55:20 -05:00
Brues 09492782cc feat(editbox): backport 4.3.4's missing EditBox API, fix three caret faults
New, as 4.3.4 does them:
- Enable / Disable / IsEnabled: a disable clears the focus; both run
  CSimpleFrame::RunOnEnableScript (frame flag 0x400, OnEnable/OnDisable).
- OnEnable / OnDisable scripts on every frame. Buttons run them when
  CSimpleButton::Enable changes the state, as 4.3.4's does.
- IsInIMECompositionMode reads the composition flag 1.12 already keeps
  (+0x3CC); OnCharComposition(self, text) runs after the input method's
  composition insert.
- OnTextChanged(self, userInput): 4.3.4's dirty bit 0x8, kept per box at
  the insert and delete points; SetText's clear and insert are the
  script-made changes. The fire block is replaced by a call that runs the
  script with the bit.

Fixes (benilla-re ui/editboxmarkup "Faults"):
- A text ending in a colour escape or an unclosed link froze the client
  on Right or Delete: the forward cursor step had no end test. It now
  stops at the terminator, as 4.3.4's does.
- A single-line box read |n as a line break in its class table but drew
  it as two characters; the table is now built with the decoder flags
  its font string draws with.
- The right-justified click converted glyphs counted from the line end
  by stepping from the line start; it now steps back from the end.
2026-10-19 15:42:15 -05:00
Brues b3955f89df refactor(frame): share the extra-script cells, add slot runner and call redirect
Frame::ExtraScripts now owns the co-hook on the base frame script
resolver (MinHook allows one per address) and hands out per-frame cells
for any script name the engine does not know, filtered by the class's
Lua type id. OnAttributeChanged moves onto it; its cells are dropped on
/reload by the module.

ScriptArgs::RunSlotWithValues runs a {handler, context} slot with Lua
values inside the slot's execution context, as the engine's fire wrapper
0x00702690 does.

Common::RedirectCall repoints one `E8 rel32` call when it still reaches
the expected target, and is idempotent across registration passes.
2026-10-19 15:42:07 -05:00
Brues 1645f6513a feat(frame): add 4.3.4's missing Frame and Region methods
Close the Frame/Region gap against the 4.3.4 decomp (animation methods
excepted):

- SetPropagateKeyboardInput / GetPropagateKeyboardInput: frame flag
  0x200000. The Frame key-down and char slots and the EditBox key-down
  slot run their scripts, then answer "not taken" so the walk goes on to
  the frames below and the bindings, as 4.3.4's slots end. Key up is not
  hooked: the top's key-up handler discards the slot's answer.
- SetDontSavePosition / GetDontSavePosition: frame flag 0x80000, which
  the layout-cache save (0x00490E60) now skips, as 4.3.4's
  PlacedFrameCallback does.
- GetBoundsRect: 4.3.4's walk with its ScrollFrame override and pending
  layout resolve, on the engine's rect reader and frame lists.
- CanChangeProtectedState, CanChangeAttribute, AllowAttributeChanges:
  what 4.3.4 answers with nothing protected and nothing tainted.
  IsProtected moves to Region and returns nil, nil, as 4.3.4's does.

Both flags go through the engine's SetFrameFlag; none of its 14 callers
in 1.12 uses either bit.
2026-10-19 14:59:30 -05:00
Brues 2d2a5b9442 refactor(frame): name the layout resize, share the frame-list walk
0x007680E0 is 4.3.4's CLayoutFrame::Resize(force): force 0 marks the
layout dirty, force 1 resolves it now, as Script GetLeft calls it. It was
named FUN_FONTSTRING_LAYOUT_INVALIDATE, which hid the second use; rename
it FUN_LAYOUT_RESIZE.

Move the walk of a frame's intrusive region and child lists out of
Frame::Alpha into Game::ForEachFrameListObject, so the bounds walk can
use the same code.
2026-10-19 14:59:22 -05:00
Brues 9a2de093b9 docs: list the interruptible cast events in the README events table 2026-10-19 14:07:13 -05:00
Brues ff57450b7c feat(spell): match the engine's cast-failure events, add interruptible events
UNIT_SPELLCAST_INTERRUPTED vs FAILED now follows the failure reason, as
1.12 (0x6E4940, 0x6E2238) and 4.3.4 (HandleSpellFailedOrGo) decide it:
SPELL_FAILED_INTERRUPTED / _COMBAT give INTERRUPTED, every other reason
FAILED. A failure for the in-flight spell (read before the engine's
handler pops it, its own test at 0x6E2201) ends the cast in progress and
is reported with that cast's guid, then STOP. Casting while moving is a
FAILED attempt, and line of sight or a dead target at the end of a cast
is FAILED, not INTERRUPTED. A per-cast "reason reported" flag replaces
the interrupt dedup window.

Channels with SPELL_ATTR_EX3_HIDE_CHANNEL_BAR record no channel and fire
no channel events, as 1.12's MSG_CHANNEL_START handler and 4.3.4 skip
them.

Add UNIT_SPELLCAST_INTERRUPTIBLE / _NOT_INTERRUPTIBLE: Spell::Cast
watches the target and focus and fires when the notInterruptible answer
for the same cast flips, as 4.3.4 does from the unit's aura update.
2026-10-19 14:03:07 -05:00
Brues 05b978df3c feat(aura): report isStealable, as 4.3.4's CanStealAura does
1.12 builds only the friendly dispel list when a spell is learned
(AddSpellToBook); it has no offensive mask. Apply 4.3.4's rule to the
spells the player and pet know: a Dispel effect aimed at an enemy
(TARGET_UNIT_ENEMY, or TARGET_UNIT, which covers Dispel Magic and Devour
Magic) adds its dispel type. The mask is rebuilt when the spellbook
count or the pet changes.

An aura is stealable when the player can attack the unit, the aura is a
buff that is not passive, channeled or an area aura, and its dispel type
is in that mask. Reported as isStealable in AuraData and at UnitAura
position 8.
2026-10-19 13:16:27 -05:00
Brues e2c789510a feat(aura): list the player's own auras first, as 4.3.4 sorts them
C_UnitAuras walks a live unit's auras in 4.3.4's sorted order
(CGUnit_C::InsertSortedAura): auras the player or a unit the player
owns cast, then auras the player could apply, then the rest, each group
in slot order. Every index and slot walk uses it, including the by-ID
and by-name lookups and GameTooltip:SetUnitAura, so indices still agree
across them. The out-of-range group array keeps slot order, as 4.3.4's
does.

The groups are cached per unit and rebuilt when its aura array changes
or a new frame starts. Aura::Source::CastersForSlots finds every slot's
caster in one pass over the cache, and the can-apply answer is kept
until the slot's spell, the spellbook count or the pet changes.
2026-10-19 13:05:46 -05:00
Brues fd7843b8b3 feat(aura): add RAID and CANCELABLE filters, fix stale player timers
Use the engine's own aura tests where C_UnitAuras guessed or gave up:

- RAID calls the two tests behind UnitBuff/UnitDebuff's raid-filter
  argument (castable buff 0x4B3870, known dispel type 0x4B3920);
  isRaid reports the same answer.
- CANCELABLE / NOT_CANCELABLE read the descriptor's cancelable bit.
- PLAYER also counts a caster whose charmer or creator is the player
  (totems, guardians, charmed units), as 4.3.4's IsAuraCaster does.
  The charmer-or-creator read moves to Unit::Identity::OwnerGuid.
- Filter tokens and spell-name lookups ignore case (SStrCmpI).
- castByPlayer (UnitAura position 13) is a player caster only, as in
  4.3.4; isFromPlayerOrPlayerPet keeps pets.
- canApplyAura: the player or pet knows the spell and it applies an aura.
- Player timers look up the buff record by slot and honour its
  until-cancelled flag, so a permanent aura no longer reads the stale
  expiry its slot kept from an earlier aura.

Corrects the player-buff record and visible-aura comments in Offsets.h.
2026-10-19 12:50:54 -05:00
Brues e6f0a077e6 fix(screen): read GetPhysicalScreenSize from the graphics device
GetPhysicalScreenSize parsed the gxResolution CVar, which is the
configured resolution, not what is drawn: a resized window kept
reporting the setting. It now asks the device for its live render-window
rectangle through GxCapsWindowSize (0x58A240), the same source the
engine's font code sizes text from (GxuFontUpdateViewport), so the result
follows the window. An empty rectangle gives the font code's own
640x480 fallback.
2026-10-19 12:23:15 -05:00
Brues bbd78b437f feat(model): backport 4.3.4's PlayerModel and DressUpModel methods
SetDisplayInfo and SetCreature move from Model to PlayerModel, where
4.3.4 registers them, and now ride vanilla's own pane path: SetDisplay
(0x505CB0) stores the record and AttachDisplayModel (0x505A70) builds the
model with the engine's skins (ApplyCreatureDisplay), Stand, the pane
camera and light, and rebuilds it on every show. A co-hook on
AttachDisplayModel adds 4.3.4's SetUpModel step: a display with an Extra
record is dressed through the character compositor. SetCreature passes
the creature-cache record itself; SetDisplayInfo passes a per-pane record
holding the display ID, the only field the pane reads. The hand-built
ApplySkins is removed.

SetPortraitZoom, SetCamDistanceScale and RefreshCamera apply 4.3.4's
ConfigureCamera steps after vanilla's (0x505890); the defaults leave the
camera untouched. The portrait camera id is bounds-checked, since
GetCameraById indexes unchecked.

DressUpModel gains UndressSlot (one step of vanilla's Undress) and a
TryOn that takes item links, recipe links and carried item names in
front of vanilla's worker. PlayerModel:SetRotation takes 4.3.4's animate
flag, and Model:SetGlow exists as the no-op it is on a 4.3.4 Model.
2026-10-19 12:11:21 -05:00
Brues d5c6530b80 docs: move USER_WAYPOINT_UPDATED into the Events section 2026-10-19 11:51:50 -05:00
Brues a47f871adb feat(map): add GetExploredAreaIDsAtPosition and MAP_EXPLORATION_UPDATED
C_MapExplorationInfo.GetExploredAreaIDsAtPosition(uiMapID, pos) returns
the explored areas whose revealed overlay art is under a map point, most
visible first, or nil. It tests the art's alpha, decoded through the
engine's own BLP reader (driven as GetPortraitAlphaMask drives it),
not the overlay hit rects: measured over the 1.12 art, the rects name an
area over bare base map at 16.7% of points and give the wrong first
area at 11.6% where they overlap.

MAP_EXPLORATION_UPDATED co-hooks the engine's explored-bits watcher
(0x4A6460), which EnterWorldUI arms and LeaveWorldUI clears, so it fires
only on a real change and never stacks across /reload.

The overlay exploration filter now calls the engine's IsAreaExplored
(0x4A9A40) instead of re-deriving the bit test; the copy treated a
negative AreaBit as unexplored where the engine's unsigned compare
treats it as explored. Tile geometry is shared between GetMapOverlays
and the new hit test, and tile sizes come from the engine BLP reader.
2026-10-19 11:45:14 -05:00
Brues b9071a37f9 feat(text): render inline icons in edit boxes, as 4.3.4 does
4.3.4's edit box renders |T...|t in its text. Typed markup stays literal
because the edit box stores a typed | as ||, and 1.12 does the same
(0x77c254; Paste goes through InsertChar too). So edit boxes need no
special case once || is read the way both engines read it.

- The span rule is 4.3.4's GxuDetermineQuotedCode CODE_TEXTURESTART
  rule, in one scanner (IconSpanAt). Only |T...|t and |A...|a are spans;
  || is always a literal pipe. The old doubled ||T...||t match is gone.
  Stock 1.12 has no pipe-doubling sanitizer, so the ||T it was built for
  was typed text plus our own marker output.
- The edit-box suppression gates are removed: node bit 6 (really
  non-space-wrap), the focused-buffer test, the render-line content
  compare and the re-entry bracket.
- New co-hook on the fit-to-width function 0x772bc0 (mouse click to
  cursor, single-line visible window), mirroring 4.3.4's
  GxuFontGetMaxCharsWithinWidth.
- Ctrl+C drops icons: GxuStripControlCodes honours 4.3.4's 0x1000
  texture bit, and CopySelection's mask is patched from 0x500 to 4.3.4's
  0x1500. CopyToClipboard(text, true) now calls the same engine strip
  instead of its own parser.
- {rt1} and the other raid tags are expanded in the CHAT_MSG text at the
  event fire, and in the speech bubble after its escape strip (a
  redirected SetText call at 0x4b16c0), as 4.3.4's
  CGChatBubbleFrame::ParseRaidIcons does. The message buffer keeps the
  tags.
- The chat anti-spoof doubles a smuggled |T's pipe, as the edit box does
  for a typed one.
- The tokenizer hook honours the 0x800 all-pipes-literal gate.
2026-10-19 10:11:09 -05:00
Brues 9ab6627d90 feat(unit): add InteractUnit and the INTERACTTARGET / INTERACTMOUSEOVER bindings
InteractUnit(unit [, exactMatch]) is 4.3.4's Script_InteractUnit. It
resolves the argument the way 4.3.4 does:
- "mouseover" reads the hovered-object GUID, which in 1.12 is any
  object type (units, game objects, corpses).
- A unit token resolves to its GUID.
- Any other text runs the engine's by-name search with TYPEMASK_OBJECT.

It then calls 1.12's own OnSpriteRightClick (0x00492820), the function
a world right-click runs, so targeting, the object's right-click and
the autoloot modifier all come from the engine. 4.3.4's taint gate is
dropped because 1.12 has no secure environment.

Both bindings are spliced into the TARGETING group, as in 4.3.4. Their
names are added to every locale, using Blizzard's strings.
2026-10-19 03:33:21 -05:00
Brues 799ab1d3ce fix(target): call the selection setter as __stdcall, not __cdecl
FUN_SET_SELECTION_BY_GUID (0x00493540) returns with `ret 8`, and the
engine's own callers (TargetByName, OnSpriteRightClick) never clean the
stack after it. Target::Nearest declared it __cdecl, so each call from
TargetDirectionEnemy / TargetDirectionFriend popped the two GUID words
a second time and left the stack 8 bytes off.
2026-10-19 03:33:21 -05:00
Brues 77fb074191 feat(tooltip): add SetAnchorType, IsUnit, ANCHOR_TOP/BOTTOM and two getters
Cross-checked against 4.3.4's Tooltip_Scripts:

- GameTooltip:SetAnchorType(type [, x [, y]]) was missing in 1.12, but
  the shipped GameTooltip_ShowCompareItem port (and pfUI) call it.
  It stores the offsets and, with an owner, the anchor, then runs the
  engine's position routine with force.
- GetMinimumWidth and GetPadding read the fields 1.12's SetMinimumWidth
  and SetPadding already write; GetPadding returns the stored internal
  value, as 4.3.4 does.
- IsUnit(unit) compares GUIDs and returns 1 or nil. The token is probed
  first, because 1.12's resolver raises on an unknown name.
- 1.12's SetOwner has nine anchor names and sends every other one to
  ANCHOR_LEFT. ANCHOR_TOP and ANCHOR_BOTTOM get codes of their own; one
  hook on the position routine places them, and SetOwner and
  GetAnchorType are re-registered to know the names. ANCHOR_CURSOR_RIGHT
  is not added.
2026-10-19 02:07:42 -05:00
Brues 5c5c21e2ec fix(action): GetActionInfo no longer reports a dead macro button as an item
A 0x40 action entry is the server's ACTION_BUTTON_MACRO; there is no
bag-item tag (items are 0x80, by itemID). A 0x40 entry whose macroID is
not in the macro-slot map is a button whose macro is gone, which the
engine and 4.3.4 both treat as nothing. GetActionInfo returned
"item", nil for it.

- Empty slots, dead macro buttons and unknown tags now return nothing,
  as 4.3.4 does, instead of a nil.
- Action::Slot::MacroSlotForID calls the engine's own scan
  (FUN_MACRO_ID_TO_SLOT) instead of a copy.
- Offsets notes, Slot.h and API.md no longer describe a bag-item case.
2026-10-19 01:43:47 -05:00
Brues eccf5896cb feat(cursor): GetCursorInfo returns pets, and the right link for dragged items
Cross-checked against 4.3.4's Script_GetCursorInfo:

- Drag-source items (action bar, auction slot) keep only an itemID on
  the cursor, so they return the plain itemID link, as 4.3.4 does.
  The old search of the bags for a matching item could describe the
  wrong copy when two carried different enchants. The duplicate link
  builder in Info.cpp is gone; Item::Link::BasicFromItemID is used.
- A pet action returns "petaction"; a stable pet returns "pet", index.
- The stable cursor slot is 0-based in the engine (ClickStablePet
  stores its argument minus one); the Offsets note said 1-based.
- CURSOR_CHANGED now sees a change between two pets.
2026-10-19 01:34:59 -05:00
Brues fdae686cc9 feat(console): add pitchLimit, AppendLogToFile and 4.3.4's Tab completion
Cross-checked against the 4.3.4 decompilation (wowdecomp15595):

- The handler's first argument is the command name, not unused (the
  shared CVar handler looks its CVar up by it); Game::Console::Write
  takes 4.3.4's COLOR_T, and Game::Console::Printf is the engine's own
  ConsolePrintf (0x0063CD50).
- pitchLimit <deg>: writes the camera pitch clamp, which 1.12 keeps as
  two .rdata floats read only by camera code.
- Ctrl+Tab lists every command containing the typed text; Tab after
  set/cvar_reset/cvar_default completes CVar names (extension). Our key
  handler registers at the console's own priority 7.0, which the
  engine's tie rule runs first, so no hook is needed.
- AppendLogToFile [file] [numLines]: implements the contract 4.3.4's
  help text documents (the shipped command prints "Access Denied").
- The command-list walk moves into console/Registry.h, and
  EnsureParentDirs into Common.
2026-10-19 00:52:28 -05:00
Brues e75e585551 feat(frame): register Cooldown as a real frame type, so XML <Cooldown> works
4.3.4 registers "Cooldown" in the frame-type factory table, beside
GameTooltip and the model types. Vanilla has no such type: the
CreateFrame hook rewrote a "Cooldown" request as a Model with
CooldownFrameTemplate, so XML <Cooldown> elements were still "Unknown
frame type".

The Cooldown module now registers the type through the engine's own
FrameXML_RegisterFactory (0x006EE880), during the game Lua registration
pass, which CGGameUI::Initialize runs before the game-UI factory list
and before FrameXML loads. The table is never cleared, so a /reload's
second registration is a no-op, as for the engine's own types. The
factory builds the engine's Model (0x006EECF0) and marks it, and XML and
CreateFrame both reach it through the builder. CreateFrame drops its
Cooldown special case, and Cooldown.h goes away (nothing outside the
module calls it).

Every 4.3.4 Cooldown draws a sweep without a template; here the sweep is
CooldownFrameTemplate. A Cooldown loads it under its first node, before
the node's own templates and content, through a new
Xml::FrameLoad::AutoSubscribeBefore observer. Xml::LoadNode is the
shared "load this node onto the frame" step that Inherits also uses.
The template is setAllPoints, and a 4.3.4 Cooldown starts unanchored, so
the observer then calls CLayoutFrame::ClearAllPoints (0x00767620). A new
frame has no anchors at that point, so this restores exactly that.
Without it, a Cooldown with its own Size and CENTER anchor kept
TOPLEFT/BOTTOMRIGHT on UIParent and stretched across the screen.

Verified in-game (1.12.1 via VanillaFixes) with a throwaway test addon:
a bare XML <Cooldown>, an XML <Cooldown> child inheriting
CooldownFrameTemplate, and CreateFrame("Cooldown") with no template each
report "Cooldown", stay a Model, load UI-Cooldown-Indicator at scale
0.75, and draw a visible sweep. The bare one sits at its own 36x36
CENTER anchor, the child fills its host, and a plain Model still reports
"Model".
2026-10-19 00:08:55 -05:00
Brues 4ea0223f34 feat(xml): read inherits as a template list, and CreateFrame's id
4.3.4 reads `inherits` as a list. CSimpleFrame::LoadXML tokenizes it
on " ," and loads each template, left to right, before the node's own
content, so later templates override earlier ones; FindParent walks the
same list for a `parent`. Vanilla's frame loader, child-frames builder
and builder parent walk each look the whole string up as one name, so
XML `inherits="A, B"` failed with "Couldn't find inherited node".

Each of the three steps now takes a list the same way: every name in
order through the engine's own step, then the node itself. A single
name keeps the engine's path untouched. Textures and font strings keep
one template, as in 4.3.4.

CreateFrame is now 4.3.4's Script_CreateFrame on vanilla's builder:
- every name in a template list must resolve, or it raises the engine's
  "Couldn't find inherited node" error; the whole list goes on the
  request node, so the frame is built through the list path above with
  all templates applied before OnLoad. The old hook built with the
  first template and grafted the rest after OnLoad, and it skipped
  missing names.
- the 5th argument `id` is set on the node, so GetID() in OnLoad
  returns it.
The id has to be on the request node before the builder runs, and
vanilla builds and frees that node in its own body, so the function is
replaced, with the engine's node constructor, attribute setter,
builder, status object and error strings.

Verified in-game (1.12.1 via VanillaFixes) with a throwaway test addon:
XML and CreateFrame lists apply left to right (B's size over A's), both
templates' regions and children exist when the last template's OnLoad
runs, a missing name is skipped in XML and an error in CreateFrame, a
space-separated list takes its parent from a template, CreateFrame's id
reaches OnLoad, and CreateFrame("Cooldown") still reports "Cooldown".
2026-10-18 23:54:14 -05:00
Brues 6f55df19fa docs(readme): list the CHAT_MSG_* arguments in the Events table
They went into the API category list, which names functions; the Events
table further down is where event payloads are listed.
2026-10-18 23:28:24 -05:00
Brues 889a096963 feat(chat): give CHAT_MSG_* 4.3.4's lineID and sender GUID (arg11, arg12)
4.3.4's SendChatEvent fires every chat event with lineID and the sender's
GUID string after the ten arguments 1.12 already passes. 1.12 fires all ten
from one FUN_FIRE_EVENT call in FUN_0049B0B0, so that call is redirected to
append them:

- arg11 lineID: ++counter per message, before its event fires; 0 for text
  emotes, as 4.3.4's AddTextEmoteMessage passes.
- arg12 guid: the sender's GUID only for a player sender and a message not
  tagged GM, "" otherwise.

The redirect also works under Turtle's .tdata detour on the same function,
which returns to the PUSH just before the CALL. GetCurrentChatGUID() stays
and now reads the same sender, nil where arg12 is "". It moves into the new
Chat::EventArgs module with the redirect.

The sender GUID was wrong or missing on several paths, all fixed here:

- Monster say/yell put the monster's TARGET (often the local player) in the
  pair we published; the packet layout (vmangos BuildChatPacket, matching
  FUN_0049D560's reads) sends sender, name, target. Monster chat now has no
  sender, as in 4.3.4.
- Raid boss whispers are rewritten to a plain whisper carrying the target,
  so they reported the local player as sender. An SMSG_MESSAGECHAT
  subscriber keeps the wire type for the dispatch that follows.
- A message from a sender the name cache did not know was queued and later
  dispatched with both GUID pairs zeroed, by the name-query callback
  FUN_0049CCC0 or the enter-world drain FUN_0049D230. The queue entry keeps
  the GUID, and both callers pass pointers into it.
- Text emotes fire without passing their GUID on; the builder is co-hooked
  to provide it.

Chat::Dispatch's argument labels are corrected too: the pair it called the
target GUID is the speaker the speech bubble is placed on.
2026-10-18 22:47:22 -05:00
Brues 90b4691130 fix(debugtools): show all 19 event arguments in the event trace
The event trace passed only arg1..arg9 from its XML OnEvent and kept nine
argument columns, so it never showed arg10 that 1.12 already sends with
every CHAT_MSG_*, nor anything after it. The engine sets at most
arg1..arg19 for an event, so the trace now passes and stores all 19, with
trailing nils marking the end as before.
2026-10-18 22:47:22 -05:00
brues-codeandJared Reni 99de63755b CreateFrame("Cooldown") (#106)
* feat(frame): CreateFrame("Cooldown") builds vanilla's cooldown Model

Later clients have a native Cooldown frame type; vanilla draws cooldown
sweeps with a Model from FrameXML's CooldownFrameTemplate, driven by
CooldownFrame_SetTimer, and its CreateFrame rejects the type name
("Unknown frame type 'Cooldown'"). Ported code writes
CreateFrame("Cooldown", name, parent, "CooldownFrameTemplate") and then
calls CooldownFrame_SetTimer - Zygor Guides Viewer 2.0 does it while
building its guide window, which stopped there.

In the CreateFrame hook, build a "Cooldown" request as "Model", defaulting
the template to CooldownFrameTemplate when none is given.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
CreateFrame("Cooldown", nil, UIParent, "CooldownFrameTemplate") returns a
Model, and Zygor's guide window builds.

* feat(frame): give the Cooldown frame 4.3.4's methods

4.3.4's CGCooldown_Scripts registers SetCooldown, SetReverse,
GetReverse, SetDrawEdge and GetDrawEdge. The Cooldown frame built by
the CreateFrame hook now has the same five: SetCooldown takes start
and duration in seconds and errors as 4.3.4 does when either is not a
number, the setters read their value as 4.3.4's StringToBOOL does,
and both flags start false.

The hook marks each frame it builds as a Cooldown. The methods keep
their state per marked frame, SetCooldown drives the sweep through
CooldownFrame_SetTimer, and a marked frame reports its type as
"Cooldown" from GetObjectType / GetFrameType and answers
IsObjectType("Cooldown"). Every other frame delegates to the engine's
own type methods.

The reverse and draw-edge flags are stored and reported, but do not
change how the sweep draws: the sweep has no reversed form and no
edge. The five methods sit on the Model registry, so a Model that was
not built as a Cooldown raises the wrong-object-type error when one
is called on it.

---------

Co-authored-by: Jared Reni <jaredreni@gmail.com>
2026-10-18 16:39:34 -05:00
Brues 7cd891e86c fix(bindings): follow 4.3.4's bindings, modified clicks and key state
Modified clicks: IsModifiedClick, GetModifiedClick, SetModifiedClick,
GetNumModifiedClickActions and GetModifiedClickAction, with 4.3.4's
<ModifiedClick> Bindings.xml node and its 18 defaults. Each binding set
loads, saves and copies them through co-hooks on the engine's own
binding-set steps, in 4.3.4's "modifiedclick" file lines. [mod:]
asks IsModifiedClick, as 4.3.4's macro conditions do.

Direct actions run as 4.3.4's ExecKey runs them: SPELL / ITEM / MACRO
on key release through 1.12's spellbook, item and macro functions,
cast at you for SELFCAST and at your focus for FOCUSCAST; CLICK sends
the frame a mouse down and up, with 4.3.4's virtual-click button logic
built from the button's own methods. RunBinding no longer runs them.

While a key binding runs, its own modifiers count as released for
every modifier read, the engine's IsKeyDown included.

Overrides follow 4.3.4: two lists per key, checked inside the key
lookup at both of 1.12's lookup steps; GetBindingAction takes
checkOverride; isPriority is loose; "" removes; the owner must be a
frame.

ActionButtonUseKeyDown (default 0) and 4.3.4's action-button key
handlers, ported onto 1.12's bars.
2026-10-18 15:11:02 -05:00
Brues 6e50577565 fix(target): follow 4.3.4's TargetNearest and TargetDirection
TargetNearest, TargetNearestEnemyPlayer and TargetNearestFriendPlayer
now run the engine's own tab cycle (FUN_00493F60), which is 4.3.4's
TargetNearestEnemy: units in front first, the targetNearestDistance /
targetNearestDistanceRadius ranges, no critters or unseen units, and
the 3 s / 1 s snapshot shared with the native functions. A co-hook on
its predicate adds 4.3.4's types 0, 2 and 4 as three new modes.
TargetNearest now cycles any unit, as in 4.3.4.

TargetDirectionEnemy / TargetDirectionFriend are now 4.3.4's
CGGameUI::TargetDirection, built on 1.12's GetScreenCoordinates, the
camera's forward vector and the tab search's tests: facing is a screen
direction relative to the camera, the search starts at the target when
it is on screen, the cone is at least 22.5 degrees, and a hit locks
further calls until the new TargetDirectionFinished().
2026-10-18 14:20:26 -05:00
Brues 024c6d2021 feat(chat): prefix %t with the target's raid marker, as 4.3.4 does
4.3.4's chat parser prefixes both of its name codes, %f and %t / %n,
with {rtN} when the unit carries a raid marker and a name was found.
1.12's %t already resolves the name the same way, so the hook only
writes the marker in front of the %t pair and the engine still fills
in the name.

Rename Chat::FocusToken to Chat::ChatTokens; %f and %t share the name
lookup and the marker helper.
2026-10-18 13:56:54 -05:00
Brues 4b47059788 feat(debugtools): build /fstack with GameTooltip:SetFrameStack
Replace the Lua EnumerateFrames walk with the engine method, as
Blizzard_DebugTools does. /fstack also accepts "true" for hidden frames.
2026-10-18 13:38:14 -05:00
Brues 1aa5a07823 feat(tooltip): add GameTooltip:SetFrameStack, as 4.3.4 does
Mirror 4.3.4's CGTooltip::SetFrameStack: walk the engine frame list,
hit-test the layout rect against the cursor, name each frame the way
4.3.4 does, sort by strata and level, and fire the new
OnTooltipSetFrameStack script before Show. Every input already exists
in 1.12; the new offsets are verified against the binary.

GetMouseFoci now replays the engine's mouse-focus pass instead of
calling Lua getters: it walks the per-strata mouse input queues and
calls the engine's hit test, so hit-rect insets and scroll clipping
apply as they do for GetMouseFocus.

Also fix the FUN_REGION_GET_RECT comment: the rect is
{bottom, left, top, right}, not {top, left, bottom, right}.
2026-10-18 13:38:14 -05:00
Brues 00f32e0e2f feat(xml): load <Attributes> on frames, as 4.3.4 does
4.3.4's CSimpleFrame::LoadXML reads an <Attributes> child through
LoadXML_Attributes; 1.12's frame loader (FUN_XML_FRAME_LOAD) walks its
child elements and silently skips the unknown one, so ported templates
lost every attribute. Each <Attribute name= type= value=> is now set
the way 4.3.4 sets it: type nil/boolean/number/string (default),
converted with the loader's own helpers (FUN_XML_ATTR_TO_BOOL, new
FUN_SSTR_TO_FLOAT), stored without firing OnAttributeChanged (through
our SetAttributeNoHandler, so unit/type* behave as when set from Lua),
and malformed entries logged through the loader's status sink with
4.3.4's warning texts (VTBL_XML_STATUS_ADD, level 1).

FUN_XML_FRAME_LOAD was already hooked by Xml::ParentKey, and MinHook
takes one hook per address, so Xml::FrameLoad now owns it and fans out
after the engine loads each node (the RunnerHook / WorldTick pattern).
ParentKey's frame binds and the attribute loader subscribe; its node
helpers and loader-safe wrapper push moved there too.
OFF_COBJECT_LUA_REGISTRY_REF duplicated OFF_COBJECT_LUA_REF (both 0x08)
and is folded into it.

Verified in-game with a test addon: template attributes inherited and
overridden by the frame's own, number / boolean / nil types, a mixed-
case name, values present by OnLoad, no OnAttributeChanged on load, and
the three FrameXML.log warnings.
2026-10-18 05:17:22 -05:00
Brues 5537432662 docs(frame): describe 4.3.4's attribute and mouseover behavior
OnAttributeChanged takes (self, name, value) and nested changes fire
their handlers; mouseover follows SecureButton_GetModifiedUnit; the
3-arg GetAttribute and SetAttribute's required value. Drops the
implementation paragraphs.
2026-10-18 05:10:05 -05:00
Brues 5962ccc83d fix(frame): follow 4.3.4's attribute system and unit-frame mouseover
Compared against 4.3.4's CSimpleFrame attribute code and
CGWorldFrame::OnLayerUpdate:

- OnAttributeChanged gets (self, name, value) as real arguments, like
  4.3.4's RunOnAttributeChangedScript, plus the this/arg1/arg2 globals.
  It used to fire through the no-argument invoker with globals only, so
  a modern function(self, name, value) saw name == nil. The engine's
  runners only carry %d/%s values, so Frame::ScriptArgs gains
  RunWithValues for arguments already on the Lua stack.
- No recursion guard: a handler that sets attributes fires their
  handlers too, as in 4.3.4. The guard silenced every nested
  OnAttributeChanged on every frame.
- SetAttribute requires the value argument; the 3-arg GetAttribute form
  needs exactly four arguments and treats a nil prefix/suffix as empty;
  usage errors name the frame like the engine's (GetName ?: <unnamed>).
- The mouseover unit of a hovered frame comes from FrameXML's
  SecureButton_GetModifiedUnit, pcalled under the engine's error
  handler, as 4.3.4 does, so unitsuffix and modifier-qualified unit
  attributes count. 4.3.4 asks protected frames; with no protection in
  1.12 the analog is a frame that has attributes. The mouseover tooltip
  stays (4.3.4 shows it only over the world frame).
- SecureStateDriver.lua is 4.3.4's file again: it drives itself through
  SecureStateDriverManager attributes and reads OnUpdate's elapsed,
  both of which the guard and the old no-argument handlers had ruled
  out.
- Game::Lua::ObjectLuaRef / PushObject / ObjectDisplayName replace the
  copies in ScriptArgs and Modern.

Verified in-game: handler arguments and globals, a nested handler
firing, both usage errors, the nil-prefix lookup, mouseover following
shift-unit / unit, and a visibility state driver.
2026-10-18 05:09:25 -05:00
Brues f5acea6060 fix(coroutine): follow 4.3.4's coroutine library
Compared against 4.3.4's stock Lua 5.1 co_funcs (lbaselib.c), opened by
luaopen_base in FrameScript_Initialize:

- status: a coroutine mid-resume of another one is "normal", not
  "suspended". Test what the engine's own resume body (0x006F67B0)
  tests - ci > base_ci AND CI_YIELD on the CallInfo - instead of
  ci > base_ci alone. Resuming it now fails with 5.1's "cannot resume
  normal coroutine".
- running: push the thread with the exec-context field set, as every
  engine push does; it was left as whatever the stack slot held, which
  lua_pushvalue copies into the script context. The main thread is read
  from G->mainthread (+0x50, set by f_luaopen) instead of an L captured
  at registration.
- Registered on the glue state too.
- 5.1's error texts ("cannot resume %s coroutine"); too many arguments
  or results raise, and the results check reserves the slot for true.
- wrap re-raises a non-string error object unchanged through the raw
  lua_error (LUA_RAW_ERROR, 0x6F4440); a string still gets luaL_where.

Verified in-game: "normal" status and its resume error, the lifecycle
and running(), an error in the body is not read as a yield, and the
wrap error text.
2026-10-18 04:47:53 -05:00
Brues a86f1219c3 fix(frame): follow 4.3.4's HookScript, so a hooked handler keeps its args
HookScript's HookThunk was a C closure, which Frame::ScriptArgs treats as
wanting no positional args, and it called the old handler with none - so
a modern SetScript("OnShow", function(self) ... end) saw self == nil as
soon as anything hooked it. It also padded the hook to 9 args and only
detected OnEvent by exact case.

Follow 4.3.4's FrameScript_Object::HookScript instead:
- an unset script gets the hook itself, so GetScript returns it;
- a set one gets the same wrapper hooksecurefunc installs (4.3.4 uses
  FrameScript_HookWrapper for both), exposed via HookSecureFunc.h: the
  old handler and the hook get the script's own args, and a hook error
  goes through the engine's script error handler.
ScriptArgs' HandlerWantsArgs looks inside that wrapper (C function
compare, upvalues at CClosure +0x10 per lua_pushcclosure), so a hooked
script takes the positional path only when either side declares
parameters. The usage error names the frame as the engine does:
vtable+4 GetName, else its "<unnamed>".

Verified in-game: old and hook both get self; OnEvent gets (self, event)
with no padding; an unset script stores the hook; a three-deep chain;
a hook error is reported after the old handler ran; both error texts.
2026-10-18 04:34:15 -05:00
Brues 338c6777d6 feat(hooksecurefunc): follow 4.3.4's hooksecurefunc
Compared against 4.3.4's Script_hooksecurefunc / FrameScript_HookWrapper
(taint bookkeeping aside, which 1.12 has no counterpart for):

- The hook runs under lua_pcall with the engine's frame-script message
  handler as errfunc, so a broken hook is reported like any script
  error instead of being dropped silently. The original's results still
  reach the caller.
- The wrapper is installed with lua_rawset, so a target's __newindex
  never runs. The original is still read with lua_gettable, so an
  inherited method can be hooked.
- Registered on the glue state too: 4.3.4 registers it from
  FrameScript_Initialize, which runs for both states.
- 4.3.4's error texts, and its lua_isstring name check, so a number
  name works.
- _G is pushed and inserted at index 1, so both call forms share one
  layout. The comment saying pushvalue(GLOBALS_INDEX) crashes was
  written in the commit that fixed LUA_PUSH_VALUE (it pointed at
  lua_remove); the engine's lua_pushvalue resolves the pseudo-index.

The 11.0 unhookable-name list stays. lua_rawgeti moves into Game::Lua
now that ScriptArgs is not its only caller.

Verified in-game: a hook error is reported and T(3) still returns 3 6;
__newindex does not run and an __index method hooks; a number name
hooks; all three error texts.
2026-10-18 04:24:19 -05:00
Brues aeb3bdf07b feat(playercache): resolve GetPlayerInfoByName through the engine's name search
C_PlayerCache.GetPlayerInfoByName read only the persistent NameCache,
so it returned nothing for every name while that cache was off, even
for a player standing next to you.

It now resolves the name to a GUID first (Player::Info::GuidFromName):
the engine's own by-name search behind TargetByName (party and raid
members, including out-of-range ones, then every visible player), then
the friends list, then the persistent cache. The result is built from
that GUID by the same code as GetPlayerInfoByGUID.

The engine search is wrapped once as Unit::Identity::FindGuidByName,
which UnitTokenFromName now uses too.
2026-10-18 03:59:50 -05:00
Brues 1caf9fde18 feat(luasyntax): give strings 4.3.4's shared metatable
4.3.4 ships stock Lua 5.1, whose createmetatable gives every string one
metatable { __index = string } in G(L)->mt[LUA_TSTRING]. 1.12 differs in
one line of each reader: lua_getmetatable returns 0 for a non-table, and
luaT_gettmbyobj returns nil. Co-hook both so a string reads a per-state
metatable instead, and drop the index-continuation hook that answered
with the string table directly.

getmetatable("") now returns the metatable, so libraries that extend it
(StatLogic: getmetatable("").__index.trim = trim) work, and a replaced
or function __index resolves through the engine's own code. A method
lookup costs what 4.3.4's does: luaH_getstr for "__index", then the
lookup in string.

Verified in-game: getmetatable("").__index == string, methods, nil on a
missing key, extending __index, a function __index, the write / call /
arithmetic errors, tostring, and the kill switch.
2026-10-18 03:53:26 -05:00
SkeewirtandBrues d496ff2aa7 feat(string): string.trim and string.join, as later clients expose them (#94)
* feat(string): string.trim and string.join, as later clients expose them

Later clients put strtrim / strjoin on the string table too (string.split
was already registered), so (" x "):trim() works and libraries capture
them at file scope - AceConfigCmd-3.0 does strtrim = string.trim and then
calls it for every toggle/slash command ("attempt to call a nil value").

Not verified in-game yet: these register the existing strtrim / strjoin
functions a second time, under the string table. The testkit check for
them (string methods, the chars argument, the globals agreeing) runs at
the next login, and I'll add the result here.

* docs(string): document string.split and cite 4.3.4's compat.lua

string.split was registered but undocumented. 4.3.4's compat.lua aliases
all three str* globals onto the string table (str.trim / str.split /
str.join), so name it as the source and list the three the same way.
strsplit takes the separator first, so its method form is called on the
separator.

* fix(string): bind the str* globals to their string-table functions

Each Register* call mints its own closure, so registering one C function
as both strtrim and string.trim gave two values and strtrim ~= string.trim.
4.3.4's compat.lua binds each pair by assignment (gsub = str.gsub, strrev
= str.reverse, str.trim = strtrim, str.split = strsplit, str.join =
strjoin), so the globals now alias the string-table entries by value via
RegisterGlobalAlias, as tinsert already does. Verified in-game:
strtrim == string.trim and ClassicAPI.strtrim == strtrim.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-18 03:32:31 -05:00
Brues 8b96fccfe9 refactor(addons): pass an addon file's name and table as real arguments
4.3.4 hands each addon file (addonName, addonTable) as real call
arguments: LoadAddOn puts one table on the stack and
FrameScript_ExecuteBuffer's wrapper path pcalls every file of the addon
with the name and that table. We injected a source preamble instead,
`local arg={"<Name>", __addonns("<Name>"), n=2};`, backed by a gated
global.

An addon file that uses `...` now compiles as a vararg function, and
the file loader gets a C closure that calls it with the name and the
addon's table. The __addonns global and its one-shot gate are gone.
Only the immediate-run file funnel gets the closure, never loadstring,
whose chunkname is forgeable; GetAddOnLocalTable reads the same table.
2026-10-18 03:16:06 -05:00
Brues 9d3bdfb6ad feat(focus): follow 4.3.4's focus, and give every unit event to focus, nameplates and marks
Every unit event the engine fires now reaches focus, nameplateN and
markN, as 4.3.4 does for its focus: the unit gets a script-registration
bit, so the engine watches its fields, and whatever the engine fires
for the unit fires for the token too.

- A co-hook on the registration recompute (FUN_0060c520) keeps bit
  0x8000 on units with one of these tokens. Post-init runs it too, so a
  unit coming back into range is watched again. 0x2000 is SuperWoW's
  and WeirdUtils' sparkle bit on every unit.
- nampower replaces the broadcast (0x00515E50) and the combat feedback
  (0x00494600) with detours that never call the original, so neither
  can be co-hooked. Their 38 + 4 CALL/JMP sites, which no loaded DLL
  touches, are redirected to functions that call the original address
  and then fire for the unit's tokens. Sites are found by a .text scan
  and patched only when the counts match Ghidra's xrefs.
- The tokens gain UNIT_COMBAT, UNIT_NAME_UPDATE, UNIT_PORTRAIT_UPDATE,
  UNIT_MODEL_CHANGED, UNIT_CLASSIFICATION_CHANGED and group-stat
  updates. TokenObserver now serves only focustarget: with SuperWoW
  every unit is engine-watched, so an observer would double-fire.

Focus drop rules follow 4.3.4 where 1.12 has the data: out of range is
kept for you, your pet, a party or raid member or their pet (the
engine's own target rule); death while not friendly, or arrival already
dead and not friendly; becoming not selectable. Death and the flag act
on the change. 1.12 has no duel exception and no SMSG_BREAK_TARGET.

%f in sent chat (4.3.4's ChatParserParseText) becomes the focus's name,
with a {rtN} prefix when marked, or FOCUS_TOKEN_NOT_FOUND.

The .text bounds move into Offsets.h (shared with interface/Export).
The focus still survives /reload; focustarget events stay as a
ClassicAPI extension.
2026-10-18 02:54:02 -05:00
Brues 42d037f080 fix(text): lay out inline-icon lines the way 4.3.4 does
Chat lines with icons ran past the frame edge after 47b258a. An icon
now starts at the previous glyph's ink edge, but every measure counts
that glyph by its advance, so a glyph whose cell is wider than its step
("[" in chat) pushed each following icon and the rest of the line past
the wrap budget. Cap the ink edge at the glyph's base advance.

Match 4.3.4's CGxString layout for the rest:

- Every wrap sizes icons with the fontstring's layout scale, as 4.3.4
  passes m_layoutScale to each CalcWrapPoint. The height getter, the
  rebuild's truncation and the break array set a fontstring scope the
  wrap stepper reads (new co-hook on the break array).
- A line whose tallest icon passes the font height moves itself and the
  later lines down by the overflow (InitializeText), and the origin
  finalize justifies the block with the summed extra
  (InitializeViewTranslation), via a co-hook on FUN_005CDF70.
- GetStringHeight sums each wrapped line's overflow
  (GxuFontGetWrappedTextHeight) instead of adding the tallest icon once.
- A link's hit band grows toward where its icon reaches, by the vertical
  justify.
2026-10-18 01:26:55 -05:00
Brues af4a379311 feat(equipmentset): follow 4.3.4's equipment manager
UseEquipmentSet now behaves like 4.3.4's CGEquipmentManager:
- in combat only the weapon slots swap (one COMBAT_SWAP message);
- missing items and full bags report through UI_ERROR_MESSAGE;
- bank items are used only while the bank is open, and then equip
  straight from the bank;
- a swap in flight or an item on the cursor refuses the call.

EQUIPMENT_SWAP_FINISHED now fires when the swap settles instead of
during the call: success when the paperdoll matches, failure on an
SMSG_INVENTORY_CHANGE_FAILURE for one of the moved items, or when the
paperdoll stops changing short of the target. Its failure value is nil,
not 0. CanUseEquipmentSets and the set buttons are blocked meanwhile.

GetEquipmentSetInfo uses 4.3.4's GetSetStatus counts and strict
IsSetEquipped; GetItemIDs and GetItemLocations return all 19 slots with
the 0/1/-1 markers; set buttons also grey when a replaced item is
locked. Set names go through a port of ScrubString. Item tooltips get
the "Equipment Sets:" line (dontShowEquipmentSetsOnItems hides it).
2026-10-18 00:24:00 -05:00
Brues 2b9d0e7127 fix(player): fire HEARTHSTONE_BOUND on SMSG_PLAYERBOUND
The server re-sends SMSG_BINDPOINTUPDATE at login and on every map
change, which needed two gates to filter out. SMSG_PLAYERBOUND (0x158)
is sent only from the bind spell effect, right after the bind-point
update, so it needs no filtering. 1.12 handles it in the shared player
packet handler FUN_005E38C0.

Subscribe through Net::PacketDispatch instead of hooking the bind-point
handler, which drops one MinHook and the two unused offsets.
2026-10-17 23:46:39 -05:00
SkeewirtandBrues a68fb0a6be fix(frame): keep a scroll child clipped when its ScrollFrame moves (#60)
* fix(frame): keep a scroll child clipped when its ScrollFrame moves

A frame a ScrollFrame draws carries a "scrolled" flag (0x2000 at +0xB4):
the strata pass skips it and the ScrollFrame draws it inside a viewport
cut to its rect. SetScrollChild sets the flag through the setter at
0x0076A400, which also marks the scroll child (0x4000) and recurses into
child frames. SetParent sets a moved frame's flag from its new parent
through the same setter, and the recursion doesn't stop at a ScrollFrame,
so moving a frame that holds a ScrollFrame under an unscrolled parent
cleared the flag on the scroll child and everything in it. The strata
pass then drew them whole, past the ScrollFrame's edges.

AceGUI-3.0 builds each widget under UIParent and then moves it into its
container, so every AceGUI ScrollFrame spilled: AceConfigDialog-3.0's
pages drew below the Interface Options window (61 frames under Zygor
Guides Viewer 2.0's "Display" scroll child had lost the flag).

Hook the setter to keep a frame marked as a scroll child scrolled when a
value is only being passed down (third argument -1). SetScrollChild's
own calls are unchanged.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
AceConfigDialog-3.0's Interface Options pages clip and scroll inside
their box; on the "Display" page no frame under the scroll child lacks
the flag any more (61 did before), and a ScrollFrame built under
UIParent and then moved keeps its content, its content's children and
a child added afterwards scrolled.

* docs(frame): describe ScrollFrame clipping without version history

State what stays clipped and when, with AceGUI-3.0 as the case it
serves. Remove the vanilla comparison and the engine flag explanation;
the comment in src/frame/ScrollChildren.cpp already records them.

* fix(frame): skip scroll children the way 3.3.5's setter does

3.3.5's CSimpleFrame::SetBeingScrolled (0x00490F60) does not pass the
scrolled value into a child frame marked as the scroll child, and its
direct call is not gated: a scroll child that is itself given a new
parent takes the new parent's value. The hook forced any scroll child
scrolled on a pass-down call, which also kept a directly reparented
scroll child clipped to its old ScrollFrame.

Skip a scroll child only inside the setter's own recursion, told apart
by a depth counter (the setter is its only nested caller). SetParent's
and SetScrollChild's direct calls run unchanged.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 20:40:56 -05:00
SkeewirtandBrues 721f32ac77 feat(map): keep the closed world map on the player's zone (#71)
* feat(map): keep the closed world map on the player's zone

GetPlayerMapPosition("player") reads the map the world map is set to,
open or closed, and returns 0,0 off it. The 3.x FrameXML resets that
map to the player's zone in WorldMapFrame_OnHide and in WatchFrame's
PLAYER_ENTERING_WORLD and (map closed) ZONE_CHANGED_NEW_AREA handlers;
vanilla has neither, so after zoning the closed map stays on the old
zone. Do the same resets from the bundled addon. Zygor Guides Viewer's
travel steps read the player's position this way.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
after logging in, the closed world map is on the player's zone (Darkshore)
and GetPlayerMapPosition("player") returns the player's position there.
Not checked yet: changing zones with the map closed (the
ZONE_CHANGED_NEW_AREA reset) and closing the map on another zone (the
OnHide reset).

* docs(map): describe the closed world map without version history

State what the map does and when it goes back to the player's zone,
and add that a zone change does not move the map while it is open.
Remove the 3.x and vanilla comparison and the FrameXML handler names;
the code comment in Util/WorldMap.lua already records them.

* docs(readme): keep Highlights for major features

Single-behavior fixes (faction while loading, <Script file> paths, the
closed world map, the quest completed line, SetParent frame levels,
frame alpha, OnSizeChanged sizes) each had a row in the Modern client
behaviors table. Remove those rows and point to docs/API.md, where each
fix keeps its own section.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 20:26:57 -05:00
Brues fcdc24471c fix(spell): latch remote channels on +0x228 like the player's
The broadcast +0x228 field lags another unit's channel start by up to
~1 s, and UnitChannelInfo returned nothing until it caught up. So the
UNIT_SPELLCAST_CHANNEL_START it fires from the SMSG_SPELL_START stamp
disagreed with the getter, and cast bars that poll on the event (pfUI
nameplates) missed the channel whenever the field was late.

Mirror the player's confirmed latch per remote channel: the packet stamp
stands until the field has shown the spell, and a confirmed field that
clears before endMs is the channel ending early. That drops the entry and
fires CHANNEL_STOP, where it used to run out the full computed duration
(no packet reports a remote interrupt on Turtle).
2026-10-17 20:10:37 -05:00
Brues 58f5b4f78e fix(spell): keep remote channel times through the SPELL_GO cast-slot clear
The engine's SPELL_GO handler calls ClearCastingSpell on the caster for
every spell, including a channel at the moment it starts. Our co-hook
treated that as an abort and evicted the SMSG_SPELL_START cache entry, so
UnitChannelInfo never had start/end times for another unit's instant
channel (bandages). ClearCastingSpell only ends the cast slot; a channel's
lifetime is the +0x228 field UnitChannelInfo already gates on, so that
route no longer evicts channel entries. The failure packets still do.

Fixes #102
2026-10-17 20:08:18 -05:00
Brues 6be4aac9fb feat(macro): resolve every macro's display the way 3.3.5 does
Compared Macro::ShowTooltip against 3.3.5's decompiled MACRONODE::Parse,
FindSpellID and GetFullIconPath (WoW/Source/Ui/UIMacros.cpp) and fixed
the differences:

- Every macro body is parsed, directive or not. A question-mark macro
  with no #show now shows its first action's icon, and its button
  follows that action's cooldown, count and usable state; the tooltip
  stays the engine's (Kind::Implicit). #show counts anywhere in the
  body, not only on line 1.
- "#showtooltip none" stops the parse: the macro keeps its own icon and
  holds no spell, instead of greying out.
- /castrandom and /userandom show their first entry (3.3.5 cuts the
  value at the first comma); they used to grey the button.
- /equip and /equipslot lines are collected and resolve to items only.
- Bare numbers 1..23 are inventory slots, the equipped bags included.

Edits now always end in a repaint, as 3.3.5's EditMacro does: the engine
repaints a macro's buttons straight after its parse, before our rescan,
so a re-parsed body is marked and repainted on the next tick, and a
reader's catch-up defers its repaint instead of firing
ACTIONBAR_SLOT_CHANGED from inside a button handler.

Implicit macros are also parked across the unlearn sweep, so a
condition-picked value can't delete a macro from the bar.
2026-10-17 19:49:39 -05:00
Brues a6270469e1 refactor(chatbubble): move the bubble list offsets into Offsets.h
C_ChatBubbles.GetAllChatBubbles defined the engine's bubble list head
(0x00B6F038) and link offset (+0x318) as file-local constants. Move them
to Offsets.h as VAR_CHAT_BUBBLE_LIST_HEAD / OFF_CHAT_BUBBLE_LINK_NEXT,
documented as 3.3.5's CGChatBubbleFrame list and the engine walks they
mirror. No behavior change.
2026-10-17 19:30:16 -05:00
Brues a8f73623c4 perf(nameplate): enumerate the engine's shown-plate list, not every object
NamePlate::Walk walked the whole object hash table every frame (and on
every C_NamePlate.GetNamePlates call) to find units with a plate. 1.12
keeps the same shown-plate list as 3.3.5's s_namePlates (head
0x00C4D92C, next at plate+0x4E0), each plate carrying its unit's GUID
(+0x4E8). Walk that list and resolve each plate's unit by GUID, as the
engine's own NamePlateClearAll (FUN_0060F890) does; a plate still counts
only while unit+0xE60 points back at it.

PlateReassigned becomes one read of the plate's GUID instead of a scan of
the tick's snapshot. GetNamePlates now returns the engine's order
(farthest from the screen centre first).

The old comments claiming the list was unsafe to read and that release
callers "transiently zero +0xE60" are replaced: the list is re-sorted
only by main-thread engine code, every plate on it is bound, and every
FUN_00608A10 caller is a real release.
2026-10-17 19:27:45 -05:00
Brues 47b258ad95 fix(text): size, space and align inline icons by the engine's own rules
The inline-texture backport placed icons with hand-tuned constants: a
0.18 x font lead/trail pad, a 0.6 x font vertical centre, a -1px region
nudge, and written sizes taken as raw screen pixels. Replace all of them
with the rules from the 3.3.5 / 4.3.4 clients (decompiled; the size
formula's helpers confirmed against the real 4.3.4 binary):

- A written size multiplies by fontPx / (14 x ddcWidthScale), so it
  follows the text's size, the UI scale and the resolution, and then by
  the fontstring's layout scale, as 3.3.5 does. Size defaults follow
  ParseEmbeddedTexture: ":0:2" is a width ratio, ":20:0" is font-wide.
- An icon starts at the previous glyph's ink edge (bearing + cell width)
  plus the face's outline gap, found by replaying the run's placements
  with the emitter's own glyph helpers; the next glyph starts at the
  rounded icon edge.
- Vertical alignment follows the node's justify-V (node+0x50).
- Offsets move only the drawn icon; a positive offsetY now moves it up.

GetCoinTextureString now matches 3.3.5: default height 14, a space
between denominations, and retail's 2:0 coin offset in the strings.

The four Coordinate statics at 0x00832A40 get their real names
(VAR_COORD_DDC_WIDTH_SCALE and siblings). Known gap: the fs-level wrap
callers can't see the fontstring, so they budget icons at layout scale 1.
2026-10-17 19:14:17 -05:00
Brues ac6bd552d5 fix(addons): rebuild the file index with the engine's own clear on /reload
Rescan re-ran the boot indexer on two subtrees, which only adds files, and
skipped its whole run when the index's built latch was 0. The SavedVariables
unload pass clears that latch whenever it writes a new SV file, so on that
/reload no new folder, metadata change or display-array rebuild happened.
Call FUN_VFS_INDEX_CLEAR (0x00646FC0) instead - the clear the engine itself
uses after its own file writes - and drop the latch gate. The next lookup
rebuilds the index from disk, so deleted files drop out too.

AddOns::Toc::FindValue now matches lines the way the TOC parser does: skip
a UTF-8 BOM, break lines at CR or LF, and accept any spaces after "##"
before the key, which must be followed directly by ':'. Callers pass the
bare key.

Also correct the notes that said a first-ever SavedVariables file stays
unreadable until restart; the engine's unload pass already handles it.
2026-10-17 18:42:51 -05:00
SkeewirtandBrues 2a05baee8d feat(cvar): GetCVar returns nil for an unknown cvar (#82)
* feat(cvar): GetCVar returns nil for an unknown cvar

Later clients return nil from GetCVar for a name they do not know; vanilla
raises "Couldn't find CVar named '<name>'". Ported code uses the nil as
a feature probe - LibCamera-1.0 opens with
if not GetCVar("cameraYawE") then return end, which throws at file load
on vanilla.

Co-hook Script_GetCVar: a string name that FUN_FIND_CVAR (the lookup
Script_GetCVar and C_CVar.DoesCVarExist share) does not find yields nil.
Everything else, including non-string arguments, runs the engine function
unchanged. The glue state registers the same function, so both match.

Verified in-game (1.12.1 client via VanillaFixes): GetCVar with an unknown
name returns nil at file load, without an error.

* feat(cvar): GetCVarDefault stops raising for an unknown cvar

Script_GetCVarDefault has the same isstring -> tostring -> FUN_FIND_CVAR
-> raise shape as Script_GetCVar, so it gets the same co-hook. Both now
return no values for an unknown name, matching 1.15.9 (`/dump` prints
"empty result" for each) instead of a single nil.

Docs: describe behavior only, without version or vanilla-gap notes.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 18:26:46 -05:00
SkeewirtandBrues 80ef0e2988 feat(lua): give modern XML handler bodies their implicit parameters (#84)
* feat(lua): give modern XML handler bodies their implicit parameters

Later clients compile an XML handler body as a function whose parameters
name the script's arguments - self, then elapsed / button, down /
event, ... and so on. Vanilla compiles it as a zero-parameter chunk and
publishes the frame and arguments only through the this / argN globals,
so a ported <OnLoad>self:Foo()</OnLoad> indexes a nil global.
Zygor Guides Viewer 2.0 has 85 such bodies; 13 fail at load.

For a chunk compiled by the XML script funnel FUN_00704C70 (return
address 0x00704C8C, engine-built chunkname "<Frame>:<Script>") whose body
reads self - or reads one of its script's parameter names and none of
this / argN - wrap it as return function(self, <names>, ...) ... end,
reusing the vararg path's materialize-the-inner-function shape.
Frame::ScriptArgs already pushes (self, arg1..argN) in that order. Vanilla
bodies are untouched, so FrameXML and 1.12 addons keep their globals and
no names are shadowed.

`event` alone doesn't trigger the wrap. Vanilla sets a global `event`
during OnEvent dispatch, so FrameXML's own
<OnEvent>ActionButton_OnEvent(event)</OnEvent> bodies (about 250) already
work; a body that also reads self still gets (self, event, ...), which
binds the same value.

Adds RET_LUA_SCRIPT_COMPILE (found by scanning FUN_00704C70 for the E8
call to luaL_loadbuffer; the same scan reproduces RET_LUA_FILE_COMPILE),
an XmlHandlerArgs transpile toggle, and a 6th _classicapi_TranspileStats
return counting wrapped handlers.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
probe XML bodies see self in OnLoad, elapsed in OnUpdate, button in
OnClick ("LeftButton") and event in OnEvent; Zygor's bodies load without
an error, and 112 of the 36,627 chunks compiled that session were wrapped.

* fix(lua): match 3.3.5's handler parameters; treat ... as a modern body

OnSizeChanged binds (self, w, h), as 3.3.5's wrapper does, not
(self, width, height); the table now names its 3.3.5 source.

A handler body with a ... expression is wrapped with its named
parameters. Lua 5.0 can't compile one, so only a body written for later
clients has it, and the plain vararg wrap gave an OnEvent body's ...
(self, event, args) instead of the arguments after event.

The docs list each script's names and drop the version history, and say
the values need SetModernScriptArgs on.

* fix(frame): pass OnSizeChanged the size in GetWidth/GetHeight units

FUN_FRAME_ON_SIZE_CHANGED (0x0076B660), the only code that fires
OnSizeChanged, pushed the frame's screen-rect size in raw layout units:
a 20 x 10 frame's handler saw (0.0092, 0.0046). 3.3.5 divides out the
frame's layout scale (OnFrameSizeChanged, 0x0048FA20) and converts with
the chain 1.12's own GetWidth uses (Game::InternalToPixel) before the
script runs.

A co-hook now does both: convert, then divide by the frame's effective
scale (OFF_REGION_EFFECTIVE_SCALE). Verified in game at a 0.91 UI
scale: (19.99993, 9.99997) against GetWidth/GetHeight's (20, 10).
Converting alone gave (18.2, 9.1). The vmethod uses the values for
nothing else, and neither stock FrameXML nor any installed addon reads
OnSizeChanged's arguments.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 16:27:11 -05:00
SkeewirtandBrues 5df5ce00cf fix(xml): resolve <Script file> subdirectory paths relative to the XML file (#80)
* fix(xml): resolve <Script file> subdirectory paths relative to the XML file

The XML file processor joins <Include file> onto the including file's
directory, but <Script file> only when the value has no backslash
(strchr at 0x006EE06E); a value with one is loaded from the game root.
So <Script file="widgets\AceGUIWidget-Button.lua"/> inside
Libs\AceGUI-3.0\AceGUI-3.0.xml fails with "Error loading
widgets\AceGUIWidget-Button.lua" - all 23 AceGUI-3.0 widget files in
Zygor Guides Viewer 2.0, and every other addon that embeds AceGUI-3.0.
Later clients resolve it relative to the XML file.

Co-hook the XML file processor (FUN_XML_LOAD_FILE) to track the file being
processed, and at the <Script> call into FUN_LUA_LOAD_FILE (return address
RET_XML_SCRIPT_FILE_LOAD) retry a backslash path that does not exist as
given against that file's directory, only when the joined file exists.
Root-relative paths that load on vanilla are unchanged. FUN_LUA_LOAD_FILE
is already co-hooked by AddOns::SavedVarsFirst, which now calls
Xml::ScriptPath::Resolve first.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
a probe addon's <Script file="sub\File.lua"/> loads from its XML file's
folder, and Zygor's AceGUI-3.0 option pages, built from those widget
files, work.

* refactor(xml): share the Lua file-loader hook; collapse .. in Script paths

FUN_LUA_LOAD_FILE now has one owner, Script::LoadFile, which runs path
rewriters and then suppressors. Xml::ScriptPath is a rewriter and
AddOns::SavedVarsFirst a suppressor, so neither module reaches into the
other's hook.

Xml::ScriptPath joins onto the XML file's folder with each \..\
collapsed first, as FUN_XML_LOAD_FILE does before its own joins; the
tracked pointer is the caller's uncollapsed path, so an XML file reached
through <Include file="..\x.xml"/> joined onto a path with .. in it.

The user docs no longer name later clients or what 1.12 does.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 15:52:58 -05:00
SkeewirtandBrues 1297b9522a feat(macro): accept a macro name in GetMacroInfo/EditMacro/PickupMacro/DeleteMacro (#96)
* feat(macro): accept a macro name in GetMacroInfo/EditMacro/PickupMacro/DeleteMacro

2.0+ clients take `index or "name"` in all four; vanilla raises
"Usage: DeleteMacro(index)" (etc.) for a name. Co-hook each script
function: a non-numeric string first argument becomes the macro's
1-based index via FUN_MACRO_NAME_TO_SLOT (the GetMacroIndexByName
resolver), and an unknown name becomes 0, which each original treats
like any out-of-range index (GetMacroInfo returns nils, the others do
nothing). Zygor Guides Viewer clears its scratch macros with
DeleteMacro("ZygorGuidesMacro" .. i) every time a step starts.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
an unknown name is a no-op in all four, and Zygor's DeleteMacro calls on
every step start run without an error. The known-name path hasn't run
in-game yet: the test character has no macros.

* docs(macro): say what EditMacro returns for an unknown macro name

An unknown name leaves EditMacro returning the first empty slot's index
(or 0 when every slot is full), the same as an out-of-range index and as
3.3.5; the section said all three non-GetMacroInfo functions "do
nothing". Also drop the patch-version mention.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 15:37:48 -05:00
SkeewirtandBrues b3188ced2a feat(tradeskill): add GetTradeSkillRecipeLink and IsTradeSkillLinked (#75)
* feat(tradeskill): add GetTradeSkillRecipeLink and IsTradeSkillLinked

GetTradeSkillRecipeLink(index) links the recipe in a trade-skill row as
an enchant: link carrying the recipe's spell ID, in the form the client's
own GetCraftItemLink (0x004F72A0) gives an enchanting formula
(|cffffffff|Henchant:%d|h[%s]|h|r, format at 0x0084D410), with the
spell's name in the client's locale. Rows are read as the engine's row
functions read them, so a header row (spell ID -1) returns nothing.
Vanilla's window only links the item a recipe makes.

IsTradeSkillLinked() returns nil: on this client the trade-skill window
and its functions only describe the player's own professions, since a
received trade: link opens ClassicAPI's separate viewer.

Zygor Guides Viewer 2.0 calls both on TRADE_SKILL_SHOW to record the
recipes the player knows.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
in the First Aid and Cooking windows, all 15 recipe rows link the row's
own spell (checked against GetSpellInfo) and header rows return nothing;
IsTradeSkillLinked() returns nil.

* fix(tradeskill): match 3.3.5's GetTradeSkillRecipeLink and show its links

GetTradeSkillRecipeLink now builds 3.3.5's link: gold, "Profession:
Recipe" (the profession from the engine's SkillLineAbility lookup
FUN_006de040, for the player's race and class), gated on
SPELL_ATTR_TRADESPELL. Empty names are pushed as the record holds them,
and the index is checked as a double before the cast, the way the
engine truncates and compares unsigned. IsTradeSkillLinked returns
(nil, nil), as 3.3.5 does. Both globals get doc descriptors.

1.12's SetHyperlink accepts enchant: only for records with +0x0C == 3,
which no trade-skill recipe has, and raises "Unknown link type" for the
rest. Tooltip::Hyperlink now shows the spell tooltip for a trade-spell
enchant: link, as 3.3.5 does. That also fixes clicking SuperWoW's
GetTradeSkillItemLink(index, 1) links; its SetHyperlink patch at
0x00532210 runs after this co-hook and handles only quest:.

SPELL_ATTR_TRADESPELL moves to Offsets.h now that two files use it.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 15:30:20 -05:00
SkeewirtandBrues f55893fdf4 feat(frame): Button:Set/GetNormalFontObject and Frame:IsProtected (#93)
* feat(frame): Button:Set/GetNormalFontObject and Frame:IsProtected

- button:SetNormalFontObject / GetNormalFontObject: 3.0's names for
  vanilla's SetTextFontObject / GetTextFontObject; delegate to them.
  Zygor Guides Viewer 2.0 and AceGUI-3.0 call the new names.
- frame:IsProtected() returns false, false: vanilla has no protected
  frames (the secure system arrived in 2.0). AceHook-3.0 asks before
  hooking scripts.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
Zygor sets its guide window's tab fonts with SetNormalFontObject while it
builds, without an error. Not yet checked: that the font set reads back
through GetTextFontObject and the reverse, and IsProtected's two values;
the testkit check for those runs at the next login.

* docs(frame): drop version and implementation notes from the new methods

The SetNormalFontObject and IsProtected sections named the patches the
APIs came from, said what 1.12 lacks, and described how the methods are
implemented. User docs describe the contract only.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 15:06:45 -05:00
SkeewirtandBrues e0b2e56070 feat(frame): multiply frame alpha into child frames, as 3.x does (#70)
* feat(frame): multiply frame alpha into child frames, as 3.x does

A frame now draws at its own alpha times its parent's drawn alpha, and
GetAlpha returns the frame's own alpha. Vanilla keeps one alpha per
frame and copies it into the children that exist when SetAlpha runs:

- an XML frame with alpha="0" drew its child frames at full alpha,
  because the attribute is applied before its <Frames> are built;
- a child's own alpha was overwritten whenever its parent's changed;
- a frame created or reparented under a transparent frame drew opaque.

Zygor Guides Viewer's border glow is the first case. It is an
alpha="0.0" frame whose child holds the glow textures, so on vanilla the
glow covered the guide frame from login until the first step flash.

Co-hooks the engine's alpha setter, SetParent, the frame destructor and
frame GetAlpha. Own alpha lives in a table keyed by frame. The engine's
byte holds the drawn value, so region recolors and the Model family's
model alpha read it unchanged. Children are recomputed through their
own vtable setter, as the engine's copy-down calls it.

Vanilla code that shows a child under a transparent parent
(parent:SetAlpha(0); child:SetAlpha(1)) now leaves the child hidden, as
3.x does.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
Zygor's guide frame no longer shows its border glow from login. With own
alphas 0.5 / 0.8 / 1.0, a child and a grandchild draw at 0.4; the child
of an XML frame with alpha="0" keeps its own 1.0 and draws at 0; a child
keeps its own 0.5 while its parent goes to 0.2 and back to 1; a frame
with its own 0.6 draws at 0.3 under a 0.5 parent and at 0.18 once moved
under a 0.3 one.

* fix(frame): match 3.3.5's effective-alpha math and read it from the byte

- Multiply child alpha by truncating (a*b/255), as 3.3.5's
  CSimpleFrame::UpdateAlpha and GetEffectiveAlpha do, instead of
  rounding.
- GetEffectiveAlpha reads the frame's alpha byte, which Frame::Alpha
  keeps at the drawn value, instead of multiplying GetAlpha up the parent
  chain. This is 3.3.5's Script_GetEffectiveAlpha. Drops the now-unused
  FUN_SCRIPT_REGION_GETPARENT.
- Drop the reload cleanup of the own-alpha table. The frame destructor
  hook already removes each frame's entry, and a frame that outlives a
  /reload would have lost its own alpha.
- Rewrite the API.md frame-alpha and GetEffectiveAlpha sections as
  user-facing behavior.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 14:58:24 -05:00
SkeewirtandBrues 20dc9fc962 fix(frame): move a frame's children along when SetParent sets its level (#61)
* fix(frame): move a frame's children along when SetParent sets its level

Vanilla's SetParent gives the frame its new parent's strata and level + 1,
but calls the level setter without its children flag, so the frames under
it keep the levels they had. A panel built on its own and then moved into a
raised window draws its contents behind that window: Zygor Guides Viewer
2.0's AceConfigDialog-3.0 panel in the Interface Options window had its
widgets at levels 1-4 under a window at level 5.

Hook the level setter (0x0076A4F0) and pass the children flag on
SetParent's two calls, recognized by their return addresses. The setter
then moves each same-strata child by the same amount, recursively.
Script SetFrameLevel and the setter's other callers are unchanged.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
the AceConfigDialog-3.0 panel's widgets draw above the Interface Options
window, and none of its 18 frames sit below the window's container any
more. A frame with a child and a grandchild moved under a level-20 frame
sits at 21/22/23, and at 0/1/2 once moved to no parent.

* refactor(frame): patch SetParent's children flag instead of hooking the setter

The two `push 0` that pass the level setter's children flag from SetParent
become `push 1`, which is what 3.3.5's SetParent passes. This drops the
MinHook on the level setter, which 11 call sites share, and the
return-address checks. Each site's bytes are checked before the write, as in
Quest::CompleteMessage.

Docs: describe only the current behavior in API.md and the README row.

Verified in-game: a frame with a child and a grandchild moved under a
level-20 frame sits at 21/22/23, and at 0/1/2 once moved to no parent.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 14:08:03 -05:00
SkeewirtandBrues 51d226f67d feat(tooltip): SetHyperlink takes full links and spell:/quest: links (#68)
* feat(tooltip): SetHyperlink takes full links and spell:/quest: links

Vanilla's GameTooltip:SetHyperlink matches only a bare `item:` or
`enchant:` payload and raises "Unknown link type" for anything else,
including the full |cff..|H..|h[..]|h|r links 2.0+ GetItemInfo and chat
hand out. Co-hook it:

- a full link is reduced to the payload between |H and |h;
- spell:<id> builds the SetSpellByID tooltip;
- quest:<id> shows the cached title and objectives text (tokens
  expanded by the engine's quest-text substituter); an uncached quest
  leaves the tooltip empty and queues the quest query once;
- everything else runs the engine function on the payload.

Quest::Cache::Lookup gains `unique`, the engine's own dedup flag (the
last _GetRecord argument, previously passed as an unused 0), so a
tooltip redrawn every frame waits on one queued callback.

Zygor Guides Viewer reads quest titles with
SetHyperlink("|Hquest:<id>:1|h[q]|h") and item names with full links.

Verified in-game (1.12.1 client via VanillaFixes): on a
GameTooltipTemplate tooltip, a full Hearthstone link shows Hearthstone's
tooltip, "spell:133" shows Fireball's, and "quest:957" shows Bashal'Aran's
title and objectives.

* refactor(tooltip): share the C tooltip line helpers; tidy SetHyperlink

- Add tooltip/Lines.h (Clear / Add / Show over the engine's tooltip clear,
  raw add-line and Script_Show) and use it in place of the four local
  copies in Hyperlink, CompareItem, totem/Tracker and equipmentset/Tooltip.
  EquipmentSet keeps its exact colors as packed constants.
- SetHyperlink quest colors come from UI::ColorData (HIGHLIGHT_FONT_COLOR,
  NORMAL_FONT_COLOR) instead of hand-packed doubles.
- spell:<bad id> now clears the tooltip, like quest:<bad id>, instead of
  leaving the previous tooltip's lines.
- Rewrite the SetHyperlink API.md section in plain English without version
  or vanilla-gap notes.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 13:53:22 -05:00
SkeewirtandBrues eb3c32094c feat(pvp): add IsActiveBattlefieldArena (#77)
* feat(pvp): add IsActiveBattlefieldArena

Stock 1.12 has no arenas, so it answers nil there. Turtle-lineage clients
add arena matches, run in instances IsInInstance reports as "pvp": in a
"pvp" instance their scoreboard asks for arena scores over the hidden
TW_ARENA channel, only an arena answers, and the scoreboard keeps the
reply in WorldStateScoreFrame.arenaData until the world states update
outside an instance. isArena follows that state, as the scoreboard's own
arena view does (Octo's FrameXML, patch-4.mpq: WorldStateFrame.lua and
Turtle_ArenaUI.lua). isRegistered is always nil: the reply has no rated
flag, and the client's queue window only joins skirmishes.

Zygor Guides Viewer 2.0 calls it, unguarded, to decide whether to set
its corpse arrow when the player is dead outside a battleground.

Verified in-game (OctoWoW 1.12.1 client via VanillaFixes): outside an
instance it returns nil, nil. The arena branch has not been exercised in
a match yet.

* refactor(pvp): answer IsActiveBattlefieldArena from DBC data in C

The Lua version read Turtle's scoreboard state (WorldStateScoreFrame.arenaData),
which is nil until the server's TW_ARENA reply lands and depends on Turtle's
FrameXML. The client's own data already marks an arena: a pvp-type map
(Map.dbc instanceType 3) whose area carries AreaTable flag 0x80, the flag
Script_GetZonePVPInfo reports as isArena. Check the zone as well as the
subzone, since the arena maps' areas are top-level zones. The type-3 gate
keeps the open-world rings (Gurubashi, The Maul) out.

Returns booleans, as retail does; isRegistered is always false.

Offsets.h: add OFF_AREATABLE_FLAGS, AREA_FLAG_ARENA and
VAR_PLAYER_SUBZONE_AREA_ID, and correct the zone-change handler's second
argument (the subzone ID, not the parent area ID).

* docs(pvp): note the server only ever creates arena map 26

tortoise-wow's GetBattleGrounMapIdByTypeId sends its one arena type,
BATTLEGROUND_BR, to map 26 (Blood Ring); map 28 (Lordaeron Arena) is
client data only.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 13:41:25 -05:00
SkeewirtandBrues 26ca1b4e84 feat(quest): print "<quest> completed." for chain quests too (#76)
* feat(quest): print "<quest> completed." for chain quests too

The client prints ERR_QUEST_COMPLETE_S on SMSG_QUESTGIVER_QUEST_COMPLETE
only for a quest with no next quest in its chain. The handler (and the
callback it leaves for a quest not yet cached) skips the message when the
cached record's NextQuestInChain (+0x24) is set, so a turn-in in the
middle of a chain printed only the experience and money lines. Zygor
Guides Viewer 2.0 completes a turn-in step only on that line, so its steps
for chain quests stayed open until the next login.

NOP the two `jne` over the message (0x005DC4DC, 0x005DC756), after
checking the bytes, so every turn-in goes through the engine's own
message path: same text, sound and CHAT_MSG_SYSTEM chat type, ahead of
the experience and money lines.

That later clients print the line for every turn-in is an inference, not
read from a later client's binary: the 3.3.5a build of Zygor Guides
Viewer completes chain turn-ins on this line the same way.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
mid-chain turn-ins (The Harvest Golem Mystery 40470, The Red Crystal
4811, As Water Cascades 4812, Bashal'Aran 956, Buzzbox 323 1002) print
"<quest> completed." and Zygor completes the turn-in step at once; a
quest at the end of its chain prints it as before.

* docs(quest): the completed line's order depends on the quest cache

When the quest record is not cached at turn-in, the callback 0x005DC710
prints the line on the record's arrival: after the experience and money
lines, and after QUEST_TURNED_IN. Stop promising a fixed order.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 13:13:52 -05:00
SkeewirtandBrues 7331922070 fix(build): quote the /DEF path so source trees with spaces link (#59)
* fix(build): quote the /DEF path so source trees with spaces link

CMAKE_SHARED_LINKER_FLAGS passes /DEF:${CMAKE_CURRENT_SOURCE_DIR}/src/ClassicAPI.def
unquoted, so a checkout under a path containing a space (e.g.
C:\Projects\Classic API\ClassicAPI) splits the argument and the link fails
with LNK1181: cannot open input file 'API\ClassicAPI\src\ClassicAPI.def'.
Quote the path; the DLL output is unchanged.

Verified: Release/Win32 build now links from a path with a space.

* fix(build): list the .def as a target source instead of a /DEF flag

CMake now emits a quoted /DEF: on every generator, so the hand-escaped
path in CMAKE_SHARED_LINKER_FLAGS goes away, and the .def becomes a link
dependency: editing an export relinks the DLL instead of needing a clean
build.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 02:19:51 -05:00
SkeewirtandBrues 27d8f90f03 fix(unit): UnitFactionGroup("player") answers while addons load (#79)
* fix(unit): UnitFactionGroup("player") answers while addons load

Script_UnitFactionGroup resolves "player" through the in-world unit
descriptor, so it returns nil at file scope, ADDON_LOADED and
VARIABLES_LOADED and only answers from PLAYER_LOGIN. UnitName, UnitRace
and UnitClass already answer then, and later clients answer
UnitFactionGroup too, so ported addons read it at file scope. AceDB-3.0
does exactly that to build its "<faction> - <realm>" profile key, and
fails to load on nil ("attempt to concatenate local 'factionKey'").

Co-hook the engine function: when it answers nothing for the "player"
token, fall back to the login-time race byte (VAR_PLAYER_RACE_BYTE) and
the same race -> faction-group chain its player branch uses. That chain
moves out of C_CreatureInfo.GetFactionInfo into a shared
Creature::Info::FactionGroupForRace; GetFactionInfo's behavior is
unchanged. Once the player object exists the engine answers by itself.

Adds FUN_SCRIPT_UNIT_FACTION_GROUP (slot 13 of table 0x00850438).

Measured in-game before the fix (Octo 1.18.1 client, Human):
UnitFactionGroup("player") = nil at file load / ADDON_LOADED /
VARIABLES_LOADED, "Alliance" from PLAYER_LOGIN; UnitName/UnitRace
answer at every stage.

Verified in-game after the fix (same client and character):
UnitFactionGroup("player") is "Alliance" at file load, ADDON_LOADED and
VARIABLES_LOADED, and AceDB-3.0 sets up Zygor Guides Viewer 2.0's saved
settings.

* fix(unit): keep UnitFactionGroup's in-world nil; describe both engine branches

Script_UnitFactionGroup reads the live faction template when the unit's
object is in the world, and only falls back to the name cache's race when
it isn't. The race fallback now runs only under that same condition (no
player object), so an in-world nil (e.g. charmed by a monster) stays nil
instead of turning into the race's faction. Comments and API.md now say
which engine branch the fallback mirrors.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 02:14:04 -05:00
SkeewirtandBrues 35ef1228eb feat(lua): give each pass of a for loop its own loop variables, as in 5.1 (#66)
* feat(lua): give each pass of a for loop its own loop variables, as in 5.1

Lua 5.0 declares a for loop's variables once for the whole loop (its
parser's forbody activates them before entering the loop block), so every
function made in the body shares one variable, which is nil once a
generic for ends. Lua 5.1 declares them per pass, and 5.1 code relies on
it. Zygor Guides Viewer 2.0's recent-guides menu gives each entry
`checked = function() return ... guide.full end`; on 1.12 it errored
with "attempt to index a nil value" whenever the menu opened.

A new transpile pass rewrites such a loop to the 5.1 manual's own
equivalent, `for __cf_k, __cf_v in e do local k, v = __cf_k, __cf_v;`,
on the same line. It applies only to loops whose body contains a
function, and not when the body assigns to a loop variable (5.0 carries
that into the next pass and 5.1 doesn't). Chunks whose blocks don't
balance are left alone. The trigger scan follows blocks and brackets
without allocating. Toggle: "ForLoopScopes".

Tested offline on the rewriter's own code: 21 targeted cases, and 1,417
addon and Classic Era FrameXML files (67.7 MB). 184 loops were rewritten,
and every rewritten file still compiles under Lua 5.1. The pass adds about
0.03-0.05 s over the whole 67.7 MB.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
the recent-guides menu opens without an error, and functions made in a
generic for, a numeric for and a pair of nested loops each return their
own pass's values.

* refactor(lua): close loop upvalues per pass in the compiler instead of rewriting source

Replace the token-scanning source rewrite with a hook on the parser's
forbody. Lua 5.0's loop variables are the loop's control registers, and
a function made in the body keeps them open until forstat's block ends.
Emitting one OP_CLOSE at the end of each pass, before OP_FORLOOP /
OP_TFORLOOP, gives each function its own pass's values.

The OP_CLOSE is emitted only when a nested function names a loop
variable. markupval already records that on forstat's block, so
nothing is guessed from tokens. A loop that captures nothing compiles
to the engine's exact bytecode.

This fixes the gaps in the source rewrite (indexed and dotted targets,
`function v()`, nested elseif, long target lists). It adds no locals,
so it can't push a function past the 200-local limit, and it adds no
scan to every chunk load. Assignment to a loop variable still steers
the loop, as stock 5.0 code may rely on. The ForLoopScopes toggle is
gone with the rewrite.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 01:58:02 -05:00
SkeewirtandBrues 76cc907bd0 feat(tooltip): add GameTooltip:AddTexture on the engine's own routine (#67)
* feat(tooltip): add GameTooltip:AddTexture on the engine's own routine

Vanilla has the 3.x tooltip-texture feature built in and unexposed:
GameTooltipTemplate declares <name>Texture1..3, the XML-OnLoad scan
binds them (tooltip+0x34C), FUN_005303D0 lays the next one out on the
last line (sized to the line, text shifted right) and the tooltip clear
undoes it. Nothing in the 1.12 binary calls that routine; expose it as
GameTooltip:AddTexture. The engine's limits stay: three textures per
tooltip, none on the header line. Zygor Guides Viewer adds guide
images to its tooltips this way.

Verified in-game (1.12.1 client via VanillaFixes): on a
GameTooltipTemplate tooltip with two lines,
AddTexture("Interface\\Icons\\INV_Misc_Bag_08") shows <name>Texture1
with that file, and ClearLines hides it again.

* fix(tooltip): repair AddTexture layout around the engine routine

The engine's texture routine was never called before, and its layout has
two defects. The tooltip clear re-anchors the line below a textured line
at (0, 0) instead of the template's 2px gap, so that line sat too close on
every later tooltip from the frame. And every re-anchor replaces the
line's offset, so a second texture on one line, or one on the line right
below a texture, broke the text alignment.

Tooltip::ClearItemGuid becomes Tooltip::Clear: the one clear co-hook now
also restores the gap below each textured line. AddTexture refuses a
texture on or right below a textured line, accepts only strings, and
returns whether it placed the texture. Correct the Offsets.h description
of the routine and keep the user doc to the contract.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-17 00:18:26 -05:00
SkeewirtandBrues e9e431e014 feat(frame): add SetClampRectInsets / GetClampRectInsets (#69)
* feat(frame): add SetClampRectInsets / GetClampRectInsets

Later clients let a frame that is clamped to the screen keep a different
rect on screen than its own: SetClampRectInsets(left, right, top, bottom)
grows or shrinks the rect the clamp uses. Zygor Guides Viewer 2.0 sets
them on its frames while building them (a negative top inset lets a
frame's top go off screen), and 3.3.5's own FrameXML uses them too.

The engine clamps a frame to the screen inside its rect calculation
(0x00767A20): it resolves the edges and, for a clamped frame, slides the
rect onto the screen. Hook that calculation: for a frame with insets, take
the unclamped rect, grow it by the insets (converted from the frame's
units to layout units with the inverse of Script GetLeft's scaling), slide
that onto the screen with the engine's own steps and order, and move the
frame's rect by the same amount. Frames without insets go through the
engine's clamp as before. SetClampRectInsets re-lays the frame out, as
SetClampedToScreen does, and (0, 0, 0, 0) clears the insets.

Sign convention from 3.3.5's own calls: WorldMapFrame (0, 0, 0, -60)
"don't overlap the xp/rep bars", chat frames (-35, 35, 26, -50).

Verified in-game (1.12.1 client via VanillaFixes): a clamped 100x100
frame placed 10 above the bottom of the screen stays at 10, moves to 60
with (0, 0, 0, -60) and back to 10 once cleared; a frame placed 20 over
the top is clamped to the edge and, with a top inset of -25, keeps its
20 over. GetClampRectInsets returns the insets set.

* refactor(frame): address review of SetClampRectInsets

Use the existing OFF_REGION_ANCHOR and UI coordinate globals instead of new
duplicate offsets, and move the pixel/anchor-unit conversion into one shared
Game::PixelToInternal / InternalToPixel pair (replacing the copies in
LinePool, Transform and Metrics). Restore only the clamp bit around the
unclamped rect calculation so other layout flag bits survive. Add doc
descriptors for both methods and drop version/implementation notes from
the user docs.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-16 23:56:17 -05:00
SkeewirtandBrues fbcc1c9ae1 feat(editbox): add SetCountInvisibleLetters / IsCountInvisibleLetters (#88)
* feat(xml): read parentKey, function= and button font style= from XML

Later clients' XML has three attributes vanilla's parser keeps on the
node but never reads. Ported UIs lean on all three: Zygor Guides Viewer
2.0 uses parentKey 69 times (its arrow, skin buttons and step frames),
binds its main frame's whole OnLoad with function=, and names button
fonts with style=.

All three hook the engine's per-object XML node loaders. Those run on
the object's layout sub-object ((object+0x24)->vtable[+8], called from
the frame builder at 0x006EE4D9 and the region factory at 0x006F2756),
so the object is `this - OFF_XML_LOADER_SUBOBJECT`. The loaders: frames
FUN_00769820 (every derived frame type's loader calls it first),
textures FUN_0076FE20, font strings FUN_00770F40, and Button's
FUN_XML_BUTTON_LOAD (CheckButton's calls it first). Each hook runs the
engine's loader, then:

- parentKey="Name" sets parent[Name] = object on the Lua wrappers, the
  parent being the object's script-region parent (OFF_REGION_PARENT,
  which GetParent reads). An unnamed element has no wrapper yet, so it
  is registered the way the engine's own lazy path does
  (ScriptRegister(object, NULL), as GetParent does); a named one is
  never registered here, since SetName already did that under its name.
  The builder loads content and child frames before it finalizes, so a
  parent's <OnLoad> already sees its keys, and keys inside a virtual
  template bind on every frame built from it.
- A script element with function="Name" becomes
  frame:SetScript(<element>, _G[Name]). The loader runs before the
  builder's finalize, so a bound OnLoad fires at the usual point.
- A NormalFont / HighlightFont / DisabledFont with style and no inherits
  is applied through the engine's own setter for that state with
  _G[style]. Vanilla reads only inherits there and otherwise leaves the
  button's embedded font empty, so its text had no font.

Adds FUN_XML_FRAME_LOAD / FUN_XML_TEXTURE_LOAD / FUN_XML_FONTSTRING_LOAD
/ FUN_XML_BUTTON_LOAD, OFF_XML_LOADER_SUBOBJECT and
OFF_SCRIPT_REGION_NAME, with their derivations.

Verified in-game (1.12.1 client via VanillaFixes, Zygor Guides Viewer 2.0):
probe XML gets its parent keys on a Frame, a Texture, a FontString, a
button's NormalTexture and a frame inside an inherited template; an
<OnShow function="..."/> handler runs; a button with
<NormalFont style="GameFontHighlightSmall"/> reports that font object.
Zygor's frames build with their keys, its main frame's OnLoad runs, and
it loads without a Lua error.

* feat(editbox): add SetCountInvisibleLetters / IsCountInvisibleLetters

3.3.5's EditBox can count color codes and hyperlink markup toward its
SetMaxLetters limit: SetCountInvisibleLetters(true), or
countInvisibleLetters="true" in XML (its macro text, friends broadcast and
BNet report boxes). Off is the default. AceGUI-3.0's MultiLineEditBox
calls the setter while building.

1.12's SetMaxLetters limit (+0x340) counts only visible letters: its
counter (0x0077BC80) skips the markup classes in the edit box's per-byte
table (+0x330), so with a limit of 5 "|cffff0000abcdefg|r" keeps
"|cffff0000abcde" (checked in-game). That is 3.x's default (off). With the
flag on, the limit check's three counts (returns 0x0077C09F, 0x0077C0C1,
0x0077C0E9) count each markup token at its length instead. The counter's
other callers, the cursor movement and GetUTF8CursorPosition, are
unchanged.

For XML, hook the EditBox node loader (0x00779FB0, identified by the
"letters"/"autoFocus"/"multiLine" attributes it reads after calling the
frame loader) and, after it runs, read the attribute and parse it with
the engine's own boolean parser (0x006F1B30, as for autoFocus). The
loader follows the node-loader convention of the XML attributes change
(OFF_XML_LOADER_SUBOBJECT), which this builds on.

Verified in-game (1.12.1 client via VanillaFixes): with SetMaxLetters(12),
"|cffff0000abcdefg|r" is kept whole with the flag off and cut to
"|cffff0000ab" with it on; an XML EditBox with letters="12" and
countInvisibleLetters="true" reports the flag on and cuts the text the
same way.

* docs: correct GetNumLetters note, drop version comparisons

GetNumLetters counts the letters you see (FUN_007992C0 calls the same
counter as the limit check), not bytes. Remove the 3.3.5 / stock 1.12 /
later-client comparisons from the new XML and edit box sections.

* fix(frame): build extra templates' child frames in CreateFrame

The multi-template graft called the main vtable's +8 slot, which is the
Lua method lookup FUN_00778590, not a node applier, passing the XML node
as the Lua state. Its second call (the +0x24 sub-object's node loader)
applied the template's content, but <Frames> children are built only by
FUN_0076A060 from the finalize step, so an extra template's child frames
were never created.

Call the node loader, then FUN_XML_FRAME_LOAD_CHILD_FRAMES directly, so
OnLoad is not re-run. Correct the notes in Offsets.h and CreateFrame.cpp.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-16 23:42:22 -05:00
SkeewirtandBrues 142faafb13 feat(frame): add SetHyperlinksEnabled / GetHyperlinksEnabled (#92)
* feat(frame): add SetHyperlinksEnabled / GetHyperlinksEnabled

3.3.5 has SetHyperlinksEnabled/GetHyperlinksEnabled on ScrollingMessageFrame
and SimpleHTML only, so register them on those two types' method tables
(0x00CF5294, 0x00CF5328), and hook the three functions both types fire
OnHyperlinkEnter/Leave/Click through (0x007A3780, 0x007A37B0, 0x007A37E0)
to skip the script while a frame's hyperlinks are off. On stays the
default, which is vanilla's behavior.

Zygor Guides Viewer 2.0 turns hyperlinks off on the step lines it fills
with Gold Guide item lists, and back on when they show guide steps.

Verified in-game (1.12.1 client via VanillaFixes): both types report true
by default, false after SetHyperlinksEnabled(false) and true again after
SetHyperlinksEnabled(true), and a plain Frame has neither method, as in
3.3.5. Not yet checked: the skipped script itself (a click on a link with
hyperlinks off), which needs the mouse; that check runs next session.

* refactor(frame): gate hyperlink scripts via RunnerHook, keep Leave

Replace the three MinHooks on the per-type hyperlink fire functions with
a Frame::RunnerHook subscriber keyed on the script slot (+0x320 Enter,
+0x330 Click). OnHyperlinkLeave is never suppressed, so a tooltip shown
before hyperlinks were disabled still closes. Parse the argument with the
engine's loose boolean (default on), as 3.3.5's setter does.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-16 23:27:51 -05:00
GratisNinja86andBrues c243489916 Fixed bleed of druid "Pounce" spell not shown under nameplates (#105)
* Attribute Pounce Bleed to the caster

* fix(aura): attribute triggered auras from the Spell.dbc trigger link

Replace the hardcoded Pounce -> Pounce Bleed table with the DBC link:
any effect of type SPELL_EFFECT_TRIGGER_SPELL whose EffectTriggerSpell
applies an aura gets the trigger's caster.

- Arm the target and attribute on the application hook, so a hit by
  the trigger that the triggered aura never follows (bleed-immune
  target) creates no phantom entry. An existing instance from the same
  caster that the descriptor still lists is refreshed in place, since
  the server's re-apply fires no OnAuraAdded.
- Work for any caster, not only the local player.
- Share the target list (hit list, else the caster) and the duration
  helper with the cast's own aura path.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-10-16 23:12:12 -05:00
Brues 917b15640e feat(quest): add C_QuestLog.GetInfo and C_QuestLog.GetQuestLogTitle
Both run the engine's Script_GetQuestLogTitle (0x004DF930) and repackage
its returns, so title, level, header, collapse and complete/failed state
match the stock GetQuestLogTitle. Also registers Enum.QuestFrequency and
Enum.QuestClassification.

Corrects the Quest::Cache note on +0x14..+0x24: those slots are
RepObjectiveFaction, RepObjectiveValue, the two opposite-rep fields and
NextQuestInChain, not SuggestedPlayers and friends. The 1.12 wire carries
no suggested group size, so suggestedGroup is always 0.
2026-09-30 15:08:38 -05:00
Brues 7ccbbaaf68 fix(compat): stop Turtle's Toggle Movement button erroring
Turtle's Options frame sets GroupFrame_ToggleMovement(state) directly as
the button's OnClick. With modern script args the handler receives the
button as `state`, and `1 - state` errors (Turtle_GroupUI.lua:409). Wrap
the global so only a number reaches the original.
2026-09-30 14:58:58 -05:00
Brues 71805db62f docs(readme): list PickupEquipmentSet and WEAR_EQUIPMENT_SET 2026-09-27 00:07:57 -05:00
Brues 85619155f8 feat(equipmentset): add C_EquipmentSet.PickupEquipmentSet
Equipment sets become action-bar buttons, as in 3.3.5: action type
0x20000000 | setID and cursor type 13. The set can be picked up,
placed, dragged off, and swapped with other actions. The button shows
the set icon, name and tooltip, and grays out while a set item is
locked. A click fires WEAR_EQUIPMENT_SET(setID) and the embedded
EquipmentManager equips the set.

The server drops action type 0x20 without saving it, so placements are
kept in the per-character equipment-set file. The server is sent an
empty slot, and the saved buttons are merged into the
SMSG_ACTION_BUTTONS buffer at login. GetActionInfo and GetCursorInfo
report "equipmentset", name.
2026-09-27 00:05:29 -05:00
Brues 46dc198505 feat(tooltip): add GameTooltip:GetUnit
GetUnit() returns (name, unitToken). The engine drops the token after
SetUnit resolves it to a GUID, so it is kept where it enters:

- SetUnit is re-registered in front of the engine method and stages
  the token; it binds in the unit-builder co-hook that SetEvents
  already owns, before OnTooltipSetUnit fires.
- A build with no staged token is the world mouseover ("mouseover");
  the in-place refresh keeps the bound token.
- Unit-frame hover (Frame::Attributes) stages the frame's unit, since
  the engine resolves "mouseover" only for a live object and an
  offline or far group member has none.

The name follows Script_UnitName's order (live object, group roster
slot, name cache), so offline members resolve for GetUnit and
GetUnitGUID alike.
2026-09-26 22:33:13 -05:00
Brues 7707127d5f fix(macro): add the question-mark icon to the macro icon list
The stock 1.12 macro icon list holds only Ability_* and Spell_* icons,
so on a client without Turtle or pfUI the macro picker cannot select
INV_Misc_QuestionMark, and #showtooltip never gets a macro to take over.

Mirror 3.3.5's loader: seed the icon through pass 3's own append before
the walks, then move it to index 0 after the engine sorts and dedups.
2026-09-26 00:31:19 -05:00
Brues fa7d71435f fix(nameplate): retry CREATED and UNIT_ADDED until they fire
A plate was marked seen before NAME_PLATE_CREATED was sent, and a GUID
entered the tick snapshot before NAME_PLATE_UNIT_ADDED was sent. When a
fire was dropped because its event slot was not claimed yet, the plate
was never announced again until /reload cleared the diff state. pfUI
builds its overlay on CREATED and finds it on ADDED, so such a plate
kept Blizzard's look (brues-code/pfUI#59).

FireWithFrame now reports whether the event went out, and a plate is
marked seen only then. ADDED waits for its slot AND for its frame's
CREATED, so a handler never gets a unit for a plate it was not
introduced to. A deferred GUID gets no token slot and no observers, and
is left out of the snapshot, so the next tick retries it and no REMOVED
fires for an ADDED that never went out.

Not verified in game: the dropped-slot case cannot be forced here, so
only the normal path was built and deployed.
2026-09-25 10:34:40 -05:00
Brues 3467513df9 feat(container): group sorted gear by equip slot
Gear was one category per quality tier, ordered inside by class,
subclass and name, so a helm could sit between two pairs of boots and
an epic helm landed far from a green one. Gear is now one category,
ordered by class, then equip slot, then subclass, then quality (best
first), then name, so like pieces sit together.

The slot key ranks Item.dbc inventoryType through a table rather than
the raw INVTYPE number, which does not follow the character pane (robe
is 20, chest 5; cloak 16). The order is Baganator's: weapons by hand,
ranged and ammo, then armor with shields and off-hands first, head to
feet, then jewelry, shirt and tabard.
2026-09-25 10:19:16 -05:00
Brues 6000df8009 feat(cvar): add C_CVar.SetTempCVar and RemoveTempCVar
SetTempCVar changes a cvar for the session without saving it to
Config.wtf; RemoveTempCVar restores the value from before the first
temp set.

The temp set passes a6 = 0 to the engine setter, the only argument that
marks the config dirty, so it applies the value and runs the change
callback without asking for a save. When something else dirties the
config, a co-hook on the config writer (0x0063D980) points each temp
cvar's value at its saved string for the write and restores it after.
A plain SetCVar over a temp value wins: the entry drops itself, so the
user's set is saved and never rolled back.

Errors mirror Script_SetCVar. Registered in-game and on glue.
2026-09-25 09:59:27 -05:00
Brues fde3beca9d fix(table): keep the stored length on weak-valued tables
The getn heal read a nil at the stored last slot as proof that nobody
maintained the length. For a weak-VALUED table that is false: the
collector clears those slots behind the writer, so `luaL_setn` is still
exactly what the last append left and the holes below it come and go
between two reads.

Compost-2.0 is the casualty. `secondarycache` is `__mode = "v"`, filled
with `table.insert`; `GetTable` walks it with `pairs` and calls
`table.remove(cache, i)` on a live index. Once the GC clears slot 1 and
the stored last slot, the heal bisects to border 0, `luaB_tremove` takes
its `e == 0` empty-table early-out and returns NOTHING, and the next line
indexes with the nil it got back -- "table index is nil" at
Compost-2.0.lua:81, once per recycled table, in every addon that pulls
Compost in through AceLibrary.

The border search is what exposed it (5aa382b's table.insert switch is
not involved -- Compost never appends a nil, so no mark ever applied to
its tables). The walk-down it replaced returned the HIGHEST populated
slot, which is always at or above the live index the pairs loop holds, so
remove still found something; a bisect returns some border and probes its
way down to 0 through the collected slots. That tradeoff was known and
written down -- a weak cache read through table.remove is where it bites.

So gate the heal: `__mode` mentioning "v" returns the stored length
untouched, as rule 3, ahead of the mark. It costs one getmetatable and a
raw `__mode` fetch on the already-rare unhealthy path, so the bisect keeps
its win everywhere else, and the mode is read raw -- the same fetch the
collector's own check uses.

New plumbing: Game::Lua::GetMetatable, from the offset already catalogued
in LuaCAPI.md. LuaEnv::Fenv had rolled its own copy; it now shares this
one.

Verified in game: a three-slot weak table with slots 1 and 3 collected
reports getn 3 and hands back its live slot (0 and nothing before), and
the Compost errors are gone.
2026-09-17 23:39:43 -05:00
Brues 452f3c14fc fix(macro): keep the unlearn sweep from deleting #showtooltip macros
The spell-removal handler FUN_005E9FE0 calls FUN_004E5E20(spellID) right
after the unlearn writer. That sweep walks all 0x78 action slots, resolves
each through FUN_ACTION_SLOT_TO_SPELL -- which is macro-aware, so a macro
slot answers with the primary-spell cache this module writes -- and clears
every slot whose spell matches. The clear notifies with sendToServer = 1,
so CMSG_SET_ACTION_BUTTON goes out and the server persists it: the macro is
gone for good, not until the next reload.

That rule is sound for a cache the engine filled from a /cast line and
wrong for one filled from a display directive, which names an icon rather
than what the button does. `#showtooltip [known:18223] 18223` over a /cast
the player can still perform would lose the whole macro on a respec, and a
conditional directive makes it arbitrary besides -- the cached value is
whichever clause happened to match on the last evaluation.

Co-hook the sweep and park every managed macro's cache at 0 for its
duration, restoring afterwards with a plain field write (nothing we own
changed, so no repaint is owed; the slots the engine really did clear were
announced by its own notify). A BusyScope wraps it because the sweep's
ACTIONBAR_SLOT_CHANGED handlers reach Lookup, whose catch-up would
otherwise re-apply the parked values mid-sweep for slots the loop has yet
to reach. Macros with no directive are untouched.

Consequence: a plain #showtooltip macro whose /cast line names the
unlearned spell now also survives, where stock 1.12 removed it.
2026-09-17 14:04:59 -05:00
Brues 6bb12c3c12 ci: drop the Gitea mirror entirely
octowow.st's Gitea instance would not accept a git push under any
credential scheme, converting the repo off "mirror" status didn't
change that, and its own pull-mirror sync was already unreliable
before any of that -- three commits of narrowing down the actual cause
without ever reaching a fix. The repo is being removed from Gitea, so
there is nothing left to mirror to.

Removes mirror-release.yml, the diagnose-mirror-auth.yml scratch
workflow, and the `mirror` job in build.yml that called it.
2026-09-17 11:49:21 -05:00
Brues 7a08199ba5 ci: replace the status-code probe with a real end-to-end push test
Every scheme in the first diagnostic came back 200 on the GET leg,
which does not actually clear anything -- a bare status code can't tell
a real git advertisement apart from a 200 that's something else, and
`git push` also has a second POST leg the GET-only probe never touched.

Run the real thing instead: `git push --dry-run` end to end against a
disposable ref, with real credentials, under the three most plausible
schemes -- captures git's own diagnostic output instead of inferring
from a client-side parse error that looks the same for a 401, a 403,
and a malformed 200.
2026-09-17 11:41:31 -05:00
Brues a5bb3823fb ci: add a one-shot diagnostic for the mirror git-http auth scheme
Converting the Gitea repo out of mirror status did not fix the push
(same client-side error), which rules out `repo.IsMirror` gating and
means the two prior fixes were both guesses at a credential scheme with
no way to verify which one, if any, the deployed Gitea actually accepts
-- a 401 and a 403 look identical from the git client's side.

Tests six candidate schemes against the real git-receive-pack endpoint
with the real MIRROR_TOKEN, printing only the resulting HTTP status per
scheme -- never the token or a response body. Delete this file once the
working scheme is found and applied to mirror-release.yml.
2026-09-17 11:37:22 -05:00
Brues 8c941c757d fix(ci): authenticate the mirror push with a token header, not oauth2 basic auth
The direct push added in 2fff956 failed every run: git reported
"could not determine hash algorithm; is this a git repository?" against
the Gitea push URL. Reproduced the exact message locally by hitting the
same endpoint with a deliberately bad token -- it is git's confusing
rendering of a plain 401, not a routing or protocol problem (the same
endpoint serves a clean smart-HTTP advertisement for an unauthenticated
fetch).

`oauth2:<token>` as the HTTP Basic auth username is GitLab's convention,
not Gitea's, and Gitea rejected it. Switch to the `Authorization: token
X` header instead -- the exact scheme this same workflow's curl calls
already use successfully against this server -- rather than guess at a
different Basic-auth username convention.
2026-09-17 11:21:27 -05:00
Brues 2fff9564b2 fix(ci): push release tags to the Gitea mirror directly
Gitea's pull-mirror sync is a background queue job: POSTing mirror-sync
only enqueues it, and a failure on Gitea's end (stale pull credentials,
a stuck queue) is invisible from here -- the workflow would just poll
for the tag for 5 minutes and time out, so releases never made it
across.

Replace the ask-and-poll with a direct push: fetch the release tag from
GitHub (shallow, depth 1) and push it straight to the mirror with the
existing MIRROR_TOKEN, which already has write access. A git push either
lands or fails loudly on the spot -- nothing to wait on. Gitea's own
pull-mirror can keep doing whatever it does for everyday commits and
branches; this workflow no longer depends on it working.
2026-09-17 11:09:11 -05:00
Brues bbefdb847d fix(aura): include the player's pet in the PLAYER filter
Blizzard defines the token as "Include only auras that were cast by the
player, or by the player's pet or vehicle"
(AuraUtil.AuraFilters.Player). There are no vehicles here, so the caster
set is player + pet -- but all three comparisons tested
`casterGuid == PlayerGuid()` and nothing else.

A pet's cast carries the PET's guid in the Aura::Source cache, since
that is who SMSG_SPELL_GO names, so "HARMFUL|PLAYER" silently dropped
every aura the pet applied. `!PLAYER` had the mirror bug: it returned
the pet's auras as though a third party cast them.

Centralize on one IsPlayerOrPetCaster predicate rather than fixing each
site -- IsPlayerCast, GroupIsPlayerCast and CachedMatches had already
grown three separate copies of the comparison, which is how they would
drift again. The pet guid comes from VAR_PET_GUID, a live engine global,
so the predicate stays two compares with no object resolve; it runs per
aura slot. A caster of 0 (cache miss) still matches nothing.

Unrelated and untouched: the `isFromPlayerOrPlayerPet` aura field, which
means "applied by ANY player or a player's pet" and is answered from the
caster's HIGHGUID prefix.

Verified in-game: a Hunter pet's Scorpid Poison now returns from
C_UnitAuras.GetAuraDataByIndex("target", 1, "HARMFUL|PLAYER").
2026-09-16 23:32:16 -05:00
Brues 56d2dbbc27 fix(player): file WEAPON_SLOT_CHANGED under PaperDollInfo
Blizzard's generated API docs put all three of this file's events in the
PaperDollInfo system (PaperDollInfoDocumentation.lua), so the descriptor
said the wrong system and would have invented a stray "Item" grouping in
the /classicapi browser. Filing it correctly also lines up
PLAYER_EQUIPMENT_CHANGED and UPDATE_INVENTORY_DURABILITY for whenever
they get descriptors of their own.

Same source confirms the payload: the entry carries no Payload field, so
no arguments is right. It is also flagged UniqueEvent where the two
per-slot events are SynchronousEvent -- recorded in the header comment,
since that makes the per-frame coalescing the event's own shape rather
than a local preference.
2026-09-16 22:25:44 -05:00
Brues 0296e0e5a4 feat(player): add WEAPON_SLOT_CHANGED
Fires with no payload when the item in inventory slot 16, 17 or 18
changes -- equip, unequip and swap alike. The narrow sibling of
PLAYER_EQUIPMENT_CHANGED that swing-timer consumers want, so they no
longer filter three slots out of a 19-slot event in Lua on every gear
change. Blizzard's own Blizzard_SwingTimer registers this event.

Rides the descriptor-field observers Player::Equipment already installs
for PLAYER_EQUIPMENT_CHANGED -- the weapon slots are three of the 19 --
so there is no new hook, no second registration and no polling. The
dispatcher invokes the callback only when a slot's item GUID actually
changed, and seeds each node's mirror from live at registration, so
login and /reload produce no fire.

Coalesced to at most one fire per frame via a dirty flag drained on
WorldTick: one action can change two weapon slots (a two-hander
replacing a one-hander plus an off-hand) and the per-slot observer would
otherwise fire twice for it. The drain checks the reservation slot
before clearing the flag, so a change marked while the reservation is
still unclaimed is held rather than swallowed.

Slot 18 is exempted for the classes whose slot 18 is a relic slot -- a
Libram/Idol/Totem is a passive stat item, not something you swing.
Gated on the same data Script_UnitHasRelicSlot (0x00519E50) reads rather
than a hardcoded class list: ChrClasses.dbc[class] + 0x40, verified in
the disassembly at 0x00519EAE-0x00519EC0 and against the client's own
ChrClasses.dbc, where that column is 1 for PALADIN/SHAMAN/DRUID and 0
for the other six. Read live, since the class-byte global is
repopulated per character-enter.

Not verified in-game yet: built and deployed only.
2026-09-16 20:30:17 -05:00
Brues 6812771a89 fix(event): raise the reservation cap past the 64-slot overflow
MAX_RESERVED was 64 while the codebase carries 65 AutoReserve
instantiations: 60 at file scope plus the 5 lazy function-local ones in
voicechat/Tts.cpp, which construct on first registration and only when
VanillaTTS is absent.

The constructor silently returns once g_reservedCount hits the cap, and
the file-scope 60 all run at static init, so the TTS five land last and
the 65th -- VOICE_CHAT_TTS_VOICES_UPDATE -- was dropped: Slot() stayed
-1 and Fire() no-opped, so the event never fired on any client without
VanillaTTS.

Bump to 96 and record the incident; the comment's "~40 reservations"
figure was stale from the previous overflow at 32.
2026-09-16 20:28:25 -05:00
Brues 4d835aa674 feat(combat): add PLAYER_SWING / PLAYER_SWING_RANGE_UPDATE / C_SwingTimer
Backports the Forever beta swing-timer API. PLAYER_SWING and
PLAYER_SWING_RANGE_UPDATE fire off the packets the engine already sends
for melee/ranged auto-attacks, mirrored as state (parry haste, extra
attacks, on-next-swing abilities, cast-time resets) rather than relayed
1:1, so N packets for one logical reset collapse into one event.

Two bugs surfaced only by in-game testing, not by reading the
disassembly:

- FUN_UNIT_CAN_ATTACK (0x00606980) is __thiscall with the second unit
  pushed on the stack, not __fastcall(ecx,edx) -- Ghidra's decompile of
  the one caller renders it as a plain two-arg call either way, so the
  wrong convention crashed on a bogus ecx read off [ebp+8] garbage.
  Same trap as FUN_SET_CVAR_VALUE.

- The generic engine range core (FUN_006e3480, what
  C_Spell.IsSpellInRange already uses) computes full 3D distance, but
  the server's actual melee-attack gate
  (Unit::CanReachWithMeleeAutoAttackAtPosition,
  WorldObject::CanReachWithMeleeSpellAttack) is explicitly 2D --
  verified by landing hits at 5.08yd 3D distance that the 3D check
  rejected. Melee now gets its own 2D check
  (Combat::Swing::InMeleeRange), reading the same live engine reach
  constants; ranged keeps the 3D core, which matches the server's own
  (also 3D) generic spell-range gate.

Also: attack-start no longer resets the off-hand timer unless the
target is actually in range. Unit::Attack's off-hand reset fires the
instant an attack is declared, even out of range, and the server just
silently re-arms it every 100ms until you're close enough -- firing
PLAYER_SWING there promised a swing time that was not real.

Slam is special-cased for Turtle: every rank in Turtle's own client
Spell.dbc carries AttributesEx2's swing-reset exemption, but packet
timestamps show Turtle's server does not honor it for Slam -- both
melee timers delay after casting it, contradicting both the client
data and the public tortoise-wow reference source.
Combat::Swing::AutoSwingResetOverride is a small extension point
(mirroring Turtle::ComboDuration's Rip override) for this kind of
server/client divergence; src/turtle/SwingReset.cpp registers the
known Slam ranks.

Verified in-game: swing detection (dual-wield, extra attacks
coalescing to one event, cast-time resets), the melee range fix, and
the attack-start range gate. The Slam override has not been
rebuilt/retested yet.
2026-09-16 17:50:13 -05:00
Brues dfbba225d2 fix(macro): correct the loose/mpq split in the icon enumeration
The three macro-icon scan callbacks were named and tagged for the wrong
walker. FUN_LOAD_MACRO_ICONS hands 0x004F0220 to FUN_MPQ_ENUM_FILES (the
archive listfile walk) and 0x004F0350 / 0x004F04F0 to the disk walker,
but Icons.cpp had it exactly inverted: the archive pass was tagged
SRC_LOOSE and both disk passes SRC_MPQ. So GetMacroIcons /
GetMacroItemIcons returned the loose on-disk icons -- nothing at all on a
stock install -- while GetLooseMacroIcons / GetLooseMacroItemIcons
returned the archive set. It went unnoticed because the only consumer,
IconDataProviderMixin, calls all four and concatenates, so only the
ordering within each list changed and never the content.

Tags corrected, and the offsets renamed to what the loader actually hands
them to, with each one's filter recorded since that is the load-bearing
difference between the two disk passes:

  FUN_MACRO_ICON_CB_DISK        -> FUN_MACRO_ICON_CB_MPQ
  FUN_MACRO_ICON_CB_USER_MPQ    -> FUN_MACRO_ICON_CB_DISK_PREFIXED
  FUN_MACRO_ICON_CB_INSTALL_MPQ -> FUN_MACRO_ICON_CB_DISK_ANY

Also replaces a wrong guess in the Offsets.h block. It claimed a filter
inside the SStrDup/array-append helpers downstream of all three callbacks
was what kept INV_* out of the engine's own list. Decompiling the loader
and all three callbacks shows there is no shared downstream helper at
all: the grow-and-append code is inlined identically into each callback,
so the only filtering is what each one does itself. The list is
Ability_*/Spell_* only because passes 1-2 prefix-filter and pass 3 -- the
one that does not -- is a disk walk over a folder that ships empty. A
loose INV_*.blp dropped into Interface\Icons\ does enter the list,
through pass 3 alone. The block now also records the qsort + adjacent
SStrCmpI dedup, that GetMacroIconInfo pushes the empty string rather than
nil for a bad index, and that only GetNumMacroIcons triggers the lazy
build.

Verified in-game.
2026-09-15 10:54:59 -05:00
Brues 930b0c6492 Add C_LossOfControl.GetSchoolLockout
Serving the school-interrupt lockout through the generic list costs a caller
two full BuildList passes -- GetActiveLossOfControlDataCount runs one and
GetActiveLossOfControlData runs another -- plus a Lua table per entry, and
BuildList classifies up to 16 debuff slots with RecordForID on each. All of
that aura work is waste for a caller that only wants the lockout, and a macro
conditional reading it every frame pays it every frame.

The state behind it is g_schoolLock, seven pairs of ticks. Read it directly:
no table, no debuff scan, one pass.

Return a mask rather than a school. Each SMSG_SPELL_COOLDOWN batch locks one
school, so being kicked on fire and then frost leaves two entries active, and
a caller walking the list and stopping at the first SCHOOL_INTERRUPT drops the
rest. filterMask narrows the scan, which is how a caller gets one school's own
remaining time instead of the aggregate.

Also document that the ADDED/UPDATE events diff which effects are active, so
re-locking an already-locked school extends endMs without firing either one --
that expiry cannot be cached on the events.
2026-09-15 10:18:36 -05:00
Brues 428c3308c6 docs(todo): add #101 Frame:SetOnUpdateMode
Records the engine trail found while evaluating it: the per-frame
dispatcher FUN_0076B2C0 (vtable +0x38, __thiscall(frame, float elapsed),
fires the OnUpdate slot at +0x128) and the walk FUN_00765650, which
iterates nine strata buckets of the frame+0x310 intrusive list with NO
visibility check in either place. Visibility is list membership, and that
list is the render list -- which is what splits the enum: Disabled /
RunWhenVisible / RunWhenVisibleOnce need only a co-hook on the
dispatcher, while RunOnce / RunAlways have to be driven from the
already-owned WorldTick because a hidden frame is not in the list at all
and forcing it in would try to draw it.

Also notes the open question (which elapsed the self-driven modes pass,
and whether WorldTick runs before or after the UI pass), that no loaded
DLL references either function, and that RunAlways is the only genuinely
new capability -- the rest is parity with existing idioms.
2026-09-15 02:16:45 -05:00
Brues a33146241e feat(macro): make [button:N] read the click it is running inside
The condition existed but was a stub: it matched only "1" / "leftbutton"
and always passed, because nothing on this client could say which mouse
button had driven the current click. GetMouseButtonClicked can now answer
that, so the condition asks it.

Numbers use the modern API order -- 1 left, 2 RIGHT, 3 middle, 4, 5 --
which is deliberately NOT the order of the engine's internal click
bitmask (where 2 is the middle button); that mask never reaches Lua. A
name is matched as written, so [button:rightbutton] and [button:2] are
the same test, case-insensitively.

Outside a click the answer stays "left button". That is not a cosmetic
default: Macro::ShowTooltip re-evaluates conditional directives off the
world tick with no click in progress, so a nil-means-no-match rule would
change which icon a `/cast [button:2] X; Y` macro displays at rest. The
engine's own no-argument Button:Click() means the left button, so it is
also the honest resting answer for a state-driver poll.

Verified in-game with all five buttons, both directly from OnClick and
through a real macro body -- click -> attribute macro ->
EXECUTE_CHAT_LINE -> SlashCmdList -> SecureCmdOptionParse, which
confirms the click context survives the whole chain -- plus the name
form, the btn alias, and the no-click resting answer.
2026-09-15 01:38:38 -05:00
Brues c7af8d396e feat(frame): accept AnyUp / AnyDown in Button:RegisterForClicks
The engine's RegisterForClicks (0x00782490) SStrCmpI's each argument
against exactly ten literals -- LeftButtonDown 0x1 / LeftButtonUp 0x100,
Middle 0x2 / 0x200, Right 0x4 / 0x400, Button4 0x8 / 0x800, Button5
0x10 / 0x1000 -- treats anything else as contributing nothing, and
ASSIGNS the OR to the click mask. So the collective names later clients
take, "AnyUp" and "AnyDown", did not fall back to the default here: they
zeroed the mask and the button silently stopped answering every real
click, while Button:Click (which ignores the mask) kept working and hid
it. That is what broke the first click-bracket harness yesterday.

Frame::ClickMask re-registers RegisterForClicks on the Button method
registry (0x00CF4E14, new VAR_BUTTON_METHOD_REGISTRY; most recent
registration wins, CheckButton inherits through the type walk). It does
not reimplement the parser: for each AnyUp / AnyDown argument it appends
the five names that collective stands for onto the Lua stack and
tail-calls the engine's own function, which then does the self
typecheck, the parse, the setter and any error text itself. The
collective string is left in place -- the engine's unknown-name -> 0
rule already makes it inert -- so the reshape is purely additive and
the engine's loop terminates exactly as before.

Verified in-game with left, middle and right: AnyUp fires OnClick on
release; AnyDown on press; "anyup" + "LeftButtonDown" (case check) fires
left on both press and release and the others on release only; a
LeftButtonUp control is unchanged; "Fnord" alone still yields no clicks.
2026-09-15 01:04:10 -05:00
Brues a2a2ccb804 feat(frame): bracket the click at the engine's click vmethod
PreClick/PostClick now fire on every click, with or without an OnClick
handler, and GetMouseButtonClicked is live inside OnMouseDown and
OnMouseUp on any frame -- the two things 3.3.5 does that the previous
runner-only bracket could not.

3.3.5 (CSimpleButton::Click FUN_0096fd70 -> FUN_0096f090) fires PreClick,
OnClick and PostClick as three independent `if (slot)` blocks, so
Pre/Post never depended on OnClick. And the frame-manager field behind
GetMouseButtonClicked is written by exactly four dispatches -- that
click, the double-click, and CSimpleFrame::OnMouseDown FUN_0048fc30 /
OnMouseUp FUN_0048fce0 on every frame type -- not by OnDragStart.
Confirmed live on 3.3.5: `down LeftButton LeftButton`, `up LeftButton
LeftButton`, `drag LeftButton nil`. 7a4ab29 had misread +0x16c/+0x174 as
OnClick/OnDoubleClick and made OnMouseDown/OnMouseUp nil; corrected.

1.12 has the same two decision points. The runner interceptor now gates
on all four mouse-button script slots (OnClick +0x4CC, OnDoubleClick
+0x4D4, OnMouseDown +0x150, OnMouseUp +0x158 -- the CSimpleFrame
resolver FUN_0076A0D0's table is recorded in Offsets.h) and scopes the
name from the fire's own "%s" argument. PreClick/PostClick move to a
co-hook on the Button click vmethod FUN_00779540, which every
Lua-creatable button reaches (Button directly, CheckButton's override
toggles then chains to it). The detour fires them through the engine's
own variadic forwarder FUN_007026F0 with the engine's own "%s" literal
and its own name literal for the button mask, so the path and the arg1
pointer are identical to the engine's OnClick fire; the whole click is
scoped, as in 3.3.5. `down` is not supplied -- 1.12's vmethod never
learns press-vs-release. 3.3.5's same-button re-entry guard drops the
whole nested click; 1.12's engine recurses, so this only skips our own
Pre/Post on that re-entry. Net: one new hook.

The previous limitation was justified by a note that SuperWoW
inline-hooks FUN_00779540 and a second MinHook faults (ERROR #132). A
literal scan of every DLL the client loads finds no reference to that
address in any of them, while SuperWoWhook's real targets all appear as
plain literals. The #132 sighting is kept on record; its trigger was not
this function. Both Offsets.h notes rewritten; FUN_BUTTON_CLICK, which
existed only as prose, is now defined.

Verified in-game across real and programmatic clicks: Pre/Post with no
OnClick, full bracket with nested different-button click and restore
(LeftButton / RightButton / UNKNOWN outers), self-click yielding one
extra OnClick and no extra PreClick, CheckButton toggled before
PreClick, plain-Frame OnMouseDown/OnMouseUp reading the button with
OnDragStart nil, double-click without Pre/Post, an OnUpdate watcher
never seeing a value, and /reload -- all with the full DLL stack loaded.
2026-09-15 00:53:17 -05:00
Brues 7a4ab29cb0 fix(input): scope GetMouseButtonClicked to the click dispatch
It read a button captured from the WH_GETMESSAGE mouse-message hook and
evicted two world ticks later, so it reported a button for as long as one
was held, and for a couple of frames after every click -- useless as the
"am I inside a click handler" test it exists to be.

3.3.5 does none of that. The getter (FUN_0050f950) pushes a frame-manager
field that only the four click dispatches ever write -- button OnClick
FUN_0048fc30, OnDoubleClick FUN_0048fce0, and the two secure click paths
FUN_0096fd70/FUN_0096fdd0 that wrap PreClick -> OnClick -> PostClick --
each saving the old value on the C stack, setting its own button argument,
running the handler, then restoring. That C-stack save is what makes a
nested click shadow the outer one and restore on unwind.

1.12 has no such field but the same bracket point: FUN_00779540 (OnClick)
and FUN_00779650 (OnDoubleClick) fire their handler through the runner
Frame::ClickEvents already intercepts, passing the button name as the
fire's only "%s" argument. Mirror the engine's bracket there and read the
name out of the fire, which also inherits the engine's own naming:
Button:Click (FUN_007826C0) folds its optional string down to a numeric
mask, so a bare Click() arrives as "LeftButton" and an unrecognized name
as "UNKNOWN".

GetMouseButtonClicked moves to Frame::ClickEvents with the dispatch it
describes. IsMouseButtonDown and GLOBAL_MOUSE_* keep the message hook,
which is the right source for a device query. The recursion guard now
covers only the PreClick/PostClick pair, so a nested click still gets its
own button scope.

It now returns nil in OnMouseDown / OnMouseUp / OnDragStart, matching
3.3.5, where those paths never touch the field.

Verified in-game across all four dispatches: real and programmatic clicks,
OnDoubleClick, PreClick/PostClick, the nested inner/outer restore, Click()
argument folding, and an OnUpdate watcher that never saw a value outside a
handler.
2026-09-14 22:37:45 -05:00
Brues ef8ea710d4 feat(frame): guard GetPoint against dangling anchor targets
An anchor node (region+0x28 + point*4, vtable 0x0081C44C) stores its
relativeTo as a raw pointer at +0x0C with no weak reference. When the
target frame is freed the pointer is never cleared, so Script_GetPoint
still reads the target's refcount at [relativeTo-0x24+4] and faults --
ERROR #132, ACCESS_VIOLATION at 0x007A2452.

Re-register GetPoint on the Region method registry (front-of-bucket
wins, no MinHook -- the Texture::SetDesaturated mechanism). The
replacement SEH-probes each anchor's target header and hands dead ones
to the engine's own FUN_00767E70, which frees the node and NULLs the
slot by pointer comparison without ever dereferencing the dead target,
then delegates to the stock GetPoint.

Delete rather than NULL the relativeTo. 3.3.5 restructured CFramePoint
as a 16-byte POD with a flags word and invalidates in place (bit 0x800,
gated on by every reader), but the 1.12 node has no flags word, so its
only representation for a dead anchor is the empty slot -- exactly what
FUN_00767E70 produces. A live 0x44C node with relativeTo == 0 is a
state the engine never creates, and the layout readers would fault on
[0 + 0x3C].

Add _classicapi_ArmGetPointCrash to arm the condition deterministically
(decommitted page / low address / null relativeTo). No pure-Lua path
can produce it -- CreateFrame frames are never freed on this client.

Scope: covers the GetPoint reader only. The layout readers GetWidth and
GetHeight (0x007A2FB8) deref the same field unguarded, and nothing here
addresses whatever leaves the pointer dangling in the first place.
2026-09-14 21:37:43 -05:00
Brues a2d7d4e9e6 feat(classes): add C_ClassColor.GetClassColor
Returns a class's color as a ColorMixin, nil for anything that is not a
class name.

There is no engine source for the colors on this client: ChrClasses.dbc
has 17 columns and none of them is a color, and the binary carries no
class-color table (searched it for the class float triples and for the
hex strings, no hits). RAID_CLASS_COLORS is what the client actually
has -- FrameXML builds it in Fonts.xml, Util/Color*.lua gives it the
mixin, and every UI colors classes from it -- so the function reads
that table instead of carrying a second copy of the nine colors. Same
call C_UnitAuras.GetAuraDispelTypeColor makes with the
DEBUFF_TYPE_*_COLOR globals: one source of truth, one shared object per
class, and a class another addon recolors stays recolored here.

The lookup runs metamethods, so the pfUI shim in Util/AddOnCompat.lua
keeps answering grey for unknown keys.

Verified in-game: "WARRIOR" returns 0.78/0.61/0.43 with hex, colorStr
and the mixin methods; an unknown name returns nil; the result is
identical to GetClassColorObj for the same class.
2026-09-14 13:12:25 -05:00
Brues 449841b4eb fix(debugtools): draw the title bars above the backdrop, fit the scroll bar
The Backdrop of each frame draws its background and border into the
BACKGROUND layer, and it is applied after the textures declared in the
XML, so a title bar in that layer ends up underneath it. On
ScriptErrorsFrame, whose backdrop is the 32px dialog border, the header
came out behind the window edge; on EventTraceFrame and
TableInspectorFrame the bar is a translucent one inside the frame, so it
was buried rather than misplaced. Every Blizzard frame that uses
UI-DialogBox-Header puts it in ARTWORK. The title text of all three is in
OVERLAY and still reads over the top.

ScriptErrorsFrame is also the only frame here that takes its scroll bar
from UIPanelScrollFrameTemplate, which hangs the bar off the right edge
of the scroll frame rather than inside it, so the bar ran past the
border. Narrow the scroll frame, and its child edit box with it, to end
where the Close button does. Blizzard's own measurements do not carry
over: its ScriptErrorsFrame inherits UIPanelDialogTemplate, a thin
GearManager border, not this backdrop. The other two frames place their
sliders by hand and already sat inside.
2026-09-14 01:56:48 -05:00
Brues 89c705b922 docs: describe the four macro commands added today
Covers /castsequence, /castrandom, /userandom and /stopmacro in the Lua
reference, plus StopMacro beside GetMacroSpell, and updates the README
groups and counts.

Two caveats are worth having written down rather than found: a list names
no single action, so the random commands give the action button nothing
to show, and being static lines they end the #showtooltip collection --
a /castrandom above a /cast takes the icon from it.
2026-09-14 01:38:13 -05:00
Brues bf79ee1d93 feat(macro): add /stopmacro
Stops the rest of the macro body, split the way 3.3.5 splits it: the
command is addon Lua, and the flag belongs to the body runner, which is
what makes "stop the rest of THIS macro" mean anything.

The runner clears the flag for each body it starts and restores the
previous value when that body ends, so a line that runs another macro
re-enters the runner and the inner /stopmacro ends the inner body only.
A stray StopMacro() outside a macro leaves nothing armed for the next
one. Each line is dispatched synchronously through ChatEdit_SendText
into its handler, so the flag is already set when the fire returns.

The command binds ClassicAPI.StopMacro rather than the bare global.
StopMacro is a plain name in a crowded space, and the global is only
ours until an addon declares one of its own -- after which the command
would set THEIR flag and the macro would keep running with nothing to
show for it. The mirror captured our function at registration.
2026-09-14 01:33:36 -05:00
Brues 4f99a1ed95 feat(macro): add /castsequence, /castrandom and /userandom
Ports the three remaining cast-family commands from FrameXML, including
the macro icon, which is half the feature: a sequence whose button does
not show the current step is barely usable.

The sequence state lives in Lua and the icon asks for it by name. That
is Blizzard's own split -- 3.3.5's macro code calls the Lua global
QueryCastSequence through lua_pcall and takes the item over the spell --
so execution and display read one index and cannot disagree about which
step is current. Macro::ShowTooltip mirrors that call for any option
line that came from a castsequence command.

The random pair is faithful to 3.3.5 rather than nicer than it: the
binary has no query beside QueryCastSequence, so a comma list reaches
the resolver whole, names nothing, and greys the button. Being a static
line it also ends the collection, so a /castrandom above a /cast takes
the icon. #showtooltip gives one of these macros an icon.

QueryCastSequence stops answering if the contested-command pass hands
/castsequence to another macro addon: our table only advances while our
handler runs, so a frozen step one on a sequence somebody else drives
would be worse than no icon at all.

Three adaptations the 1.12 client forces: item detection uses the
carried-item test, since there is no name to item lookup here; the cast
events carry the spell in different argument positions per event; and
CastSpellByName takes no unit, so a targeted step routes through
C_Spell.CastAtUnit like /cast already does. /cast, /use and both random
commands now share one action dispatch instead of four copies of it.
2026-09-14 01:21:12 -05:00
Brues 298eff528c fix(quest): fire QUEST_ACCEPTED from the engine's own accept gate
The client announces "Quest accepted" from a per-quest-slot descriptor
observer, while the quest log is rebuilt from a separate one. Slot 0's
announcer shares a descriptor anchor with the rebuild node and is
registered first, so accepting into an empty quest log announced a
quest no quest-log API could see yet.

Rebuild the log at the top of the observer, as 3.3.5 does, and source
QUEST_ACCEPTED / QUEST_REMOVED from the engine's own per-slot gates
instead of a log diff. That drops the set-diff login heuristic, catches
the re-announce when a quest goes complete to incomplete, and makes the
message precede the event on every path. A cold quest cache rides the
engine's own callback queue so the deferred announce still comes first.
2026-09-13 23:35:05 -05:00
Brues b8b9da2adb ci(release): mirror releases to the Gitea instance
A Gitea pull mirror replicates commits and tags only. A release is a
database record with its own attachments, so it never crosses: the
mirror's Releases page shows bare tags with nothing to download.

Push them over through Gitea's API instead. The new workflow ensures the
tag is on the mirror (forcing a mirror-sync and waiting if it is not),
then creates the release -- or promotes the bare tag record Gitea's own
sync left behind -- and uploads each asset, replacing one whose size no
longer matches. The files come from the GitHub release rather than a
rebuild, so both hosts serve identical bytes.

`Build` calls it after every release build. Running it from the Actions
UI with a tag redoes one release; with the tag blank it backfills every
release on GitHub. A `release: published` trigger cannot work here --
releases created with the default GITHUB_TOKEN do not start another
workflow -- hence the `needs: build` job.

Endpoints, payload fields and status codes verified against the
instance's own swagger (Gitea 1.26.4).

Needs a MIRROR_TOKEN secret holding a mirror token with `repository`
write. Without it the mirror job fails with that instruction, leaving
the already-published GitHub release untouched.
2026-09-13 21:34:16 -05:00
Brues 40abcabe9d fix(unit): read the creature id from the unit's live entry, not the GUID
UnitCreatureID and C_CreatureInfo.GetCreatureID extracted the template from
GUID bits 24-47. On the (v)mangos family that is the spawn row's FIRST
creature id: Creature::CreateFromProto builds the GUID from creature_id[0]
and applies the rolled template through UpdateEntry -> SetEntry only, and a
respawn re-rolls. Turtle's creature table has up to four ids per row (6,935
of 79,773 rows use more than one), so mobs with different names reported the
same id — every Gordunni ogre from a {5236, 5238, 5239} row read 5236.

New Unit::CreatureID reads the entry the engine keys the creature NAME query
on: the instance block at [[unit+0x08]+0x0C] (FUN_00604600's own read), with
the GUID bits only as the out-of-view fallback for creature GUIDs. The
descriptor's OBJECT_FIELD_ENTRY slot reads 0 for creatures on this client,
as it does for items, so it is documented as unusable. Pet GUIDs pack the pet
number, not a template, so Guid::CreatureEntry now returns 0 for them; pets
in view report their real template from the block.

Verified in-game on Turtle: Gordunni Shaman / Battlemaster / Mage-Lord read
5236 / 5238 / 5239 while all three carry 5236 in the GUID.
2026-09-12 23:47:08 -05:00
Brues 108a91a843 feat(api): describe the API in the code, browse it with /classicapi
docs/API.md is 18.7k lines and its anchors are signature slugs, so editing a
signature breaks the 281 internal and 88 README links into it. Blizzard
solved the same problem by shipping the API as data plus a browser addon,
and warcraft.wiki.gg renders those same tables. One set of descriptors can
feed all three.

Each registration now carries one next to it: typed arguments and returns,
nilability, defaults, and a sentence. Events, enumerations and returned table
shapes are described the same way. No Script_* body changed.

Game.h gains namespace Game::Doc (Field with Req/Opt/Vararg, FieldList,
Function, Method, Structure, Event) and a trailing descriptor argument on all
six Game::Lua::Register* plus Event::Custom::AutoReserve.

api/Documentation.cpp records every registration on the first pass of each
Lua state and seals it, so /reload re-registers but records nothing and the
environment comes from which pass saw the name. Export is lazy: nothing is
materialized until C_APIDocumentation.GetSystem asks for one system, because
eager export would build thousands of tables per reload for a slash command.
_classicapi_UndocumentedAPI lists what still has no descriptor.

AddOns/!!!ClassicAPI/APIDocumentation/ ports Blizzard_APIDocumentation's eight
files. Named /classicapi, not /api: the browser holds only what ClassicAPI
adds, so /api would have implied the whole 1.12 surface. Two deliberate
differences from the retail source, both noted in the file headers: a system
search also matches its namespace, since that is the name people type; and an
undocumented function says so, because an empty signature otherwise reads as
a real one.

LinkUtil gains the SetItemRef to LinkUtil.ProcessLink dispatch. That handler
registry was dead code; a new link type now registers a handler instead of
stacking another SetItemRef override. Also defines assertsafe there, which
was undefined and only mattered once the function went live.

Documented: the C_Spell and C_SpellBook surface, the spell globals, both
spellbook enumerations, the 13 UNIT_SPELLCAST_* events, GameTooltip as the
widget-method example and C_Glue as the glue and mixed-environment example.
66 of 692 function registrations. tools/New-ApiDocSkeletons.ps1 emits
paste-ready skeletons to make the rest of the sweep tractable.

Verified in game: the browser lists, searches, and prints detail; links
render and click through; right-click copies and shift-click dumps.
2026-09-12 23:20:46 -05:00
Brues b4e5f4f2bb feat(spell): fill notInterruptible in UnitCastingInfo / UnitChannelInfo
Mirror the 3.3.5 client's own predicate on 1.12 data instead of pushing a
placeholder false. The value is relative to the local player: the spellbook
is folded into school masks of INTERRUPT_CAST spells and MOD_SILENCE spells
(cached on Player::StatSignal), a cast is not interruptible when its
PreventionType is not SILENCE or when the caster's immunity auras (effect /
state / school / mechanic immunity) strip every mask, and the flag is never
reported while the player knows no interrupt or silence at all.

1.12 differences, each documented in Spell::Interruptible: the vanilla
server's interrupt effect also needs InterruptFlags 0x02 (channels:
ChannelInterruptFlags 0x04), which silence ignores; SMSG_SPELL_START carries
no immunity block, so creature_template interrupt immunity stays invisible;
Feral Charge's interrupt lives on its triggered spell, so the capability walk
follows one TRIGGER_SPELL hop.

Verified in-game: a paladin's Holy Light reads false, flips to true while
Divine Shield is up, and back to false when it drops.

Also centralize SPELL_EFFECT_APPLY_AURA in Offsets.h (was local to Level.cpp).
2026-09-12 22:21:16 -05:00
Brues 390eec4749 docs(nameplate): correct stale frame-identity and token-shift prose
The API.md nameplate prose contradicted the code in two places, and
both were resolved in the code's favor after verifying it.

Frame identity: the prose claimed default engine plates get a fresh
wrapper table per call with unstable identity. UI::FrameObject::Push
has one path for both plate kinds — a registry ref at +0x08 of <= 0
delegates to the engine's ScriptRegister, which builds the wrapper and
writes the ref back, so every later call rawgeti's that same cached
slot. Identity is stable for both kinds and addon-set fields survive.
Dropped the registry/metatable mechanics that only existed to justify
the wrong claim; kept the pooled-frame caveat, restated with its real
reason.

Token stability: the NAME_PLATE_UNIT_ADDED note said "nameplate3" can
resolve elsewhere after a slot "vacates and shifts". AssignSlot never
shifts an entry and removal frees the slot in place. Kept the advice
to store the GUID, fixed the reason: slots are reused, never shifted.

Also fixed the iteration example one code block above the slot rules,
which broke at the first vacant slot and so missed every plate past a
gap in the sparse slot array.
2026-09-12 21:58:03 -05:00
Brues f86893c8ef fix(spell): make IsUsableSpell the engine's own usability verdict
IsUsableSpell hand-rolled five checks (known, alive, off cooldown,
power, reagents) and diverged from IsUsableAction exactly where the
engine does more or less: it never tested stance, so Whirlwind in
Battle Stance reported usable, and it tested cooldown first, so a
0-rage Whirlwind on cooldown reported (nil, nil) instead of (nil, 1).

IsUsableAction reads a per-slot cache that FUN_004E5050 fills by
calling FUN_SPELL_IS_USABLE (0x006E3D60) on a player spell's record,
or by comparing the pet's power against the spell cost for a pet
spell. Run those same two paths live, plus the knowledge gate the
helper lacks. Cooldown is not part of usability: the helper has no
cooldown branch and FrameXML greys and swipes as separate states.
Item::Usable had been calling the helper all along.

A pet-book spell given by ID now takes the pet path instead of
always reporting not usable.

Offsets.h: add VAR_PET_GUID and FUN_PET_ACTIONS_USABLE (verified via
Script_HasPetUI, Script_GetPetActionsUsable and the recompute's pet
branch); replace the FUN_SPELL_IS_USABLE comment with the decompiled
check list.

Fixes #51
2026-09-12 09:12:48 -05:00
Brues d4ac5dc210 fix(slash): only give back a command that is still ours
The contested-command heal cleared any key we added whose command string
another addon also claimed. Both halves of that test read the live table a
frame later, so an addon that takes one of our keys OVER broke it.

SuperCleveRoidMacros registers into our own `CANCELAURA` key: it replaces
the handler with its conditional one and writes `SLASH_CANCELAURA2 =
"/unbuff"` over our alias. The heal then tested `/unbuff` -- a command we
never registered -- and on a hit cleared the key, deleting that addon's
`/cancelaura` rather than handing ours back. `/unbuff` kept working through
its own owner, so the symptom was `/cancelaura` alone falling through to
`ChatEdit_ParseText`'s "Type '/help'" message.

Snapshot the handler and the command strings at file scope, while the table
holds exactly what this file registered, and skip a key whose handler is no
longer ours. Taking a key over is already how an addon wins a command, so
there is nothing left to resolve. The `/petattack` case that motivated the
heal is unchanged: that addon registers a rival key beside ours, our handler
stays in our key, and the contested string is one we registered.

Reported downstream as brues-code/SuperCleveRoidMacros#6.
2026-09-12 08:35:38 -05:00
Brues b0585f5628 feat(sound): add C_Sound.PlayVocalErrorSound and Enum.Vocalerrorsounds
Plays the player character's spoken complaint for an error ("my bags are
full") in their race's and sex's voice.

This one maps exactly rather than approximately: VocalUISounds.dbc's
second column IS the modern Enum.Vocalerrorsounds value, and this build
carries every one of the 68 values (0..67) across 11 races. Verified by
resolving a row's sound ids to their SoundEntries names — row
{9, 0, 1, 1875, 1999, ...} is error 0 for race 1, whose normal sounds are
HumanMale_InventoryFull and HumanFemale_InventoryFull, which also pins
the column layout {id, enum, race, normal[male,female],
pissed[male,female]}.

The row lookup is ours because the engine has none: it loads the table
and never reads it, the only xrefs to its records/count globals being the
loader's own writes. Only the indexing is reimplemented — the same
records[id] walk every other DBC reader here performs — while the play
goes through the engine's by-id player like every other sound.

Race and sex come from the login-time bytes rather than the unit
descriptor, so this resolves from addon-load onward, before the in-world
player object exists.

The "pissed" column is deliberately unused: many of the ids it names
match no SoundEntries row. Combinations with no recording play nothing
and raise nothing, which is data rather than an error.

Verified in game on a Night Elf female: Inventoryfull, Outofammo and
Nomana each played, and GetRecentSoundFiles showed
Sound\Character\NightElf\NightElfFemaleErrorMessages\... — right race and
sex — with varying file suffixes, so the engine's weighted variant pick
is running too.
2026-09-12 08:04:16 -05:00
Brues 6013d8b937 feat(sound): add C_Sound.PlaySoundWithOptions and GetSoundScaledVolume
The table form of PlaySound, and the volume reader that falls out of it.
Four of the params' six fields map onto something real here.

volumeOverride is the one that needed finding. FUN_00458DA0(row, stream,
scale) computes the row's own volume times `scale` and hands it to
FUN_007A5DC0, which stores it on the stream and pushes it to FMOD. The
by-id player already calls that with a scale of 1.0 immediately after
starting a sound, and the setter writes rather than accumulates, so
calling it again with another scale simply replaces the volume — no
touching FMOD directly, and no reimplementing the row's volume rules.
Resolving the row needs FUN_0045CDA0, since the applicator is a method on
it.

GetSoundScaledVolume then comes free: that same setter writes the result
to stream + 0x74, so the field IS the scaled volume. Read only off a
stream still in the engine's live list, because a finished stream's
memory returns to a pool.

soundKitID and runFinishCallback were already supported. uiSoundSubType,
forceNoDuplicates and overridePriority are accepted and ignored, and the
docs say so rather than implying they work.

Params are read with GetTable rather than a raw read, so a table built
from a mixin still resolves.

Verified in game: volumeOverride 0.1 is audibly quiet against 1.0,
runFinishCallback still fires SOUNDKIT_FINISHED through this path, and
GetSoundScaledVolume returned 0.276 for a volumeOverride of 0.4 — the
row's own 0.69 scaled, which is what confirms the multiplier semantics
the docs describe.
2026-09-12 07:46:05 -05:00
Brues 27277b11aa feat(sound): fire SOUNDKIT_FINISHED when an opted-in sound ends
Reports the handle of a finished sound, and only for sounds played with
`runFinishCallback` — the documented contract, and what makes it
affordable: without the opt-in every footstep and UI click would dispatch
a Lua event.

Detected on the world tick, NOT from FMOD's end callback. That callback
(FUN_007A53C0) runs on the STREAMER thread — it opens with
EnterCriticalSection and only moves the stream onto a deferred list — so
firing an event there would call into the Lua VM off the main thread. The
engine reclaims those streams in FUN_007A4B60, from the per-frame sound
update that ends in FSOUND_Update, so noticing completion on the main
thread is what the engine itself does.

A tracked entry keeps the stream's path hash (+0x80, stamped at creation
by FUN_007A51D0) beside the handle. Stream objects come from a pool and
their addresses are reused, so "still in the live list" is not enough on
its own — a later sound can land on the same address and the event would
be deferred to the wrong one. Comparing the hash narrows that to the same
file replaying at the same address, for one extra dword read of a node
already found alive.

C_Sound.PlaySound takes the remaining modern arguments: channel,
forceNoDuplicates and runFinishCallback. forceNoDuplicates is accepted
and ignored — the engine's by-path dedup is bit 0 of a flag word the row
itself supplies, and the by-id player ORs in only bits 1, 2 and 4 from
its arguments, so asking for it would mean bypassing that player and
re-deriving its weighted file pick.

The global PlaySound deliberately does NOT take those: it gains the
SoundKitID form and nothing else, staying as close to the global it
replaces as the extension allows.
2026-09-12 07:40:51 -05:00
Brues ccfdb8309c feat(sound): add C_Sound.PlayItemSound and Enum.ItemSoundType
Plays the noise an item makes when handled, without performing the
action. Almost all of it is the engine's: FUN_00457FF0 takes a sound type
and an ItemDisplayInfo id, walks that row's ItemGroupSounds id at +0x2C,
and plays the SoundEntries id at row + 0x04 + soundType * 4. Those four
columns are in the modern Enum.ItemSoundType order (Pickup, Drop, Use,
Close), which makes this a backport rather than a reconstruction — the
module only turns an item argument into a display id and calls it.

The item argument takes an ItemLocation table and the other forms this
project's item APIs accept (GUID string, itemID, link, carried item
name), through the shared ResolveItemArgOrLocation. Sound type is read
off the stack before resolving, since that resolver drives PackBagSlot
and stomps the stack.

Only Pickup and Drop play on a stock client, and that is the data rather
than a limit of the code: of ItemGroupSounds' 24 rows, the 18 any display
row points at (~29,000 displays) populate columns 1 and 2 only. The six
rows naming a Use sound are unreachable or broken — groups 1 and 2 have
no displays, and the ids they name (273/274/275) match no SoundEntries
row — and the Close column is zero in all 24. Use and Close fall through
the engine's own bounds checks silently, which is why no item can test
them; documented so nobody hunts for one.

The type stays a pass-through that indexes the row rather than selecting
a branch here, so a server filling those columns in gets Use and Close
working with no change on this side.

Sound keys off the item's display, not its itemID, so items that look
alike sound alike — the engine's grouping, and why every item has a sound
without one being recorded per item.

Verified in game: Pickup and Drop play, and differ by material.
2026-09-12 07:21:49 -05:00
Brues be7a8a0dd7 feat(sound): mute sound files, play by SoundKitID, and report what played
Five additions, one hook between them.

MuteSoundFile / UnmuteSoundFile stop a given audio file from playing.
They co-hook FUN_007A5450, the single funnel every sound passes through:
this client links only FMOD's FSOUND_Stream_* API, so even a one-shot UI
click is a stream opened by path, and the six callers of that function
are the whole surface (PlaySoundFile, the SoundEntries player behind
PlaySound and every DBC-driven spell/creature/UI sound, and four
music/ambience paths). A muted path returns NULL, which is the engine's
own "did not play" answer — its pre-play gate FUN_007A66A0 already
returns that at a category's concurrency cap, so every caller handles it
and PlaySoundFile already reports it to Lua as nil. Suppressing the open
rather than muting an opened stream means nothing is decoded for a sound
nobody hears; the only visible difference is PlaySoundFile returning nil
instead of 1 for a muted file.

C_Sound.GetRecentSoundFiles reports the last 64 DISTINCT files played,
newest first, with a timestamp and a muted flag — the other half of
muting, since hearing a sound tells you nothing about which of ~9,800
files it was. Always on: the hook exists for muting anyway, recording is
one bounded copy into a preallocated slot on a call that is about to open
and decompress an archive file, and a switch would have to be armed
before hearing the sound you wanted to identify.

C_Sound.PlaySound plays a SoundKitID and returns willPlay, soundHandle. A
SoundKitID is a SoundEntries row id — the same ids the modern client's
SOUNDKIT constants carry, verified against this build's table (850
igMainMenuOpen, 8959 RaidWarning, 8960 ReadyCheck). The engine has always
played by id internally; the only Lua door was the row's NAME string, so
addons written against SOUNDKIT ids could not play a sound here. The
global PlaySound is therefore widened to a strict superset: a number
plays by id, anything else tail-calls the engine with the stack untouched
so the name form is unchanged. It discriminates on lua_type rather than
lua_isnumber, which would also accept a numeric string and reroute
PlaySound("123") away from the name lookup.

C_Sound.IsPlaying validates a handle by walking the engine's live stream
list rather than dereferencing it, since a stream object is freed when
the sound ends, with a step guard so a corrupt list cannot spin inside a
Lua call. Handles are pooled and reused, which the docs call out.

FUN_0045CE60's ABI came from the disassembly, not the decompile — Ghidra
maps its arguments inconsistently against the call site. Re-registering
the PlaySound global was contention-checked first: no sibling DLL
references Script_PlaySound (UnitXP_SP3's "PlaySound" string is the winmm
PlaySoundW import), and the one addon that reassigns the global does a
temporary swap and restore around its own calls.

Verified in game: play by id and by name, mute and unmute across both
entry points, IsPlaying true while a sound runs, and the recent list
filling from sounds the player never triggered (zone music, quest log,
enter world) — which is what shows the funnel sees everything.
2026-09-12 06:59:37 -05:00
Brues f9167bac06 feat(export): add ExportSoundFiles, and sweep every archive when enumerating
ExportSoundFiles is a sibling of ExportDBCFiles that dumps the MPQ
`Sound\` tree to `BlizzardSound\`, with an optional subpath prefix (the
full tree is ~3.5 GB and the command runs synchronously). All 8803
SoundEntries rows have a `Sound\...` DirectoryBase, so that one root is
the whole corpus.

Writing it exposed a bug in the existing enumeration. FUN_00401470's
`archiveSelector` is not an archive SET, as the old comment assumed — it
is an INDEX into a fixed 10-entry table built by the mount function
FUN_00403740 (model, texture, terrain, wmo, sound, misc, interface,
fonts, speech, dbc). Each call walks the primary patch archives plus
exactly ONE of those ten. We passed 6, copied from the macro-icon
loader, so ExportInterfaceFiles was complete only by coincidence —
interface.MPQ IS selector 6 — while the sound export opened neither
sound.MPQ nor speech.MPQ and silently lost 6,561 of 9,535 indexed files.
EnumAllArchives now sweeps all ten, deduped; ExportInterfaceFiles and
ExportDBCFiles go through it too.

The sound export also unions the archive index with SoundEntries.dbc,
because each source holds files the other lacks: an MPQ resolves a read
by hashing the path, so the index is optional and 299 shipped files are
named by no index at all, while ~300 more (character combat grunts,
doodad audio referenced from model data) appear in no SoundEntries row.
Same shape ExportDBCFiles already uses to union the index with its .text
path-getter scan.

Failed reads and writes are now counted and logged rather than silently
skipped. A path only reaches that point because an index or the sound
table named it, so a failure means the two disagree — which is worth
seeing, and was invisible before: the console line gains "(N skipped)"
and each path goes to Logs\classicapi_debug.log.

Also: no extension filter (the tree is all audio, and the table carries
typo'd names like Kill3.wac a whitelist would drop), and the destination
is BlizzardSound\ rather than Sound\ — the loose-file VFS index resolves
loose files ahead of archives, so exporting into Sound\ would shadow the
MPQs with gigabytes of duplicates re-indexed at every launch.

Verified on the 1.18.1 build across both fixes: 3,184 files with the
original selector, 9,526 once SoundEntries was unioned in, 9,818 with
the full archive sweep, and no zero-byte writes. ExportInterfaceFiles
holds at 340/340 and reports nothing skipped, so neither it nor
ExportDBCFiles was ever affected.

Two residuals on this Turtle build, both logged rather than hidden. The
12 `Sound\Creature\Elekk\*` + 4 `Sound\Creature\ElekkPet\*` reads fail
because SoundEntries names a folder the archive does not use (the files
sit flat in `Sound\Creature\`) — a data inconsistency, not a code fault.
Separately, patch-7's 14 flat `Sound\Creature\Elekk_*.wav` index entries
do not reach disk, and that one is NOT explained: patch-7's listfile is
demonstrably walked (its 4 exclusive interface-code files exported, and
interface has no DBC fallback), yet those entries produced neither a file
nor a logged failure.
2026-09-12 06:31:47 -05:00
Brues 7d82ae8e92 docs: record where hooksecurefunc's unhookable list comes from
`kUnhookableNames` is patch 11.0.0's own refusal list, verbatim — the 23
taint-relevant names, not "the Lua base library". Nothing said so, and
with the base-library luaL_reg table (0x00811E28, 36 entries) freshly
catalogued the two looked like they should be one thing. They must not
be: 11.0 leaves tostring / error / loadstring / assert / collectgarbage
hookable and includes secure-family names that are no base function, so
deriving the list from the engine table would move it away from the
client. No earlier client on this machine (3.3.5, 4.3.4, 5.4.8) has the
restriction at all.

Say so in the source comment and the TODO section, and list the names in
the API reference, which documented every other hooksecurefunc error but
this one. Comment-only in the source; no behavior change.
2026-09-12 04:22:14 -05:00
Brues ed7e7628c7 docs: catalogue the Lua base library the batch scan never saw
BlizzardScriptAPI.md and raw_globals.txt were built by walking the 54
FrameScript_RegisterFunction batches, so the Lua standard libraries —
bound by luaL_openlib from luaL_reg tables at state creation — were
missing entirely. That gap read as "1.12 has no debugprofilestart", which
is wrong: the pair is stock since 1.7.0, in the base-library table at
0x00811E28 (36 entries: setglobal … debugstack).

Add the table to both files, with the mechanism (FUN_00703B80 runs the
lib open and the alias snippet at .data 0x008722E8 right before
FUN_LOAD_SCRIPT_FUNCTIONS), the debugprofile pair's clock (rdtsc delta
over a boot-calibrated ticks-per-second, milliseconds as a double), and
the rule this taught: check these tables or /dump the name before
declaring a global absent.
2026-09-12 04:15:44 -05:00
Brues a562573559 perf(table): bisect to a border in the getn heal instead of walking down
The heal's fallback walked down from the stale stored length one rawgeti
per slot — O(stale gap) — and since a length read never writes back, it
did so on EVERY luaL_getn read until the next append re-synced the
length. A table cleared by `pairs` and then polled through getn / concat
/ sort / unpack paid the full walk each time.

The search is now the doubling-then-bisect that luaH_getn uses for 5.1's
`#`, in one shared header (table/Border.h) that both `__len` and the heal
call; the copy that lived in Transpile.cpp is gone. The mark gate is
unchanged in meaning: `n - b == 1` said "slot n-1 is populated", so it is
now that one probe, tested before the registry lookup. For a fully
cleared table and a table stale by one the answer is identical; a stale
table with holes gets some border rather than the highest one, which is
what 5.1 itself returns for that table.

Verified in game: the reserved slot with a hole present (5, "c"), the
stale-by-one recycle (7, 2), the full clear (9, 1), 1,000 getn reads on a
cleared 20,000-slot table with no hitch, and `#` through the shared
search.
2026-09-12 04:05:49 -05:00
Brues 5aa382bbb1 refactor(table): register the marking table.insert instead of hooking it
Table::Length recorded deliberate `table.insert(t, nil)` appends (#36) with
a MinHook on the engine's `luaB_tinsert`. The hook is unnecessary: that
function has exactly one xref — the table-lib luaL_reg entry — so no engine
C code calls it, and every call arrives through one of two Lua values:
`table.insert` (lib open) and the global `tinsert`, which the engine's
embedded compat snippet binds by value (`tinsert = tab.insert`, .data
0x008722E8) from FUN_00703b80 right before FUN_LOAD_SCRIPT_FUNCTIONS
(calls at 0x0048fe97 / 0x0048fe9c; on glue 0x0046a87b / 0x0046a880).

So the marking function is now registered over `table.insert` and calls
`luaB_tinsert` directly, and `tinsert` is re-bound to the same closure by
value through a new `Game::Lua::RegisterGlobalAlias` — the snippet's own
idiom, so `tinsert == table.insert` stays true. Both Lua states get the
pair; the `luaL_getn` heal is unchanged. One MinHook fewer, on a hot Lua
function.

Verified in game: the identity triple (`tinsert == table.insert` and both
`_G.ClassicAPI` mirrors), the #36 reserved slot through both names, the
#39 heal, the positional form, and the error path through the new frame.
2026-09-12 03:49:43 -05:00
Brues d98d3a9fd5 perf(luasyntax): decide with one allocation-free lex before tokenizing a chunk
The load hook gated on raw bytes — memchr for `#`/`%` and three scalar
scans for `...`, `0x` and `[=` — then tokenized the whole chunk, and
RewriteAll threw the token vector away when no operator token existed.
A `%` in a format string or a `...` in prose was enough, so nearly every
addon file and every SavedVariables file paid for a token stream it did
not need: on the dev install, 723 of 1391 addon files (101.6 of 160 MB
on disk) and 39 of 301 SV files (16.7 of 16.9 MB).

The lexer is now `Lex<Sink>`, one body with two sinks. RunPasses runs it
first with `FlagSink`, which records only whether `#`, `%`, `...`, a hex
number or a leveled long bracket occurred outside a string or comment,
and tokenizes only when one did. The byte gates are gone (the flag lex
replaces all five) and RewriteAll takes the flags instead of rescanning
the tokens. A chunk with no real 5.1 syntax costs one pass and no
allocation, and the string/comment skipping stays single-sourced.

Measured in game after the change: 40,921 chunks / 19.1 MB per login,
112 chunks / 2.8 MB tokenized, 39 ms inside the rewrite in total.
`_classicapi_TranspileStats()` exposes those counters.
2026-09-11 21:05:38 -05:00
Brues 3d91ae0f91 feat(macro): show a spell named by ID even when it is not learned
`#showtooltip 1539` resolved its value through the engine's name resolver,
which maps a name -- or an ID through its name -- to a spellbook SLOT. An
unlearned spell has no slot, so the directive matched nothing and the button
greyed with no icon and no tooltip. That constraint is right for `/cast`,
which needs the slot, but an icon and a tooltip need only the spell record.

A value the directive names itself is the author saying what to display, so
it now falls back to `Spell.dbc` when the spellbook has no slot for it. The
button still greys, because the spell still cannot be cast, which is the
honest result: the macro shows what it is about and says you cannot use it.

`spell:N` is accepted as the display counterpart of `item:N`, and skips the
spellbook unconditionally -- nobody writes that form except to name a spell
for display. A bare number skips it only for an explicitly named value; one
lifted off a `/cast` line resolves exactly as far as that cast would, which
keeps the bare form honest about what the macro will actually do. A spell
NAME cannot be rescued either way, since 1.12 has no name-keyed spell index.

The name path still runs first, so a learned spell keeps its real spellbook
resolution including the pet-book flag; the record fallback only sees what
the spellbook rejected, and forces `isPet = 0` there, a pet slot being
exactly what just failed to resolve. The 1..19 inventory-slot rule stays
ahead of it, so `#show 13` is still slot 13 rather than spell 13.

A published value counts as explicit for the same reason a directive's does.
2026-09-11 17:10:51 -05:00
Brues fedccf5b95 fix(macro): give a contested slash command back to whoever owned it
Vanilla has no `/petattack`, so the conditional slash-command registry ADDS
it. SuperCleveRoidMacros ships the same command under its own SlashCmdList
key -- `PETATTACK` where we register `PET_ATTACK` -- and both set a
`SLASH_*` string of "/petattack". Neither ever overwrites the other, so
loading first decides nothing: `ChatEdit_ParseText` walks SlashCmdList with
`pairs` and takes the first match, making the winner hash order.

When ours won, `/petattack [hastarget,alive,harm]` fed that addon's
conditions to `SecureCmdOptionParse`, which does not know `hastarget` or
`alive`, so no clause matched and the line did nothing.

Rejecting a condition we cannot evaluate is right by itself -- retail does
the same -- so the fault is owning the command at all. A command we add and
someone else already binds is handed back. Splitting one command across two
condition parsers would be worse than one owner: the dialects disagree, and
ours deliberately differs from 3.3.5 for an `[@unit]`-only group.

Only added commands are given up. One we replace (`/cast`, `/target`) has no
second entry to lose to, and an addon that wraps ours still chains through
it.

The check runs a frame after load, not at file scope -- this addon loads
first, so nothing is registered to detect yet -- and not on PLAYER_LOGIN,
which has already fired during a `/reload` and would run the check
immediately to the same empty result. The addon load pass is synchronous, so
one frame is enough on both paths. A command registered by a load-on-demand
addon later keeps its own entry, and its coin flip.
2026-09-11 16:50:10 -05:00
Brues 0ba73b8457 fix(macro): leave GetMacroInfo alone and expose the shown icon instead
`Macro::Info` re-registered `GetMacroInfo` to answer with the icon a `?`
macro's `#showtooltip` resolved to, so the Macro UI's list would match the
action button. But the Macro UI seeds its icon selector from that same
return -- `MacroFrame_Update` sets `MacroPopupFrame.selectedIconTexture`
from it, and `MacroPopupFrame_Update` checks the grid button whose name
matches -- so opening the selector on such a macro pre-selected an icon the
player never picked, in the one place that edits the stored icon. Saving was
never at risk (an unclicked selector leaves `selectedIcon` nil and
`EditMacro` then leaves the icon alone), but the display was wrong.

One return cannot serve both readers, and the one that edits state has the
stronger claim, so `GetMacroInfo` goes back to the engine's: it is the read
side of the icon `C_Macro.EditMacro` writes, and every addon that captures
it now gets the stored icon.

The icon a macro SHOWS becomes something a caller asks for, through
`C_Macro.GetMacroIcon`. It reads the macro icon getter this DLL already
hooks, so the `?` rule and the active-icon choice stay in one place and the
answer matches what the action button and the drag cursor get.
Util/MacroIconSelection.lua paints the Macro UI's list buttons from it after
the stock update, which is additive -- an empty slot or a macro with a
chosen icon answers with what stock already drew.

Dropping the re-registration also takes a commonly captured global out of
the override chain.
2026-09-11 16:34:11 -05:00
Brues d9565fbe1f fix(macro): correct macro display on a client that owns the macro tooltip
SuperWoW detours the engine's macro tooltip builder and reimplements
3.3.5's version of it: build the cached spell's tooltip when the macro's
primary-spell field is non-zero, else add the macro's name. We write that
field on purpose -- it is what makes a macro button's icon, cooldown,
range, usable and auto-repeat state correct -- so every display fault here
traced back to what we put in it.

Four things were wrong:

- `MaintainExternal` re-derived "the publisher had a value" from
  `kind != None`, but `Publish` marks a claimed macro `ShowTooltip` either
  way. One tick after `SetMacroDisplay(i, false)` it turned the
  publisher's "nothing matched" (cache 0, button usable) into "named an
  unknown spell" (the grey-out sentinel), and then stuck, because the next
  pass saw the sentinel already in place. The button greyed and the
  tooltip came up empty -- a spell tooltip for -1 builds nothing and skips
  the name. `matched` is stored on the entry now.

- A publisher's claim outlived the publisher. `PrepareForReload` never
  cleared the entries and `Rescan` deliberately never re-reads a claimed
  body, so an addon disabled between reloads left every macro it had ever
  claimed frozen on its last answer. Claims are dropped on reload, each
  one handed back to the engine's own parse first.

- `LookupEntries` scanned all 36 entries for a matching macroID. That is
  not sound: `FUN_MACRO_CREATE` bumps one of two per-scope counters, so a
  general and a per-character macro can share an id, and an entry whose
  slot-map index shifted keeps its old id until the next rescan. Either
  way another macro's resolution could answer. It resolves through the
  slot map now and requires the entry to still agree.

- `#show` is icon-only, but the tooltip is not ours to delegate on this
  client: the field we fill for the icon is the same one the detoured
  builder reads, and it cannot carry the distinction. `#show` builds the
  macro's name through `Script_SetText`, which runs the identical
  sequence. `Publish` takes the kind from the body for the same reason, so
  a claim can no longer promote `#show` to `#showtooltip`.

Also: a resolved spellID with no Spell.dbc row goes back to the engine
rather than rendering an empty frame, matching the fallback 3.3.5's own
macro tooltip ends with; and a conditional directive keeps its tooltip
refreshing while hovered, which is 3.3.5's `dynamic | built` return.
2026-09-11 16:03:27 -05:00
Brues 61db68dd7f fix(lua): gate frame-method self with the engine's own type check
Every engine frame method validates its `self` in three steps before
touching it: lua_type == table, resolve to the CFrameScriptObject, then
the IsA(typeId) vmethod at vtable+0x10. We did the first two and skipped
the third, so ResolveObject handed back a pointer for ANY frame and the
method cast it to whatever type it expected.

That was reachable from plain Lua, not just through a mirror or a hook.
The per-type method dispatcher is an __index handler that rawgeti's the
method closure out of the Lua registry, so frame methods are ordinary
first-class values, and

    GameTooltip.SetSpellByID(ShapeshiftButton1, 133)

reached the tooltip builder with a Button, writing tooltip fields through
Button memory. The engine refuses that same call with "Wrong object type
for member function".

Game::Lua::ResolveTypedObject runs the engine's prologue and raises the
engine's own three error strings, read from .data rather than reinvented.
FrameScriptTypeId mirrors the lazy id assignment, so a check is valid
before any stock method of the type has run. Seven per-type wrappers stop
a call site pairing a method with the wrong class's id, and
ResolveTypedObjectAny covers a method that more than one type reaches.

45 call sites across 19 files now gate self. model/DisplayInfo.cpp had
already worked this out for Model alone and loses its private copy.

Type ids are per CLASS, one shared by all of that class's methods. Each
was read from the prologue of a method that can only belong to its class:
a base-class method registered into several tables carries the BASE id, so
sampling GetObjectType or GetDrawLayer would have produced a gate that
accepts unrelated types. Frame comes from Script_RegisterEvent and Texture
from Script_SetDesaturated, both cross-checked against the first entry of
their table.

Deliberately left ungated: the binding `owner` in bindings/Api.cpp and the
three co-hook sites in texture/Atlas.cpp. Each only uses the pointer as an
identity key and never casts it, so a gate would tighten the contract for
no safety gain -- and raising inside a co-hook would fire before the
original ran.

Verified in-game: the Button-as-tooltip call now raises the engine's
error; a Button still reaches a Frame-registry method
(button:SetAttribute round-trips), so IsA does accept derived types; and
fontstring:GetRotation() still answers -- that reader is registered on
both the Texture and FontString registries and needs the id pair rather
than the Texture id alone.
2026-09-11 14:12:40 -05:00
Brues f895d38f76 refactor(time): drop C_DateAndTime.GetServerTime for the ClassicAPI mirror
The alias existed because FrameXML takes the GetServerTime global on
some clients, and an addon needs some reachable name for the epoch.
ClassicAPI.GetServerTime now is that name, so the hand-made one is
redundant surface.

Docs now point the GetServerTime caveat at the mirror.
2026-09-11 12:37:38 -05:00
Brues 804ed61c76 feat(lua): mirror every registration under a ClassicAPI namespace
Registering a Lua name is not the same as owning it. The engine's
registrars write _G, FrameXML and every addon load after that, and
whoever writes last wins with no error and no way for the loser to
notice. GetServerTime is the case on record: a client whose GameTime.lua
declares its own replaced ours on every login, and no addon could reach
the C function again.

Every name RegisterGlobalFunction, RegisterGlueFunction and
RegisterTableFunction bind is now also bound under _G.ClassicAPI, which
nothing else writes -- ClassicAPI.GetServerTime,
ClassicAPI.C_Item.IsBound, namespaces kept as subtables. All three
registrars are single chokepoints, so this is one helper covering 637
in-game registrations plus 26 glue ones, and anything added later needs
no extra call.

Two properties, both of which depend on doing this in the registrar
rather than from addon Lua:

  - It runs at registration, so the mirror captures OUR function. A
    Lua-side `ClassicAPI.X = X` in the embedded addon would run after
    FrameXML and faithfully copy the clobbered version.
  - It mirrors by VALUE, reading the name back rather than making a
    second closure over the same C function. So `ClassicAPI.X == X`
    holds until something replaces the global, and the pair doubles as a
    clobber check:

        if GetServerTime ~= ClassicAPI.GetServerTime then ... end

EnsureSubTable uses raw get/set so a namespace carrying a metatable
cannot divert either side, and MirrorRegistration restores the stack via
an absolute gettop rather than counting pops.

Not covered, and documented as such: frame methods, which live in the
per-frame-type registry rather than _G, and RegisterIntegerEnum values,
where a mirror would be a stale copy rather than a reference.

Verified in-game: ClassicAPI.GetServerTime == GetServerTime is false on
a client whose FrameXML takes that global, while
ClassicAPI.GetTimeCached == GetTimeCached is true.
2026-09-11 12:35:36 -05:00
Brues aacace1645 fix(time): take the server clock from the engine's own time sync
`GetServerTime` had two separate problems.

The global is not ours to keep. Registration happens inside
FUN_LOAD_SCRIPT_FUNCTIONS and FrameXML loads after that, so a client
whose GameTime.lua declares its own `function GetServerTime()` replaces
it on every login and every /reload, and no addon can reach the C
function again. Turtle's version returns (serverHour, serverMinute) --
which is itself just the player's own machine clock, since it only
diverges from date() if the realm answers a TW_TIME broadcast, and
nothing in the public core does. Add C_DateAndTime.GetServerTime: the
same C function under a name FrameXML never touches.

The value was also the wrong clock. It was rebuilt from the broadcast
gametime struct, which carries minute granularity, no timezone, and
whatever per-map time offset the realm folded in before sending. The
engine already has a better source: FUN_004DE430 (quest-log enter-world
setup) sends CMSG_QUERY_TIME unconditionally, and the handler caches
localEpoch - serverEpoch at VAR_SERVER_TIME_DELTA, refreshed hourly. The
reply is a raw time(nullptr), so the skew yields a true UTC epoch with
real seconds, free of both the timezone and the map offset. The sign is
confirmed by the engine's own use of it -- the timed-quest expiry check
in FUN_004DE510 converts a server timestamp into local-clock space by
ADDING the delta.

The two clocks answer different questions, so Time::Server exposes both
and each function takes the one its contract names:

  CurrentEpoch()     the instant  GetServerTime, GetSecondsUntilDailyReset
  RealmClockEpoch()  the display  GetCurrentCalendarTime, GetServerTimeLocal

GetServerTimeLocal is "the epoch offset by the server's timezone", which
RealmClockEpoch already is by construction, so its round-trip through
the *player's* timezone is gone. GetSecondsUntilDailyReset moves the
other way: a realm buckets its day over a raw time(nullptr), so the
boundary is UTC midnight rather than the displayed midnight.

Verified in-game across an Azeroth -> Kalimdor port on two realms, one
on UTC and one on UTC-5. The instant stays continuous (+51 s across the
port, matching real elapsed time) while GetGameTime jumps 12 hours;
GetServerTimeLocal tracks the realm's displayed clock and rolls the date
with it; GetCurrentCalendarTime's hour matches GetGameTime in both zones.

Fixes #50
2026-09-11 12:17:37 -05:00
Brues 4bf2c17e0f docs: repair the broken links in the API reference
Fourteen anchors in docs/API.md pointed at headings that do not exist, so
those links went nowhere. Most are typos in the slug (`doesitemexit`,
`gettaxiroutep`, `afters`) or a slug that was never updated after its
heading gained an argument (`C_Spell.CastAtUnit` picked up
`placeGroundSpell`, `GetItemSubClassInfo` picked up its `C_Item` twin).
`C_QuestLog.GetQuestIDForLogIndex` was written in camel case, which a
heading anchor never is.

`GetMacroInfo` has no entry of its own in this document, so that reference
is now plain text instead of a link to nothing.

Also correct the table-of-contents text for `C_Spell.CastAtUnit`, which
still named the two-argument signature.

Found while checking the anchors this branch touched. A pass over both
documents now reports no broken link, in either direction.
2026-09-11 08:16:45 -05:00
Brues 3191c4dcfc fix(macro): leave a macro alone when its conditions are not ours
A macro written for another macro addon names conditions this parser does
not have. SuperCleveRoidMacros' `[alive]` is one. The `#showtooltip` reader
scans every macro body, so it met that condition and printed
"SecureCmdOptionParse: unknown condition 'alive'" at login, about a macro
that works.

Worse than the noise: a condition we cannot evaluate cannot pass, so its
group fails. A macro with no unconditional fallback clause then matched
nothing, and the reader wrote 0 over the spellID the engine's own parse had
put in the per-macro cache - costing that button its cooldown, range and
usable state.

`SecureCmdOptionParse` now records the keywords it does not own on its
cached parse and returns the first one as a third value. It still names
them, once each, for a caller the player drove. The reader passes the new
`quiet` flag and reads that value instead: on a foreign dialect it resolves
nothing, writes nothing, and stops re-evaluating until the body changes. The
engine's parse stays in the cache, and the addon that owns those conditions
can still claim the macro through `C_Macro.SetMacroDisplay`.

Such an entry also stays out of `dirty`, because a dirty entry nothing
evaluates would keep `HasPendingWork` true and re-run the catch-up on every
reader.

Moving the warn-once bookkeeping from parse time to call time also stops a
quiet scan from consuming the one warning a keyword gets, so a condition the
player later types is still named.

This is not a load-order fault. SuperCleveRoidMacros creates `_G.CleveRoids`
at the top of Init.lua, and that same file sets `ClassicAPIMacroDisplay`,
which lifts our wholesale yield on purpose so it can publish per macro. The
window is between our first tick and its first publish, which it cannot make
until the player object exists.
2026-09-11 08:14:35 -05:00
Brues 373dce8202 ShaguTweaks nil check
Fixes #49
2026-09-11 08:00:51 -05:00
Brues 4c7f1c36d6 docs: cover the macro conditions and #showtooltip in the README
The README said nothing about either, and its Macros section still claimed
the macro work added no Lua functions.

Two rows in Modern client behaviors: the `[conditions]` / `@unit` syntax
across 38 slash commands, and what `#showtooltip` drives on a macro button.
The Macros section now lists the body forms a macro accepts - the
directive, the conditions, the `!Name` prefix, and `#` comment lines, which
no longer reach chat. A new Slash commands section names all 38 commands by
group, and the bundled-addon section mentions that it holds them and
`SecureCmdOptionParse`.

`C_Macro.SetMacroDisplay` and `GetMacroItem` join the Macros row of the
call table, and `IsUnitToken` / `UnitTokenFromName` join the Unit row.

Also add the `## MerchantFrame` heading the README already linked to. The
six `C_MerchantFrame.*` entries sat inside `## Map` with no heading of
their own, so that link went nowhere.
2026-09-10 18:59:10 -05:00
brues-code 36c367a6d6 feat(macro): native #showtooltip, conditional slash commands, and a display API for addons (#48)
* feat(macro): native #showtooltip/#show, conditional /cast and /use

Backport the macro display system to the engine:

- Macro::ShowTooltip resolves `#showtooltip [cond] value` / `#show` (and
  the bare form over the macro's /cast and /use lines, first match wins)
  through the Lua SecureCmdOptionParse on the world tick and writes the
  result into the engine's per-macro spell cache (+0x564/+0x568), which
  every action reader already consumes. Repaints go through the engine's
  own slot-changed notifier. Item targets are cached alongside.
  Re-evaluates on modifier / mouseover / target / combat changes and every
  200 ms otherwise. Yields entirely when SuperCleveRoidMacros is loaded.
- The `?` icon rule is a co-hook on the macro icon getter, so action
  buttons and the drag cursor both show the resolved icon; GetMacroInfo,
  GameTooltip:SetAction, GetActionCooldown, GetActionCount and
  IsConsumableAction are re-registered in front of the engine for macro
  slots with a resolved directive and tail-call it otherwise.
- Macro::RunBody re-implements the engine's body runner so `#` lines
  never reach chat; Macro::Execute skips them too.
- /cast and /use in the embedded addon (3.3.5 handler shape): items
  first, [@unit] via C_Spell.CastAtUnit, 1..19 = inventory slot, other
  numbers stay spellIDs. SecureCmdOptionParse: a group whose only piece
  is @unit passes only while the unit exists (3.3.5 passes it
  unconditionally). C_Item.GetItemCount accepts names. GetMacroItem
  added; GetMacroSpell now reflects the directive.
- Offsets.h: 0x004F0F40 was the macroID -> MacroEntry resolver,
  mislabeled as a spell-state cache; renamed FUN_MACRO_ID_TO_ENTRY, with
  the action-bar / macro-runner constants this needs added and verified.

* feat(unit): add IsUnitToken for token-vs-name dispatch

Vanilla ships each "act on a unit" verb as two Lua entries, one taking a
unit token and one taking a character name, and each errors on the other
kind of input. Conditional slash commands need to accept either, because
SecureCmdOptionParse hands back a token for `/target [@focus]` and a name
for `/target Bob` through the same variable.

IsUnitToken(value) answers which one a string is by calling the engine's
own token resolver inside lua_pcall and reporting whether it returned or
threw. Consulting the resolver rather than matching a token list here
keeps the answer correct for every family it knows, including this
client's native GUID literals and our own focus / nameplateN / markN,
which unit/TokenExtensions.cpp hooks onto the same function. It reports
whether the text names a token, not whether a unit is there, so "target"
with nothing targeted is still true.

    if IsUnitToken(x) then TargetUnit(x) else TargetByName(x) end

Additive on purpose. Merging the pairs into a modern TargetUnit /
AssistUnit / FollowUnit was written and reverted: those names are common
enough for other DLLs and addons to replace that re-registration is
silently last-one-wins, with no error and no trampoline to chain. That
mechanism is only safe for names nobody else contends.

Offsets.h records two findings from decompiling the resolver. The throw
is raised by its callee, not by FUN_RESOLVE_UNIT_TOKEN, which is a thin
wrapper returning 0 on a miss. And this client reaches the error through
a patched fallthrough that first parses a 0x<hex> GUID literal, so GUID
unit tokens resolve natively with no SuperWoW loaded.

* feat(addon): backport the conditional slash commands

Adds 27 commands that take [conditions] through SecureCmdOptionParse,
following the 3.3.5 SecureCmdList handler shapes: targeting
(/targetexact, /cleartarget, /targetlasttarget, /targetlastenemy,
/targetenemy, /targetfriend, /targetenemyplayer, /targetfriendplayer,
/targetparty, /targetraid), casting and state (/stopcasting, /cancelaura,
/cancelform, /dismount), equipment (/equip, /equipslot), action bars
(/changeactionbar, /swapactionbar) and the pet family.

/target, /assist and /follow gain conditions by replacing the FrameXML
handlers, which is the only way to add them. Plain input keeps working:
each routes through IsUnitToken to the engine's token entry or its
by-name entry, where the old handler always went by name.

Three natives have a different shape here than the 3.3.5 handlers assume,
so those bodies are not straight ports. PetAttack takes no target and
always sends the pet at the current target. ChangeActionBarPage takes no
page and only fires ACTIONBAR_PAGE_CHANGED, so CURRENT_ACTIONBAR_PAGE is
set first. Pet autocast is a spellbook-slot toggle with no enable and
disable entries, so a name is resolved against the pet book and on/off
read the state and toggle only on a mismatch. /cancelaura needs no buff
walk, since CancelSpellByName already matches a player buff by name.

Not ported for want of a native: /targetlastfriend, and the /mt and /ma
family, which needs party assignments the client does not have.

Command names come from the locale files, with the localized name taken
from the matching Blizzard GlobalStrings and the English one alongside.
zhCN ships English for all 27. The short aliases retail also carries
(/eq, /tar) are left out, since those collide with addon shorthands.

* fix(macro): resolve item link values in #showtooltip

`#showtooltip` over a `/use item:6948` line showed no icon. The directive
evaluator built its item argument as `{0, 0, value}`, hardcoding the whole
value as a NAME, so the `item:N` and pasted-link forms could never match
and the value fell through to the spell lookup. `/use` itself was fine,
which is why the macro cast the item but the button stayed blank.

The link parsing already existed for the Lua entries. Split it out as
`Item::Arg::ResolveString` and call that instead of hand-building the
argument, so both paths read the forms the same way.

A bare number keeps skipping the item lookup: `ResolveString` reads "6948"
as an itemID, and a bare number that is not an equipment slot has to stay
a spellID per the documented `/cast 5019` rule.

An explicit itemID now also resolves when none is carried, falling back to
the ID after the bag and equipment walk misses. The icon and tooltip come
from the item record, and the tooltip path already handled an unheld item
through a hyperlink, so a macro naming an item in the bank or one written
before looting it now displays. Names are still limited to what you hold,
since 1.12 has no name-keyed item cache.

* fix(macro): make [@cursor] work in /cast, /use and #showtooltip

`/use [@cursor] item:4390` did nothing and its `#showtooltip` showed the
question mark. Two causes, both in the addon.

The parser rejected the clause. A group whose only piece is `@unit` passes
only while that unit exists, and the existence test ran UnitExists on
`cursor`, which is not a unit token. The engine raises there, the pcall
caught it, and the group failed. `none` was already exempt; `cursor` joins
it, since both name something other than a unit and neither can be tested
that way.

Nothing routed the target once it did pass. `SecureCmdUseItem` sent every
target through UseItemByName, which takes a unit GUID, and the spell branch
had only the on-unit and default cases. A `cursor` target now goes to
C_Item.UseAtCursor and C_Spell.CastAtCursor, which were written as the
`[@cursor]` analogs but had no caller. SecureCmdItemParse has already
turned a bag or inventory slot into a link, so one item call covers every
value form.

`#showtooltip` needed no change: the value resolves once the clause passes.

* feat(macro): accept a character name as a macro target

`/cast [target=Feral] Rejuvenation` did nothing. A `@unit` or `target=unit`
piece takes a character name as well as a unit token, but nothing here
turned a name into something the unit functions accept, and the existence
gate ran UnitExists on it, which raises for a string that names no token.

`UnitTokenFromName(name [, exactMatch])` runs the engine's own by-name
search — `FUN_UNIT_FIND_BY_NAME`, the one behind TargetByName, AssistByName
and FollowByName — and reports the winner as a token: a standard one when
it fits, else the GUID literal, which this client's resolver takes too. It
walks party, then raid, then every loaded unit, so it reaches units no
token names. Prefix match by default, nearest first, like TargetByName.

`GroupPasses` now resolves a named target once and uses it for both jobs:
the bare-group existence test (`[@Feral][] Spell` falls through when they
are not around) and the conditions, which previously raised on a name.
The pcall that already guarded the existence test is what tells a token
from a name, so a token target costs no more than before.

The slash handlers resolve the target the same way before handing it to
CastAtUnit, UseItemByName, FocusUnit or StartAttack, and drop the command
when a named unit is not around.

* feat(macro): drop a ground-target item at your feet with [@player]

`/use [@player] item:4390` sent the grenade through UseItemByName, which
passes a target GUID but never commits the placement, so the reticle came
up instead of the grenade landing. Route a `player` target to
`C_Item.UseAtUnit` instead, which commits at the unit's position.

Only your own position is offered. Aiming a ground-target item at another
unit is not something the game lets you do by hand, so the slash handler
does not either; every other unit target keeps going to UseItemByName.

`C_Item.UseAtUnit` now dispatches with the unit's GUID rather than a zero
target, matching `C_Spell.CastAtUnit`. Without that, routing `@player`
through it would have cost a non-ground item its target: a bandage or a
scroll would fire at the current selection instead of at you. It now
covers both kinds of on-use item, the way CastAtUnit covers both kinds of
spell.

* fix(macro): stop /cast [@unit] aiming ground spells at that unit

The same aim the item side was just denied: `/cast [@target] Flamestrike`
dropped the reticle on the target with no click, for any unit. Placing a
ground spell somewhere you could not put it by hand is aim the player has
not earned, and it should not differ between a spell and a grenade.

`/cast [@player]` and `/cast [@cursor]` still place, since both name a
position you can already aim at. Every other unit still has the spell cast
on it when it takes a unit target, which is what `@unit` is for; only the
ground-placement leg is dropped, leaving the reticle up exactly as casting
by hand does.

`C_Spell.CastAtUnit` keeps the whole primitive and gains a third argument
for the choice, defaulting to placing so the API and its callers are
unchanged. The restriction lives in the slash handler, the same split the
item side uses, where `C_Item.UseAtUnit` stays unrestricted and only
`/use` limits itself to `@player`.

`Spell::AtCursor::GroundPlacementPending` reports whether the in-flight
placement is a ground one, so the handler can leave that reticle up while
still cancelling a placement for a unit the engine did not accept. Leaving
that armed would strand the cursor.

* fix(item): stop a bad unit raising out of C_Item.UseItemByName

The optional `unit` went straight to the engine's token resolver, which
raises for a string that names no token. Both the code comment and the
API docs promised the opposite, that an unrecognized string is no target,
matching the no-op contract the item argument already has.

It is reachable without an addon calling the function directly: secure
button attributes and key bindings both feed it a configured string, so a
`unit="foo"` attribute raised inside a click handler.

Probe with Unit::TokenResolve::IsUnitToken first and treat anything else
as no target, which makes the documented contract true.

C_Item.UseAtUnit keeps raising, which is deliberate and now stated in its
docs: it is the companion of C_Spell.CastAtUnit, which documents the same
behavior as matching UnitHealth("garbage").

* feat(macro): let an addon publish its own macro display

`C_Macro.SetMacroDisplay(macroSlot, value)` hands a macro's resolution to
the display path, for an addon that parses macros itself. It is aimed at
SuperCleveRoidMacros, which today replaces ten action globals plus
GameTooltip.SetAction to put its answers on the bar, and borrows an
unrelated action slot to get a range check for a macro.

None of that is needed. Writing the spell into the engine's own per-macro
cache is what makes cooldown, range, usable, current and auto-repeat
correct for a macro button, with nothing overridden, and the icon then
reaches two places a Lua override cannot: the cursor while a macro is
dragged, and the macro window grid, both of which come from an engine
getter we hook.

The value takes the forms a `#showtooltip` value takes, so a publisher
hands over what it would have written in the macro. Three states: a value
to show, false for claimed-but-nothing-matched, nil to release.

Ownership is per macro. A published one is not parsed or re-evaluated by
us and is honored even while yielding; the rest stay ours. Nothing is
re-evaluated for the publisher, but a published resolution is re-applied
whenever the engine's re-parse overwrites the cache, so a macro edit
cannot silently replace it.

The wholesale stand-down when SuperCleveRoidMacros is loaded is lifted by
`CleveRoids.ClassicAPIMacroDisplay`, which a build sets to say it drives
us. Forks without it keep the all-or-nothing yield, so an older one cannot
end up fighting for the same buttons.

* fix(macro): accept the !Name prefix in /cast and #showtooltip

`#showtooltip` over `/cast !Shoot` showed nothing and the line cast
nothing: the `!` prefix, which asks for a toggle ability to be started
but never turned off, was never part of vanilla and no name resolver
knew it.

Split it in two.

The NAME is normalized in the one co-hook on the engine's single
name -> spellbook-slot resolver, which already owned the numeric
spellID form (so `spell/CastByID.cpp` becomes `spell/NameResolve.cpp`).
`FUN_RESOLVE_SPELL_NAME_TO_BOOK_ID` calls that resolver, so a single
strip covers the runtime cast, `Spell::Arg`, the `#showtooltip`
resolution and the engine's own macro parser -- which is what lets
`IsAutoRepeatAction` light a `/cast !Shoot` button even while macro
display is yielded to SuperCleveRoidMacros.

The BEHAVIOR stays in Lua: `SecureCmdCast` strips the prefix and casts
through the existing `CastSpellNoToggle`, which asks the engine whether
the ability is already up first. `CastSpellByName` cannot carry it --
re-registering that global is off limits and nampower already co-hooks
it.

`CastSpellNoToggle` gains the `placeGroundSpell` argument that
`C_Spell.CastAtUnit` has, so `/cast [@target] !X` keeps the rule that
only your own feet and the cursor place a ground-target spell. It also
tolerates a `!` on its own input now, since its auto-repeat name
compare is ours rather than the engine's.

* feat(item): take an item location wherever an item action takes an item

`C_Item.UseAtCursor`, `UseAtUnit`, `UseItemByName` and `EquipItemByName`
took an item reference only - an itemID, `item:N`, a link, or a name - and
resolved it by searching the bags for the first match. Holding two stacks of
the same item, or two copies enchanted differently, there was no way to say
which one you meant.

They now also take an item location: `{bagID=B, slotIndex=S}`,
`{equipmentSlotIndex=N}`, or an item GUID string - the shapes
`C_Item.GetItemID` already took. A location names one exact item.

`Item::Location::FindItemArgOrLocation` owns the overload; the old `Resolve`
(locations, pointer) and the new `ResolveItemArgOrLocation` (either, pointer)
are wrappers over it, so the classification and the walk live in one place.
None of the four call sites resolves anything itself any more.

A table is only ever a location, and so is a string that parses as a strict
`0x` + 16 hex digit GUID, which no item link or item name can look like. The
form is decided from the argument alone and committed to: a location resolve
STOMPS the Lua stack (`PackBagSlot` overwrites the first slots with its own
arguments), so falling back to the reference forms after one had run would
re-read the argument as whatever it left behind - a bag index read as an
itemID, which names an unrelated item.

`EquipItemByName` needs the source coordinates too, since the swap packet
carries them, which is what the detail form is for. An
`{equipmentSlotIndex=N}` location names a worn item, so with a `dstSlot` it
routes to `Item::Swap::FromPaperdoll` - that is how a ring 11<->12, trinket
13<->14 or weapon 16<->17 move is expressed. Without a `dstSlot` there is no
slot for the engine to pick, so that combination does nothing.

Its `lua_settop(L, 0)` ahead of `ClearCursor` is gone: `Script_ClearCursor`
(`0x004895B0`) is `FUN_00495190(1, 1)` and a return - no arguments, no stack
reads. Dropping it lets the item resolve run after the cursor clear, which a
location needs: while an item is held its slot reads empty, so the location
it came from would otherwise resolve to nothing.

* refactor: centralize the item constants and the icon-path build

Four copies of the ItemStats displayInfoID -> `Interface\Icons\<name>`
chain had accumulated - `item/GetData`, `item/Info`, `container/ItemInfo`
and the new `item/Icon` - and they had already drifted: two checked for an
empty icon name and two did not. `Item::Icon::PathForDisplayInfoID` is now
the one builder and the other three call it, so a change to that chain has
a single site. `PathForItemID` is it plus the cache lookup.

`action/ItemState` had local constants shadowing values already in
`Offsets.h`: `kItemSpellSlots` for `ITEMSTATS_SPELL_SLOT_COUNT`, and a bare
`trigger == 0` for `ITEM_SPELLTRIGGER_ON_USE`. `INVTYPE_AMMO` / `THROWN`
existed in two files, and the engine runner's `0x400` macro line buffer in
two more, so those move to `Offsets.h` as well - `INVTYPE_*` next to the
string table they index, `MACRO_LINE_BUFFER_SIZE` next to the delimiters.

CLAUDE.md's rule, and duplicated offsets drifting is exactly what it was
written for.

* fix(macro): indented directives, release, and icon-getter re-entry

Three defects found reviewing the `#showtooltip` work, plus dead code.

A directive typed with a leading space was lost AND leaked to chat.
`ParseDirective` and the two `#`-line filters all tested byte 0, but the
tokenizer splits on `\r\n` only, so ` #showtooltip` arrives with its space:
the parse missed it, and then `Macro::RunBody` / `Macro::Execute` failed to
recognize the comment and dispatched the line through `EXECUTE_CHAT_LINE` -
the /say this feature exists to stop. All three skip blanks now, as does
`CastCommandArgs` so an indented `/cast` line is still collected, and the
runner dispatches the trimmed line so an indented command works at all.

`C_Macro.SetMacroDisplay(slot, nil)` left the publisher's spell in place.
`Release` cleared our entry and asked for a rescan, but `Rescan` only marks
an entry dirty when it has a directive with options - so for a macro with
no directive of its own, nothing ever rewrote `+0x564`, and the button, its
tooltip, cooldown and auto-repeat state stayed on the published spell until
the engine happened to re-parse. It now hands the field back to the engine
by running the engine's own parser, then repaints.

The macro icon getter could run Lua from under a click. `FUN_MACRO_ICON_PATH`
has two callers and one is `FUN_MACRO_PICKUP`, inside the UseAction core, so
`Lookup`'s catch-up could evaluate conditions through `SecureCmdOptionParse`
and fire `ACTIONBAR_SLOT_CHANGED` into addon handlers while the drag was on
the stack - the re-entrancy hazard CLAUDE.md records for `Tooltip::SetEvents`.
`LookupPassive` reads only what the entries already hold; the world tick
does the work and repaints, so a resolution can be one tick behind an edit.

Also drop `Active()` (no callers) and `RunBody`'s unused trampoline, and
correct the header's reference to a module that does not exist: the icon
comes from `Macro::IconPath`, not `Action::Texture`.

* fix(slash): five conditional-command defects, and cheaper option passes

`/cast 5019` could consume an item. A bare number that is not an
equipment slot is a spellID, but it reached the item lookup, which reads a
number as an itemID - so carrying item 5019 used it instead of casting the
spell. `Macro::ShowTooltip::ResolveValue` already guarded this exact case,
so the button showed the spell while the click used an item.

Every bare `/targetenemy` stepped backwards. The cycling selectors pass
the parsed value as their reverse flag, and a clause that matches with no
value yields the empty string - which is a true boolean in Lua. Six
commands were affected in their most common form.

`/cast [@none] Spell` did nothing. `@none` names no unit, but only
`@cursor` was exempted from the token resolve, so `none` went to the
by-name search and the cast was dropped. It now means no unit, which is
the untargeted form of the verb; `/target [@none]` clears the target, as
documented. The other unit verbs no longer feed `none` to that search
either - it matches on the START of a name, so it would find a Nonek.

`/assist [@target] Bob` ignored Bob. `/target` and `/follow` both let a
trailing name win over an explicit `target=target`; assist did not.

`/use [@player] 0 1` used the wrong item. The position branches ran before
the bag branch, so a named slot was thrown away and the item re-found by
link - the first match anywhere, which with two stacks is the wrong one.
Every form now resolves to one item and goes through one call, which also
means a slot is aimed by `@unit` like a name is, and that `/use` always
uses: clicking a bag slot sells the item at a merchant and repairs it
under the repair cursor (`Script_UseContainerItem` branches on the
merchant GUID and on cursor mode 0x11), which a typed command must not do.

`GroupPasses` also stopped paying for an answer it discards. A group with
conditions only needs a token, so it asks `IsUnitToken` rather than
`pcall(UnitExists)` - the conditions test existence themselves. The
existence path keeps its single pcall, and a name, which costs an
object-manager search, is remembered for the rest of the pass.
2026-09-10 18:43:06 -05:00
Brues fe9e7dddcd fix(color): keep ColorMixin on the standard color globals
An addon that carries a copy of Blizzard's own definition -- a plain
NORMAL_FONT_COLOR = {r=1.0, g=0.82, b=0} and its friends -- assigns it
over ours at file scope, so every addon that loads after it finds a color
with no methods. pfUI's who list then fails on NORMAL_FONT_COLOR:GetRGB()
(brues-code/pfUI#56).

Re-apply the color globals after each addon loads, not only at our own
load, and mix ColorMixin INTO the table that is there instead of replacing
it: the values that addon chose stay, and each reference it already handed
out gets the methods too. ITEM_QUALITY_COLORS entries are repaired on the
same pass. This replaces the SpecialTalentUI special case.

C_UIColor.GetColors() makes a color object for each of its 187 rows, so
the values are kept from the first call and each later pass costs one
lookup per tag. Only a color that is absent or has lost its methods is
touched; a tag holding something else, and a <TAG>_CODE string that is
already set, are left alone.
2026-09-10 16:15:16 -05:00
Brues 9d8f1b1b5d build: pin the project to Win32 with a preset and a configure guard
WoW.exe is x86, so there is no valid 64-bit configure. Nothing in the
repo said so, which let VS Code decide instead: CMake Tools configures on
folder open by default, and with no presets file it takes the
architecture from a scanned kit. Here it chose the x86_amd64 cross kit
(-T host=x86 -A x64) and flipped the shared build directory to x64.

That failure is badly disguised. A 64-bit build first shows up as a
static_assert deep in a struct-layout check, which reads as an unrelated
code fault rather than a build-configuration one.

Add CMakePresets.json with a single win32 configure preset. A presets file
makes CMake Tools use presets and stop using kits, so the architecture
becomes a property of the project instead of whichever kit a machine
happens to select. The preset names no generator, matching the documented
command line: CMake then resolves the newest installed Visual Studio,
which a pinned version would get wrong. Schema version 3 is the earliest
that allows omitting the generator.

Add a CMAKE_SIZEOF_VOID_P guard after project() for whatever gets past
the preset -- a hand-typed -A x64, or a stale cache -- so the configure
fails with the recovery steps instead of building something unloadable.

The existing `cmake -B build -A Win32` flow keeps working; presets are
opt-in on the command line.
2026-09-10 15:23:00 -05:00
Brues 9d1e14410c refactor: share one bounded string copy as Common::BoundedCopy
addons/LoadState.cpp used strncpy, which MSVC deprecates (C4996) and
which does not terminate on truncation, so the call site had to add the
terminator itself. frame/Attributes.cpp had already met that warning and
answered it with a local BoundedCopy helper.

Promote that helper to Common rather than copy it a second time, and
point both files at it. The helper treats a null source as empty, so
LoadState loses its null-name branch as well. Behavior is unchanged:
strncpy(dst, src, kMaxName - 1) plus a manual terminator wrote at most
kMaxName - 1 characters, and so does BoundedCopy(dst, src, kMaxName).

strncpy_s was the other option and is worse here. It invokes the
invalid-parameter handler on truncation unless the caller passes
_TRUNCATE, and LoadState runs inside an engine hook.
2026-09-10 13:36:00 -05:00
Brues 8b06caf708 docs(api): rewrite the EquipmentSet intro for the caller
The paragraph explained the storage choice rather than the API: which
opcode carries set data, that "this server" does not speak it, and that
the file format matches a sibling project. None of that changes what a
caller writes, and "this server" names nothing.

Say what the namespace does, in the section-opener style the rest of the
file uses, and keep the one storage fact a caller acts on -- sets belong
to one character.
2026-09-10 13:30:33 -05:00
Brues 4684088675 docs(api): give GetWeaponEnchantInfo real numbers for both enchant kinds
The example claimed charges = 5 for Brilliant Mana Oil and hid the
enchant ID behind a placeholder. Live dumps of both kinds correct it: the
oil returns charges = 0 with enchant 2629, and Instant Poison returns
charges = 40 with enchant 323. Show each case, so the zero reads as a
property of time-based enchants rather than as the only answer the field
ever gives.
2026-09-10 13:21:43 -05:00
Brues 9a26207df2 feat(item): read a bagged weapon's temporary enchant
C_Item.GetWeaponEnchantInfo covers only the three equipped weapon slots,
so a poisoned or oiled weapon sitting in a bag reported nothing. Add
C_Item.GetItemTempEnchantInfo(itemLocation), returning the same
(hasEnchant, expirationMs, charges, enchantID) tuple for any location the
rest of the C_Item location family accepts.

The temporary-enchant reader already needed nothing but a CGItem, so it
now takes one directly, with a thin wrapper for the paperdoll path. Its
local copy of the slot offset (0x4C) gives way to the block layout
Offsets.h already carried for spell/BonusDamage.cpp, extended with the
within-slot duration and charges deltas and a named temporary-slot index.

Verified in game: a staff carrying Brilliant Mana Oil reports enchant
2629 both equipped and in a bag, and the remaining duration keeps
counting down while the weapon sits there.

Fixes #47
2026-09-10 13:17:56 -05:00
Brues 2adfaff020 docs(api): move the enchant functions into the Item section
C_Item.GetWeaponEnchantInfo and C_Item.GetEnchantInfo were documented
inside the Spell section, sandwiched between C_Spell entries, and
neither appeared in the Contents at all.

Both now sit in Item after C_Item.GetStackCount, kept adjacent since the
second resolves the IDs the first returns, and listed in that section's
Contents block so body and Contents order agree. The headings are
unchanged, so existing links to them still resolve.
2026-09-10 13:00:14 -05:00
Brues 8a7ab490f4 docs(api): move CURSOR_CHANGED in with the other events
It was documented under Cursor while every other standalone event lives
in the Events section, placed there to follow that section's alphabetical
run. The heading text is unchanged, so existing links to
#cursor_changed-event still resolve, and Cursor keeps a pointer to it so
a reader of GetCursorInfo can still find it.
2026-09-10 12:51:58 -05:00
Brues e26f8958e9 fix(compat): let a ClassicAPI-aware addon opt out of its whole shim
pfUI's `handlesHookScript` and ShaguTweaks' `API.classicapi_version` now
return at the top of the compat callback instead of gating one branch
inside it. An addon that advertises ClassicAPI awareness handles its own
color globals, HookScript path and event registrations, so no part of the
shim should run against it. Previously the pfUI flag suppressed only the
CreateFrame shim while the RAID_CLASS_COLORS override and the
UpdateColors no-op still applied, and a ClassicAPI-aware ShaguTweaks
still had its libpredict events unregistered underneath it.

The "brues" X-Website tag now gates the pfUI HookScript shim on its own,
so an unflagged fork carrying that tag behaves as before.
2026-09-10 12:51:58 -05:00
Brues f0a83f1f31 fix(compat): restore Compost:Erase when a 5.1-stubbed copy wins
Compost-2.0 rev 17406 replaces most of its own body with stubs once it
believes it is on Lua 5.1, and our 5.1 syntax backport makes its
loadstring probe pass. Losing GetTable and Reclaim is harmless -- both
are pure recycling hints -- but Erase is not: callers hand it a live
table and expect its keys gone, and the stub takes no parameter at all.
So every call site that clears in place, rather than assigning the
returned table, silently stops clearing.

One addon shipping that revision hands it to every other Ace2 addon,
because AceLibrary arbitrates on the highest $Revision and ignores load
order. Puppeteer is the reported casualty: PTUnit:ClearAuras erases its
debuff-type and aura-ID sets in place, so a dispel type never leaves the
set once applied and a cursed raid member keeps its debuff colour after
the curse is cleaned.

Restore an in-place Erase, picked by behaviour rather than by revision or
addon name so a Compost that already clears is left alone. Checked on
every ADDON_LOADED because AceLibrary can upgrade a library at any point
during load and an upgrade installs the new copy's functions over ours;
the verdict is cached against the function that earned it, so a repeat
check costs two identity comparisons and reuses one probe table.
2026-09-10 11:37:49 -05:00
Brues 5070c892e2 feat(texture): add Texture:SetDesaturation and GetDesaturation
Backports the parametric desaturation methods. The engine desaturates a
region by storing one pixel-shader object in the region's shader slot and
binding it per draw, so an amount is a matter of having more shader
objects: one CGxShader per level (256 levels, framebuffer precision),
created lazily through the engine's own loader under a path that exists
nowhere and filled with hand-encoded ps_2_0 / ps_1_1 bytecode, then
compiled the way the loader does. No draw hooks, no per-region state.

SetDesaturated is re-registered on the Texture registry (the registrar
front-inserts and the dispatcher walks from the front) so all three
methods share one state and `false` clears a partial amount. Every
desaturation path, including SetDesaturated(true), now multiplies the
vertex-colour tint in like retail; the stock shader dropped it.

The first ps_2_0 program was rejected by the D3D9 runtime validator: an
lrp may not write a register it reads as src0 or src2. The shipped
program is the instruction shape fxc emits, and both programs were
validated on a NULLREF device. A build attempted while the device is
lost is not latched, and a level that cannot be built falls back to the
engine's stock shader.
2026-09-09 16:39:14 -05:00
Brues 8295ec9442 docs(api): clarify the multi-flavor TOC section
The intro claimed this client is the Vanilla game type, which read as a
contradiction against the paragraph below it saying `_Vanilla` files are
not used. Both are true: `_Vanilla` as a file suffix names the Classic
Era client, while `vanilla` as a directive value names this client's game
type. Drop the intro sentence, since the [Family] / [Game] table already
states it where a reader can use it, and add a note about the shared word
where the collision is first hit.

Explain why `_Vanilla` and `_Classic` are skipped instead of saying only
that they target an engine this build does not match, and state the
consequence: an addon shipping just `_Vanilla` and `_Mainline` TOCs does
not load at all, so it needs a `_ClassicAPI.toc`.

List both flavor sets in probe order, and give the Bindings half the same
shape as the TOC half.

The `## Interface:` subsection showed a multi-version line and then said
nothing about it. Say that the addon loads when 11200 appears anywhere in
the list.
2026-09-09 13:08:37 -05:00
Brues c5b1431073 feat(cvar): default scriptMemory to 0
Sets the cvar most people already set by hand, so a fresh install does
not meet the interface memory popup. Only the default is overridden: the
write happens when the live value still equals the cvar's registered
value (read from +0x30, so no hardcoded 49152), which leaves a
deliberate Config.wtf choice alone. The archive flag makes the 0 persist,
so the comparison fails on every later boot and the write happens once
per install.

What the cvar gates, since none of it is obvious: FUN_00495590 polls
Lua's live allocation (KB) against it, forces a full GC when over,
and if still over fires MEMORY_EXHAUSTED and starts a 15-second timer,
after which FUN_00401560(0) exits the process. FrameXML shows the event
as the "disable some interface add-ons and restart" popup. The poll is
gated on `limit > 0`, so 0 disables it, and nothing else caps Lua memory
(lmemPool's allocator is six size classes falling through to the Storm
heap, with no ceiling of its own).

Timing is load-bearing: scriptMemory is writable on the glue state and
read-only in the world, where the innermost setter's `if (flags & 4)
return;` makes any write a silent no-op. The glue registration is what
makes this land; the in-game one stays as a second chance. Verified by
deleting the Config.wtf line, launching, and finding 0 in the AddOns
dialog and back in Config.wtf on exit.

Adds CVar::Factory::GetDefaultString for the comparison.
2026-09-09 12:17:33 -05:00
Brues b39c16578b feat(addon): add the /startattack and /stopattack slash commands
Blizzard ships both in FrameXML's ChatFrame.lua; the handlers here are
3.3.5a's verbatim, routed to ClassicAPI's StartAttack / StopAttack.
Every locale file gets the client's own command names, taken from the
per-locale GlobalStrings dumps: /angriffstart, /empezarataque,
/lanceattaque, /начатьатаку, /開始攻擊 and their stop counterparts, next
to the English names. Gives users a clean /startattack without the
macro-addon trick of placing the Attack spell on an action slot to read
its state.

Refs #46
2026-09-09 00:49:26 -05:00
Brues 7d7e392924 fix(spellbook): flag talent ranks by name when the next-rank link is missing
SkillLineAbility's next-rank column is empty for whole chains — every
Mind Flay rank (15407, 17311..17314, 18807) holds 0 — and the engine's
own rank-chain walk (FUN_SPELL_RANK_CHAIN_KNOWN) reads that same field,
so IsClassTalentSpellBookItem flagged only Mind Flay rank 1. Fall back
to the engine's other notion of a rank set: a spellbook spell that
shares a talent rank spell's localized name, the same rule a name-cast
uses to pick the highest rank.
2026-09-09 00:14:23 -05:00
Brues 14fa610bc8 feat(spellbook): add the skill-line, cast-count, and loss-of-control surface
Nine C_SpellBook functions, two C_Spell functions, and one event, all
backed by engine data the stock Lua surface never exposed:

- LEARNED_SPELL_IN_SKILL_LINE(spellID, skillLineIndex, isGuildPerkSpell),
  fired from the learn-spell hook under the engine's own
  LEARNED_SPELL_IN_TAB gate (notified AND appended to the book). The
  learn/unlearn co-hooks move from spell/Info.cpp to spell/Learn.cpp.
- GetNumSpellBookSkillLines / GetSpellBookSkillLineInfo /
  GetSpellBookItemSkillLineIndex / GetSkillLineIndexByID, reading the
  engine's tab array ({skillLineID, numSpells} entries at 0x00B71160).
  The info table calls the engine's own Script_GetSpellTabInfo for the
  name and icon.
- C_Spell.GetSpellCastCount / GetSpellBookItemCastCount: the minimum
  over reagent slots of floor(carried / required), where carried is
  equipped + bags 0..4. GetActionCount / IsConsumableAction are
  item-only in this client, so the count is computed, not mirrored.
- C_Spell.GetSpellLossOfControlCooldown /
  GetSpellBookItemLossOfControlCooldownInfo / ...Duration: the
  C_LossOfControl effect that blocks a given spell, shaped as a
  cooldown. Silence and pacify gate on Spell.dbc PreventionType
  (+0x294, verified against six known spells).
- IsClassTalentSpellBookItem: Talent.dbc rank spells plus trained
  higher ranks via SkillLineAbility's next-rank link (+0x20, verified
  on Mortal Strike). Talent::SpellSet now owns the talent spell set
  that GetCurrentLevelSpells already used.
- ContainsAnyDisenchantSpell: any known spell with effect 99.

Shared helpers added along the way: Spell::Lookup::SpellBankArgToBookType
and SpellbookItemArgsToID, Spell::Cooldown::Query, and
LossOfControl::LockoutForSpell.
2026-09-09 00:10:52 -05:00
Brues 8ca415e9a0 feat(spellbook): add C_SpellBook.GetPlayerSpellsByAura
Every spell the player currently knows with an effect applying the given
aura, as a 1-based ascending array of spell IDs. This is IsPlayerSpell
turned around: it walks the same known-spell bitmap and reports the set
bits whose Spell.dbc record carries the aura, so only a set bit ever
touches a record -- a few hundred lookups, not the ~28,000-row table.

It replaces a C_Spell.GetSpellsByAura that scanned the whole table and
was never committed. That answered "which spells anywhere apply this
aura", when the caller summing aura amounts is asking "which of MY
spells do" -- and the bitmap is that set. It also holds only a talent's
current rank, so a sum over the result never double-counts ranks.

Known is not active. A passive is in effect while known and never shows
in the buff list; a castable buff in the result is merely learned; a
buff another player put on us is not in the bitmap at all. Callers split
on C_Spell.IsSpellPassive and check the buff list for the rest. auraName
0 (no aura) and negatives return the empty array, as does pre-login.

Lives beside PlayerKnowsSpell in spell/Info.cpp rather than in a new
file, so the bitmap read is not copied an eighth time.

Verified in-game. Rogue: aura 217 -> {52508}, rank 2 only. Priest: aura
134 -> {14777, 45553} -- Meditation rank 3 only, plus Improved
Shadowform, a source no one had listed and the data surfaced on its
own. Each class returns empty for the other's aura.

Motivated by pfUI's energytick module: its energy-tick interval needed
the SPELL_AURA_MOD_ENERGY_REGEN_TIME amount, which it had as constants
derived from two hardcoded spell IDs. With this and GetSpellEffectInfo it
names no spell at all.
2026-09-08 23:04:26 -05:00
Brues becf2f4866 feat(spell): add C_Spell.GetSpellEffectInfo
Returns one table per spell effect holding that effect's raw Spell.dbc
fields: effect, auraName, basePoints, baseDice, dieSides, pointsPerLevel,
dicePerLevel, miscValue. Three entries always, an unused slot all zeros.

Deliberately raw rather than one computed magnitude per effect. The
engine's figure also folds in a die roll the client cannot reproduce,
combo points against the combo target, the caster's spell mods, and a
level rescale for flagged spells -- a number carrying none of those while
looking authoritative is worse than the inputs. The docs carry the
formula and say that dieSides > 1 means the magnitude is rolled.

Three new offsets. DieSides was already established by the
EFFECT_BASE_DICE note, which records the verified column run as
Effect@61, DieSides@64, BaseDice@67, BasePoints@76 -- it just had no
named constant. The two per-level fields extend the same run at columns
70 and 73, and both are FLOAT, not int: field 73 on spells
10/17/43/91/122 decodes as 0.1/0.8/1.0/-1.0/0.5 as float and as garbage
as int32.

Verified in-game against answers known independently of the code:
Power Word: Fortitude rank 1 reports auraName 29, basePoints 2,
baseDice 1 and miscValue 2 (STAT_STAMINA), i.e. the +3 Stamina on its
tooltip; Blizzard rank 1 reports effect 27 / auraName 3 with
pointsPerLevel 0.1 (float32 widened), confirming the float read from
Lua; Blade Rush rank 2 reports auraName 217 with basePoints 11 and
baseDice 1, the 12 the server sums for SPELL_AURA_MOD_ENERGY_REGEN_TIME.

Motivated by that last one: computing a rogue's energy tick interval
needs the aura's amount, and the only alternative from Lua was
hardcoding it or parsing a localized spell description.
2026-09-08 22:02:22 -05:00
Brues 28658c2995 docs(api): move Enum.UICursorType in with the other enums
API.md already groups every Enum.* table in one run under Globals, with
its own block of TOC entries. UICursorType was written into the Cursor
section instead, which split that convention and gave one enum a
top-level spot none of the other seven has.

Moved next to Enum.SpellBookItemType, reformatted to the value-first
table shape the neighbouring sections use, and left the CURSOR_CHANGED
payload pointing at it by link. Also corrects "macro index" to "macro
slot" in that payload list, matching what the argument now carries.
2026-09-08 15:48:44 -05:00
Brues f5cce25d23 feat(cursor): add the CURSOR_CHANGED event
Fires CURSOR_CHANGED(isDefault, newCursorType, oldCursorType,
oldCursorVirtualID) and registers the Enum.UICursorType table its two
type arguments index. Classic Era's Vanilla PaperDollFrame uses this
event for the equip-slot highlight, so ported UI code looks for it.

The trigger is a once-per-frame diff of the cursor globals on
Tick::WorldTick, NOT the engine's CURSOR_UPDATE. That event only has
three fire sites and none announces a non-item pickup: the cursor clear
FUN_00495190 fires for every type but zeroes VAR_CURSOR_TYPE first, so
the read there always says "empty", while FUN_00494b60 and FUN_004950f0
fire after a set only when a GUID or itemID is present. An interceptor
on CURSOR_UPDATE therefore reported item cursors correctly and nothing
else -- money, spells, macros and the two pet cursors were silent. There
is no common choke point on the set side (each type writes
VAR_CURSOR_TYPE in its own path), so a state diff is what covers them
all. CURSOR_UPDATE is left completely untouched.

Info::ReadRaw is the cheap half of the diff -- seven plain global reads,
no object-manager lookup -- so the bag-item itemID resolve only happens
on a frame where something actually changed. The cost of the diff is
that the event lands one frame after the change.

Also fixes a bug this uncovered in the shipped GetCursorInfo:
Script_PickupMacro converts the Lua 1-based index into a macroID via
VAR_MACRO_SLOT_MAP before storing it, so the cursor global holds e.g.
0x01000003, and PushMacroCursor pushed that straight through as the
"macro index". docs/API.md already documented the return as macroIndex,
so the contract was right and the code was wrong. Both paths now convert
through the engine's own reverse scan FUN_MACRO_ID_TO_SLOT, the same
conversion the legacy CreateMacro wrapper does. VAR_CURSOR_MACRO_INDEX
is renamed VAR_CURSOR_MACRO_ID, since the old name invited the mistake.

Verified in-game: item, spell (vanilla and Turtle-range IDs) and macro
cursors all fire with correct old/new types, the repeated CURSOR_UPDATEs
from moving a stack produce no CURSOR_CHANGED, and GetCursorInfo returns
slot 4 for a General macro and 21 for a Character one.

oldCursorVirtualID has no faithful equivalent here -- the modern
client's "virtual ID" is not a concept this client has -- so it carries
the previous content's identifying number and says so in the docs. No
consumer is known to read it; Blizzard's own users treat the event as a
bare notification.
2026-09-08 15:45:37 -05:00
Brues 1306eaf1b8 feat(container): add four C_Container getters
GetContainerFreeSlots(bagID) returns which slots are empty as an array
of slot numbers, beside the existing count. A full bag gives an empty
table and a bag that is not there gives nothing, matching the
MayReturnNothing that Blizzard's own EquipmentManager branches on.

GetContainerItemQuestInfo(bag, slot) returns the {isQuestItem, questID,
isActive} table that draws the two quest markers on a bag button.
questID is the item's m_startQuest, isActive asks Quest::Log, and
isQuestItem is item class 12; questID stays absent rather than 0 because
every caller tests it for truth. An uncached item reports the empty
answer and warms the cache, so the next bag update draws what the first
hover could not. Verified in-game: item 18423 reports questID 7495
"Victory for the Alliance", and a quest-class item that starts nothing
reports isQuestItem with no questID.

GetContainerItemEquipmentSetInfo(bag, slot) returns whether the item
belongs to an equipment set, plus the set names joined with ", ".
Blizzard's own version is documented as non-functional, so there is no
working output to match; the lookup goes through the new
EquipmentSet::Data::SetsContainingItem, which matches on the saved
per-instance GUID. That identifies the one physical item saved into the
set rather than any copy of its itemID, and survives the item being
moved between bags. The reserved GUID_EMPTY / GUID_IGNORED slot markers
are rejected there so they cannot match a caller.

Get/SetBackpackAutosortDisabled and Get/SetBankAutosortDisabled keep the
backpack out of SortBags and the main bank container out of
SortBankBags. Both persist as cvars, like sortBagsRightToLeft. This
mirrors the per-bag BagSlotFlags.DisableAutoSort in Blizzard's generated
docs; the backpack and main bank have no slot to carry that flag, which
is why each gets its own pair.

Dropped as unimplementable rather than shipped inert:
Get/SetInsertItemsLeftToRight (the server picks the destination slot,
stack merges included, so there is no client-side insertion point to
steer) and Get/SetBackpackSellJunkDisabled (nothing sells junk here).
SortBank would be a pure alias, since kBankBags already covers the main
bank container.
2026-09-08 14:08:06 -05:00
Brues 807afc083f refactor(quest): share the quest-log lookup by questID
Four functions in this file walked VAR_QUEST_LOG_ENTRIES looking for a
questID, each re-deriving the stride and the header-row gate. Name that
walk once as Quest::Log::IndexForQuestID and let IsOnQuest,
GetLogIndexForQuestID and GetHeaderIndexForQuest read it, so a fifth
consumer does not become a fifth copy.

GetQuestIDForLogIndex indexes rather than searches, so it keeps its own
read, but its raw 16 / +8 / +0 literals become the named
OFF_QUEST_LOG_ENTRY_* offsets.

No behaviour change.
2026-09-08 14:07:41 -05:00
Brues c26afcc050 feat(baselib): forward trailing arguments through xpcall
Ports Lua 5.2's `xpcall(f, msgh, ...)` shape. This client's xpcall takes only
(f, msgh), and its implementation is explicit about the rest: `lua_settop(L, 2)`
discards any further arguments, then `lua_pcall(L, 0, ...)` calls f with none.
So the argument-forwarding form did not fail loudly -- it called f with nothing,
and a function that read its parameters saw nil. (Not a 5.0-vs-5.1 difference:
both take (f, msgh). Forwarding arrived in 5.2.)

Replacing the base-library function rather than wrapping it in Lua, for the
same two reasons `select` and `unpack` are C in this directory. A Lua wrapper
would allocate a closure AND an `arg` table per call, putting an allocation on
every error-guarded path including per-frame ones; and HookSecureFunc's
kUnhookableNames lists xpcall precisely because shadowing a core primitive with
a Lua closure diverges from what C-side callers see.

lua_pcall wants the callee and its arguments contiguous on top with the handler
at a fixed index, but the incoming order puts the handler between them, so:

  PushValue(2) -> f, msgh, a1..aN, msgh
  Insert(1)    -> msgh, f, msgh, a1..aN
  Remove(3)    -> msgh, f, a1..aN

then PCall(top - 2, MULTRET, errfunc = 1), push the status boolean, Insert(2),
and return GetTop - 1 so the handler drops out of the result set. 5.2 does the
same reshuffle with one lua_rotate, which this Lua has no equivalent of.

Purely additive: a two-argument call forwards zero arguments and is the old
behavior exactly, so the capturing-closure idiom in ExecuteFrameScript and the
plain two-argument call in ItemUtil both keep working untouched.

Verified with 25 assertions across both halves. Backward: exact return counts,
embedded and trailing nil returns keeping their slots, reference identity, the
handler running once and receiving the message, a non-function handler tolerated
on the success path, nil f caught, an erroring handler still yielding false, and
the load-bearing one -- a two-argument call still passing f zero arguments.
Forward: false and embedded/trailing nil arguments surviving, twelve arguments
intact, forwarding composing with multiple returns, arguments still arriving on
the error path, and the two cases that target the shuffle -- the handler not
leaking in as argument 1, and the handler also being passable as an argument.

Two incidental confirmations: C-side lua_error does longjmp (the missing-handler
case is caught by an enclosing pcall), which the notes had flagged as uncertain;
and Lua-level error() still does not unwind, so f runs past it and xpcall
reports success with the handler never consulted.

Closes #45
2026-09-08 13:23:04 -05:00
Brues a124629669 fix(item): warm the cache when an icon lookup misses
The three icon accessors (GetItemIcon, C_Item.GetItemIcon,
C_Item.GetItemIconByID) all funnel through PushIconForItemID, which peeked the
cache and returned nil on a miss without queueing the item. Every sibling
getter -- name, quality, level, sell price, max stack size, inventory type,
family, spell, openable, uniqueness, set, average level -- calls WarmCache
there, so the icon was the only field that could not self-heal: a caller
polling after a miss re-resolved every other field while the icon stayed nil
for the rest of the session, because nothing else ever requested that itemID.

Most visible right after login, where the carried-item prefetch can walk a
bag-slot GUID array that SMSG_UPDATE_OBJECT is still filling and legitimately
not see an item yet -- reported downstream as icons that resolve when the
client loads fast and never when it doesn't. But that window only decided
WHICH items were affected; the permanence was this missing warm, which equally
broke every uncached icon the prefetch never touches -- quest rewards, vendor
and auction listings, links out of chat.

Verified in-game: IsItemDataCachedByID(19019) reports false, and a re-poll two
seconds later returns Interface\Icons\INV_Sword_39. Both calls returned nil
indefinitely before.
2026-09-08 09:28:20 -05:00
Brues be03d45f0c feat(frame): add frame:RegisterUnitEvent, unit-aware IsEventRegistered
Modern ports call frame:RegisterUnitEvent("UNIT_HEALTH", "player") to receive
an event for one unit instead of for every unit. Vanilla has no such method, so
the call errored, and FrameUtil.RegisterFrameForUnitEvents was left out of the
FrameXML backport for the same reason.

The engine already owns registration and dispatch, so this is only a filter.
Chain membership delegates to the engine's own Script_RegisterEvent; the filter
is stored per frame here; the check is one gate on the per-frame OnEvent fire,
where the dispatcher has already set _G.event and calls the arg'd script runner
with the OnEvent slot. Suppressing there also covers HookScript chains and
Frame::ScriptArgs' positional path, both downstream, as retail does.

Semantics follow Blizzard's 5.4.8 implementation, where the filter lives on the
subscriber node and the node's kind is fixed at creation: RegisterEvent over a
filtered registration keeps the filter, RegisterUnitEvent over a plain one stays
plain, RegisterUnitEvent over a filtered one replaces the units, and no usable
unit is a plain RegisterEvent. The filter dies with the node, through co-hooks
on Frame::UnregisterEvent and Frame::UnregisterAllEvents -- the latter also
being the CScriptObject destructor's path, so frame destruction is covered.

Two divergences from 5.4.8, both additive. Unit tokens are kept as strings and
compared case-insensitively, since focus/nameplateN/markN are not in the
engine's canonical token table. And the unit count is not capped: 5.4.8 reads
exactly two units and folds each token index into a byte of one dword, and
retail later filled that dword and documents four, but we have no dword to fill,
so every string argument past the event name is a unit.

The filter applies only when the event's first argument is a string. A
number-first event, or a no-arg event (dispatched through a runner this never
sees), fires as with RegisterEvent -- one rule that holds on every dispatch
path, and one that fails toward an extra event rather than a lost one.

FUN_FRAME_RUN_SCRIPT_WITH_CONTEXT was already hooked by Frame::ClickEvents for
PreClick/PostClick, and MinHook allows only one hook per address -- a second
aborts the entire install. Frame::RunnerHook now owns that hook and fans out to
subscribers claiming disjoint slot addresses; ClickEvents moves onto it with no
behavior change.

Verified in-game: 28 assertions over the branch table above, the
PreClick/OnClick/PostClick bracket still firing in order through the shared
runner, and a capture window in which a filtered frame received only its own
token (20 of 20) while a plain control frame on the same events took 115 fires
across six token spellings.
2026-09-08 00:10:22 -05:00
Brues 66c878d03e fix(nameplate): resolve the plate during NAME_PLATE_UNIT_REMOVED
C_NamePlate.GetNamePlateForUnit and GetNamePlateForGUID both returned nil
inside a NAME_PLATE_UNIT_REMOVED handler. They share PushNamePlateForGUID,
which derived the frame purely from live engine state -- Object::ByGuid(guid)
then unit + 0xE60 -- and the event fires precisely because that binding is
gone, with the unit often already out of the object table.

Retail resolves it there (NamePlateDriverMixin:OnNamePlateRemoved calls
GetNamePlateForUnit), so publish the outgoing (guid, frame) pair for the span
of the dispatch and consult it as the getters' last fallback. Live state still
wins whenever it can answer, so nothing else changes.

Frames are pooled, so the engine can pull one off its freelist and rebind it to
another unit between the tick that last saw it and the tick that notices it is
gone. PlateReassigned checks the current tick's walk for the pointer and
suppresses the fallback in that case, rather than trusting the plate's cached
GUID at +0x4E8, which goes stale across recycling.

Fixes #44
2026-09-07 21:54:21 -05:00
Brues 3ad87eb2f3 feat(container): add C_Container.Get/SetSortBagsRightToLeft
Sets which end of the bags a sort fills from, matching the modern pair.
Backed by a `sortBagsRightToLeft` cvar through CVar::Factory, so it
persists to Config.wtf and GetCVar reads it under the same name retail
uses, rather than resetting every session.

The whole implementation is reversed cell lists. Both placement passes
still fill from the "front" and the "far end"; those ends have simply
swapped which physical slot they mean, so the sorted run and the junk
block flip together and junk stays opposite everything else.

Not adding libbagsort's other option, which flips the category ranking
so junk sorts first. It has no Blizzard counterpart, and it is mostly
redundant with this one: what it is reaching for is which end of the
bags the important items live at, and the fill direction already answers
that by moving the sorted run and the junk block at once.
2026-09-07 20:42:00 -05:00
Brues a9d2ad73f3 feat(container): add C_Container.SortBags and SortBankBags
Two phases, because every item move is a server round trip and the second
phase reads slot contents the first changed. Phase one packs partial
stacks; phase two runs on the next Bag::UpdateDelayed, plans the whole
layout, and fires the swaps as one batch, tracking each item's live
position rather than re-reading a layout it is mutating.

The ordering is ours, since retail computes it in code we cannot read and
its categories have no counterpart here: hearthstone, gear by descending
quality, consumables, reagents, trade goods, quest items, everything else
by quality, junk last and filled from the far end. Then class, subclass,
name, fuller stacks first - a real tuple comparator, so there is no
zero-padding to overflow and no placeholder name to wedge an unnamed item
among real ones. An item whose data has not arrived is pinned in place
with its slot withheld, rather than ranked by guesswork.

Neither phase may touch the Lua stack, since phase two runs from a bag
update callback. Hence Lua-free ContainersFrom / AutoStoreFrom /
MoveCountFrom, with the Lua-taking forms reduced to resolving the source
pointer and delegating, plus a direct invMgr walk instead of ResolveBag.

Five things had to be found the hard way, every one of them the client's
local state disagreeing with the server's:

- Never plan a swap between two stacks of the same item. Player::SwapItem
  tries a MERGE before it considers swapping and returns if that
  succeeds, collapsing two slots into one or redistributing counts and
  leaving both in place. Neither is a swap, so a single collision
  invalidated the bookkeeping for every move after it in the batch. One
  collision in a 55-item bag turned one pass into three.

- Entry marked "unplaced" with destBag = -1, safe while bag IDs were 0..4
  and wrong the moment the main bank joined as bagID -1: every item bound
  for the main bank read as unplaced and had its move dropped, so nothing
  could move into the main bank at all. The sentinel is destSlot now,
  which cannot collide because slots are 1-based.

- FUN_INVENTORY_SWAP's last argument gates a pre-send confirmation check.
  With 0, a Bind-on-Equip item the character could wear is stashed behind
  the bind dialog and NO PACKET IS SENT - silently, since the builder
  returns void. Now passes 1, which is what the engine itself does when
  re-issuing a swap after the dialog is accepted, and is correct here
  because both endpoints are always bag content slots where nothing binds.

- CMSG_AUTOSTORE_BAG_ITEM cannot merge across bags. Its destination byte
  can only be INVENTORY_SLOT_BAG_0 (255) for the player, and server-side
  that is the specific-container branch: keyring and backpack only. The
  search-every-bag path is NULL_BAG (0), which the builder cannot emit.
  Both sets now use one explicit two-pointer merge that addresses both
  endpoints and works everywhere. It costs a packet per transfer rather
  than per emptied source, which is the price of being correct.

- The merge loop must choose split-versus-swap from its own model, not
  the item's live stack count. The batch goes out in one frame with no
  replies, so descriptors still hold pre-batch counts; a move the model
  knew was the last of a stack went out as a split, and the server
  rejects a split that would empty its source.

Consolidation packs fully rather than stopping once a slot is freed: 9
and 2 with a cap of 10 become 10 and 1. It settles in one pass and sends
nothing on the next call, because a packed group has every stack full
except the last, so the first step walks straight to the end.

Bank specifics: ViewForBag gains the main bank (bagID -1, inside the
player's own invMgr) and bank bags (5..10, each with its own), which can
themselves be specialty bags. Bank bags resolve only once the bank window
has been opened, which is the right gate rather than an accident - the
server refuses bank moves without it, so a bank sort with the bank closed
finds no cells and does nothing instead of dispatching a batch that would
be rejected wholesale.

_classicapi_SortBagsStats() and _classicapi_SortBagsBags() report the last
pass and the per-bag view. Both earned their keep: the stats ruled out our
side of the swap divergence by showing a complete plan fully dispatched
with zero local failures, and the per-bag dump ended the sentinel hunt by
eliminating the entire area three successive guesses had been aimed at.
2026-09-07 17:47:05 -05:00
Brues db88fca050 feat(container): add C_Container.AutoStoreItem
Moves an item and lets the server pick the destination slot, which is
worth having because the server does not merely find an empty one: it
first merges the stack into existing stacks of the same item, splitting
it across several when that is what fits, and places a remainder only if
one is left. So one call consolidates a partial stack.

Two engine builders back it, because the wire has two autostore opcodes.
FUN_005E12E0 sends CMSG_AUTOSTORE_BAG_ITEM (0x10B) and takes a
destination container, so it can confine an item to one equipped bag or
let the server search the whole inventory. FUN_005E18F0 sends
CMSG_AUTOSTORE_BANK_ITEM (0x282) and takes no destination at all - the
server derives the direction from the source, so a bank source travels
to the inventory and an inventory source to the bank. AutoStore picks
between them and accepts only the pairs the wire can honestly serve.
Bank-to-bank is not among them, so consolidating stacks within the bank
still needs per-pair moves.

Both builders' stack-arg counts come from their RET, not from a
decompiler parameter list. 0x10B's last slot is never read by the body
but is still popped, and declaring seven args instead of eight made the
callee pop four bytes we never pushed - which shifted the caller's frame
and surfaced as a garbage Lua state pointer in the next function to run,
several frames from the call. Noted at both offsets, since this family
is not uniform in arity.

Three fixes to the shared bagID encoder found while doing it:

- EncodeBagSlot had no case for the keyring (bagID -2), so SwapItems,
  MoveItem and AutoStoreItem all rejected keyring slots. The engine's
  own map in FUN_PACK_BAG_SLOT has had it all along, and the linear base
  was already recorded in the invMgr slot map.
- Its bank constants restated named Offsets::INVMGR_* values, so they
  now derive from them, and the slot map is fully named rather than half
  constants and half comment. Each player-container range is bounded by
  both its own last linear slot and the live invMgr count - stricter
  than before, where the backpack had no upper bound at all.
- FUN_PACK_BAG_SLOT's fourth out-param was labelled outUnused. It is the
  bank flag, and it is what makes right-clicking a bank item send 0x282
  instead of using the item.
2026-09-07 01:38:34 -05:00
Brues 26af9bd30f docs(nameplate): correct two stale claims in the Info.cpp header
The header still described the removed fresh-wrapper-per-call path: that
we deliberately skip FUN_00701BD0 to avoid its refcount bump, and that a
default nameplate's wrapper is rebuilt per call so identity is unstable.
PushNamePlateFrame delegates to UI::FrameObject::Push, which registers
lazily when the refkey is unset, so addon-created and engine-created
plates alike resolve through rawgeti(REGISTRY, frame + 0x08) and identity
is stable across calls.

It also claimed there is no central list of live nameplates. There is:
FUN_00608870 walks the header at {0x00C4D928, 0x00C4D92C}, unlinking the
plate and reinserting it in screen-depth order, and FUN_006086E0 calls it
on every position update. FUN_00608A10 unlinks from that list and pushes
the node onto a free list at {0x00C4D91C, 0x00C4D920}, which FUN_006087F0
pops without reinitializing.

Since that reverses the comment's premise, record why the object hash
table is still the enumeration source: the list is unlinked and
reinserted throughout the render while no nameplate code touches the hash
table, a recycled node keeps a stale GUID at +0x4E8 until FUN_007CB6D0
rebinds it so unit + 0xE60 is the only authoritative binding, and the
hash walk yields the unit, nameplate and instance block together.
2026-09-06 23:52:27 -05:00
Brues e7156caa47 feat(console): add the rest of the console API
Eight functions alongside ConsoleGetAllCommands, completing the surface:
ConsoleExec, ConsoleEcho, ConsolePrintAllMatchingCommands, ConsoleIsActive,
ConsoleGetColorFromType, ConsoleGetFontHeight, SetConsoleKey and
CalculateStringEditDistance.

ConsoleExec is the one with real reach. Nothing in this client's Lua could
run a console command before, so every entry ConsoleGetAllCommands returns
was visible and unreachable at once. It is the engine's own executor --
FUN_0063CE00, which resolves the name and calls the node's +0x18 handler,
the same field the enumeration reports -- and it is what replays each
`SET` line of Config.wtf at boot.

That includes `set`, and `set` is not SetCVar: the console handler uses
the unfiltered lookup and performs no read-only test, while Script_SetCVar
checks flag bit 0x4 first. So ConsoleExec can write a cvar SetCVar refuses
and reach cvars no Lua getter can see. Inherent to exposing the console
rather than introduced here, and documented as such.

The remaining state came out of the console module: FUN_0063C860 toggles
VAR_CONSOLE_VISIBLE when the key matches VAR_CONSOLE_TOGGLE_KEY and the
`-console` switch flag VAR_CONSOLE_ENABLED is set, which gives an honest
ConsoleIsActive; FUN_00638A60 seeds nine ARGB colours whose index is the
second argument to the writer, stored per line at +0x1C; FUN_0063CB00 is a
one-line setter for the toggle key.

There is deliberately no ConsoleSetFontHeight, and the crash that settled
it is recorded at FUN_CONSOLE_FONT_INIT in Offsets.h. Writing the height
global alone does nothing, and the only thing that rebuilds the font has
no code callers at all -- one table entry at 0x0080E170 -- so it runs once
at startup before any console line exists. Its null-check-and-free of the
previous handle reads like re-entrancy and is not: every line holds a
cached font-dependent draw object at +0x20, so re-running it faults on the
NEXT frame inside the texture manager, not in the call. The console's own
shutdown frees the font and those objects together, which is what the
pairing is for. A safe setter would mean replaying that teardown across
every line to change a text size nothing asks to change.

SetConsoleKey takes the client's numeric key code rather than a key name,
because the console stores and compares exactly that and nothing in it
translates names.

Verified in-game with -console: edit distance 3 for kitten/sitting and 2
for help/hepl, red and yellow at types 3 and 4 with nil out of range,
ConsoleIsActive false while closed, and exec output, a yellow echo and a
prefix match for both Export commands all present in the console.
2026-09-06 17:19:49 -05:00
Brues 02ad0ea6ab feat(cvar): add C_CVar.GetCVarBitfield / SetCVarBitfield
Treat a cvar's numeric value as a bitfield and read or write one bit, so a
single cvar carries many independent booleans. Upstream this backs the
record of which tutorial popups a player has dismissed: one cvar, one bit
per popup, persisted by the config machinery for free.

Namespaced only. Blizzard's FrameXML calls the bare globals, but those are
its own wrappers rather than the API, and nothing here needs them.

Both wiki pages are stubs, so the details come from Blizzard's generated
documentation: `index` is typed `luaIndex`, which is what settles that it
is 1-based; the getter's return is nilable; and the setter names its
requirements as a valid and public cvar, a non-read-only one, a
non-secure one, and an index in range. The first two are questions this
client can genuinely answer -- the lookup is the same filtering one behind
C_CVar.DoesCVarExist, so a cvar preserved out of Config.wtf without being
implemented is refused here exactly as by every other Lua cvar function --
and nothing here is ever secure.

The value is parsed and rewritten as a uint64 in C++, never handed through
a Lua number, so all 64 bits are exact and the 1..64 index range is the
arithmetic type's own width rather than a limit chosen here. Writing goes
through CVar::Factory::SetString rather than the engine setter directly:
that wrapper already declares FUN_SET_CVAR_VALUE as the __thiscall it is,
and getting that wrong corrupts the stack silently. It also means a
bitfield write fires the change callback and marks the config dirty,
exactly as SetCVar does.

Verified in-game against a registered cvar: bits 1 and 5 give 17,
clearing bit 1 gives 16 with bit 5 untouched, and bit 64 gives
9223372036854775824 and reads back true -- a value past Lua 5.0's exact
integer range, which is what proves the arithmetic is not round-tripping
through a double. Out-of-range indices read nil, and setting refuses for
an out-of-range index, an unknown cvar, and a read-only one.
2026-09-06 16:55:58 -05:00
Brues 1dee8e5683 feat(cvar): add C_CVar.AreCVarsLoaded
Reports the cvar registry's own initialised state rather than a constant,
so the function states a fact instead of an assumption. VAR_CVAR_HASH_MASK
holds 0xFFFFFFFF until the first registration builds the table, and every
lookup already gates on that sentinel, which makes it the closest thing
this client has to "the cvar system is up".

It can only return true from Lua, and that is worth being plain about.
The config system runs off the boot path -- FUN_0063D380 is reached
straight from the entry point, registers the console commands and replays
Config.wtf -- long before a Lua state exists, so there is no window in
which anything could observe false. The question is real upstream, where
an account's cvars can be stored server-side and arrive after login;
nothing here is fetched over the network, so once boot has run there is
nothing left to wait for.

Kept anyway because ported code that gates on it would otherwise call a
nil, which is the whole reason the function is worth having.

Verified in-game: returns true, as a boolean.
2026-09-06 16:36:58 -05:00
Brues 583f4bb011 feat(cvar): add C_CVar.DoesCVarExist
A ClassicAPI addition -- no such function exists upstream -- named for the
DoesAddOnExist / DoesSpellExist pair already here.

It uses FUN_FIND_CVAR, the same lookup GetCVar and SetCVar go through,
because the question a caller actually has is whether those will work.
That makes the invariant exact:

    C_CVar.DoesCVarExist(name) == (C_CVar.GetCVarInfo(name) ~= nil)

The alternative lookup FUN_0063DE30 skips the bit-31 test and would also
find a cvar preserved out of Config.wtf without the client implementing a
setting by that name. Reporting one of those as existing would mislead
every caller who then tried to read it, since no Lua getter can, so the
filtering lookup is the honest one here.

Returns false rather than raising for a non-string, matching the two
Does*Exist functions it is named after: a predicate should answer.

Verified in-game: true for a real cvar, false for an unimplemented
Config.wtf name, for a console command, for an unknown name, and for nil
and a number. A sweep over every entry ConsoleGetAllCommands returns finds
zero disagreements with GetCVarInfo.
2026-09-06 16:32:38 -05:00
Brues 23ebfbe7ab docs(cvar): record why some cvars are invisible to Lua
Chasing four cvars that ConsoleGetAllCommands reported but GetCVar raised
on turned up the mechanism behind both.

FUN_FIND_CVAR is not a plain by-name lookup. After matching it tests
`if (-1 < (int)flags) return 0` -- the flags read as SIGNED, so it returns
only cvars with bit 31 set. GetCVar, SetCVar and C_CVar.* all go through
it, so a cvar without that bit cannot be reached from Lua at all.
FUN_0063DE30 is the same hash walk without the test.

Bit 31 is set when the registrar's registerConsole argument is 0, and the
config loader FUN_0063D820 runs each `SET` line in Config.wtf as a console
command, whose handler FUN_0063D500 registers an unknown name as a fresh
cvar with registerConsole = 1 and flags 0 -- into which the registrar ORs
the archive bit, so the config writer saves it straight back out.

So any line left in Config.wtf becomes a cvar on the next boot whether or
not the client implements a setting by that name: preserved across
sessions, writable from the console, invisible to Lua. realmlist.wtf runs
through the same path, so a line there materialises in Config.wtf too.

Nothing to fix. C_CVar.GetCVarInfo already uses the filtering lookup, so
it returns nil exactly where GetCVar and SetCVar do and the Lua cvar
surface agrees with itself, while ConsoleGetAllCommands lists these
because the console genuinely can reach them. Both functions were already
right; only the reason was unrecorded.
2026-09-06 16:29:03 -05:00
Brues 18927551d5 feat(cvar): add C_CVar.GetCVarInfo
Returns a cvar's value, its default, and what may be done to it. Two of
the seven returns are real here and five are structurally false, which is
worth stating precisely rather than leaving as unimplemented:

  isReadOnly              REAL, flag bit 0x4. Script_SetCVar tests it
                          before anything else and raises `"%s" is read
                          only`, so this answers in advance whether
                          SetCVar will work. Three cvars carry it on this
                          client: realmList, realmName, scriptMemory.
  isStoredServerAccount   Always false. These describe a cvar the server
  isStoredServerCharacter stores per account or per character, kept in
                          step by the synchronizeConfig cvar. No such
                          mechanism and no flag bit for one exists here,
                          so false is accurate rather than a placeholder.
  isLockedFromUser        Always false. No flag governs it.
  isSecure                Always false. Marks cvars that cannot be set in
                          combat, a protection with no analogue here.

Derived by reading 3.3.5's own GetCVarInfo, which returns the first four:
value and default from the struct, then flag bits 4 and 5 for the two
server-stored booleans. The flag OFFSET transfers -- +0x1C in both -- but
the string offsets do not (3.3.5 keeps them at +0x28 and +0x40), so the
ones used here come from this client's own cvarlist handler, which
compares +0x20 against +0x30 to print "(default: %s)".

Unknown names return nil rather than raising, so a caller can tell "no
such cvar" from "set to empty". FUN_FIND_CVAR searches the cvar registry
alone, so a console COMMAND's name finds nothing and returns nil -- the
contract's "console variables only" for free, with no test needed.

Namespaced only. A bare GetCVarInfo global is nil on a live client, and
C_CVar.GetCVarBool already established the namespace here.

Offsets.h gains OFF_CVAR_DEFAULT_STR and names three flag bits, each from
the code that acts on it: archive (the config writer skips cvars without
it), staged (the setter stores to +0x38 and marks the config dirty
instead of applying), and read only.

Verified in-game: realmList reports its value, its stock default and
isReadOnly true; gxResolution reports 2560x1080 against a 640x480 default
with every boolean false; an unknown name and the console command `help`
both return nil; and a sweep over every cvar finds exactly the three
read-only ones.
2026-09-06 16:15:29 -05:00
Brues 2c2f280c51 feat(console): add ConsoleGetAllCommands
Returns every console command and console variable as ConsoleCommandInfo
tables, backed by the registry FUN_CONSOLE_COMMAND_REGISTER fills. The
walk mirrors the `help` handler (FUN_0063FDC0), the only other thing that
enumerates it: step with next = *(uint32_t *)(node + LINK_OFFSET + 4),
stop on null or a low-bit-tagged sentinel.

Commands and CVars are ONE list, not two. The CVar registrar's last act
is FUN_CONSOLE_COMMAND_REGISTER(cvar->name, 0x0063DDE0, categoryId,
help) -- which is what makes `/console <cvar> <value>` work -- so the
command list already holds every CVar, and walking the CVar list that
`cvarlist` and the config saver use would report each one twice. That
shared handler address is also an exact commandType test: a node pointing
at it is a Cvar, anything else a Command. A pointer comparison against a
value the registrar itself writes, not a name or category heuristic.

Named as a global, not a C_Console member. The wiki files it under
C_Console.GetAllCommands, but on a live 12.1.0 client C_Console is nil
and ConsoleGetAllCommands is the real name -- the page is stale about the
namespace. The field names come from Blizzard's own generated API docs
and were then confirmed against a live entry: command, help, category,
commandType, scriptContents, scriptParameters, with the two script fields
empty strings rather than nil there too.

Enum.ConsoleCategory and Enum.ConsoleCommandType are stated in full
rather than derived from the engine's nine categories. Deriving works --
reading VAR_CONSOLE_CATEGORY_TABLE and capitalizing "debug" to "Debug"
was verified in-game -- but it makes the enum track the wrong thing. It
is a Blizzard contract, not a description of the local console, and it
carries values this client cannot produce: Reveal 9 and None 10 have no
category here, Macro 2 and Script 3 no registration path. A client that
renamed its `gm` category would silently register
Enum.ConsoleCategory.Master and turn Enum.ConsoleCategory.Gm into nil,
breaking a constant meant to be fixed everywhere. Offsets.h keeps the
verification: ids 0..8 are debug, graphics, console, combat, game,
default, net, sound, gm in that order, so a category read off a node
lands inside the enum without translation.

scriptContents and scriptParameters describe console macros and scripts,
which have no registration path here, so both are always "".

Verified in-game: 538 entries, 487 of them CVars. `help` -> Command /
Console with its description, `realmList` -> Cvar / Default, and our own
`ExportDBCFiles` -> Command / Debug, which also proves the walk sees
runtime registrations rather than only boot-time ones. C_Console is
absent, both enums resolve including the values this client cannot
return, and every field has its declared type.
2026-09-06 15:46:30 -05:00
Brues 991baa2610 feat(lua): cap upvalues at Lua 5.1's 60 rather than the byte
The limit shipped at 255, the structural ceiling -- f->nups and
LClosure.nupvalues are lu_byte, so that is the most a closure can hold.
But the point of the change is that a function valid on a 5.1 client
should load here, and 5.1's own MAXUPVALUES is 60. Anything past that is
not a compatibility gap, it is an invitation to write something no other
client would accept, which is not a thing to be first at.

One constant. Nothing in either hook depends on which number it is: the
spill path, the stale-clear and the emission loop are unchanged, and the
refusal still comes from the engine's own luaY_checklimit, so its message
carries whichever limit is in force.

Verified in-game: 60 upvalues load and sum correctly, 61 fails with
"too many upvalues (limit=60)".
2026-09-06 14:16:39 -05:00
Brues e68b690cf1 feat(lua): raise the parser's upvalue limit from 32 to 255
Lua 5.0 refuses the 33rd upvalue of a function with "too many upvalues
(limit=32)", as a syntax error on the whole file. Lua 5.1 allows 60, so a
large handler that reads many file-level locals can be valid on a modern
client and unloadable here -- and it is the one class of 5.1 difference
the source transpiler cannot reach, because the limit sits in the parser.

The limit is not the `PUSH 0x20` immediate in indexupvalue. It is the size
of a fixed array: FuncState carries `expdesc upvalues[32]` at +0x38, and
the next field, actvar[200], begins at +0x2B8 -- exactly 0x38 + 32 * 0x14.
Raising the immediate alone writes the 33rd upvalue over actvar[0], the
stack of locals in scope, and the function compiles wrong without raising.

In 5.0 that array has exactly two readers, both located in the binary:
indexupvalue (FUN_006FDF80), which scans it and appends, and pushclosure
(FUN_006FD980), which walks it after the body to emit one OP_MOVE or
OP_GETUPVAL per entry behind OP_CLOSURE. Everything past the parser is
dynamic -- f->nups and LClosure.nupvalues are bytes, OP_GETUPVAL's B field
is 9 bits, closures are sized per instance, the debug-name array grows on
demand -- so the byte is the ceiling and the array the only obstacle.

Co-hook both readers and keep entries 33+ in side storage keyed by the
FuncState's address. A function within 32 never leaves engine code: both
hooks call the original for it. Only a function the engine would have
rejected takes the reimplemented path, and that path calls the same
helpers the original does -- luaY_checklimit with 255 in place of 32, so
an overflow still raises the engine's own message; luaM_growaux for the
name array; luaK_codeABx / luaK_codeABC for emission. Bytecode and VM are
untouched: a 40-upvalue closure is one 5.0's VM already builds and runs.

Staleness is self-correcting without an open_func hook. A parse error
longjmps out, so side storage keyed by a stack address can outlive its
function and the next chunk may reuse the address. But side entries exist
only while nups > 32 and indexupvalue is the only writer, so a FuncState
arriving there with nups <= 32 cannot own any -- whatever is filed under
its address is cleared on the new function's first upvalue, before
anything could read it.

Compile-time only, so no per-frame cost, and nothing else hooks lparser
internals -- LuaSyntax's transpiler hooks luaL_loadbuffer, a different
function, and the other Octo DLLs do not touch the compiler.

The Proto offsets Frame::ScriptArgs kept locally move to Offsets.h now
that a second file reads the struct; its numparams @+0x45 / is_vararg
@+0x46 independently pin nups to the byte before them.

Verified in-game: 32 and 33 both load (engine path, first spill); 40
upvalues through the OP_MOVE path and again through a middle function's
OP_GETUPVAL path each return the right sum; a syntax error inside a
40-upvalue body followed by a clean parse still returns the right sum
(the stale-clear); 255 split across two scopes loads, and 256 fails with
the engine's own "too many upvalues (limit=255)".
2026-09-06 13:38:03 -05:00
Brues e5690b1c6a docs(readme): list texture:ResetTexCoord in the Frame row 2026-09-06 11:24:45 -05:00
Brues e91b1457fd ci: ship the pdb and map in the dev build artifact
The per-push artifact held only the DLL, so a dev build could not be
triaged from the outside. With the PDB sitting next to the DLL the
client's own crash handler resolves our frames to file and line -- a
tester's log reads `Texture::Mask::PrimIndexed_h+12 (Mask.cpp,246)`
instead of a bare address -- and the map resolves `0001:offset`
addresses by hand when there is no dump. That is the difference between
a report that names the function and one that needs a Ghidra session to
place a return address.

Both files are already produced for every build: the /Zi, /MAP and /DEBUG
flags are set unconditionally, not gated on release. They were simply not
being uploaded, while the release path has bundled them all along.

Their value is that they match one exact build, so they travel with it
rather than being rebuilt later from the same commit. All three share
build/Release as their parent and land at the zip root.

if-no-files-found: error, because an artifact missing its symbols looks
identical to a good one until someone needs a stack out of it.
2026-09-06 11:15:15 -05:00
Brues 09c5832ae8 fix(texture): make texture coordinates address the atlas art, not the file
With an atlas applied, SetTexCoord was addressing the whole sheet, so a
crop showed a slice of the surrounding art rather than a part of the
sprite, and GetTexCoord reported the atlas rect where a caller expected
what it had asked for. Both came from one cause: SetAtlas was writing the
atlas rect into the region's only set of coordinates, leaving the
caller's own nowhere to live.

A live client shows the two are separate state there: GetTexCoord reads
the full 0..1 rect immediately after SetAtlas, with GetAtlas still
reporting the atlas, so 0..1 means all of the sprite rather than all of
the sheet. Keep the caller's coordinates alongside the atlas name and
compose: SetTexCoord records them in sprite space and writes the mapped
result for the engine to draw, GetTexCoord hands them back. Both handlers
are co-hooked and pass straight through for a texture with no atlas,
which is every texture in the game until an addon calls SetAtlas -- the
empty-map test is the whole cost in that case. Both the 4-argument and
8-argument corner forms compose; anything else is left to the engine to
reject so its own error text is what the author sees.

ResetTexCoord becomes a plain restore of identity, which is what it
always was conceptually -- the atlas rect now falls out of composing
identity rather than being a special case.

Also clear the atlas on SetTexture rather than inferring it from the
texture handle. The handle comparison cannot detect a re-set to the very
file the atlas names, because the engine returns the same HTEXTURE, so
GetAtlas kept reporting an atlas that was no longer showing. That guard
predates this change. It stays for recycled regions, which is the case it
is actually good for and the reason this module needs no region
constructor hook.

Verified in-game against a registered quarter-rect atlas: identity is
reported after SetAtlas, a crop reads back in sprite space, the engine
receives the composed file-space rect from both argument forms, reset
returns to the full sprite, SetTexture clears the atlas even to the same
file, and a texture with no atlas behaves exactly as before.
2026-09-06 11:12:55 -05:00
Brues 4015fee5e2 feat(texture): add texture:ResetTexCoord
Drops a crop made with SetTexCoord or SetSpriteSheetCell and goes back to
showing the whole of whatever the texture points at.

What "the whole of it" means was the only open question, and the
generated API docs answer none of it -- ResetTexCoord is listed with no
arguments, no returns and no description, and Blizzard's own FrameXML
never calls it. Settled by testing a live client instead: with an atlas
applied, GetTexCoord reads the full 0..1 rect, and a reset after a
SetTexCoord returns to that with GetAtlas still reporting the atlas.

So the source and the user's texcoords are separate state there, and
0..1 means "all of the sprite" rather than "all of the sheet". Here an
atlas IS its texcoords -- SetAtlas is SetTexture plus SetTexCoord, with
no second layer to hold the sub-rect -- so identity for an atlas'd
texture is the atlas's own rect. Resetting to a literal 0,0,1,1 would
show the whole sheet where retail shows the sprite, so the atlas rect is
restored instead, which reproduces the visible result. Reuses GetAtlas's
staleness guard, so a texture pointed elsewhere since resets to the full
rect.

Verified in-game against a registered quarter-rect atlas: SetAtlas gives
the rect, SetTexCoord replaces it, ResetTexCoord restores it with the
atlas still set, and a plain textured region with no atlas resets to
0,0,1,1 with GetAtlas nil.
2026-09-06 10:59:47 -05:00
Brues 744bfb31d1 docs(tick): name the UI render root's arguments for what they are
The hook declared `(void *bounds, int flag)`. The second argument is the
frame's elapsed time as a float: the HLAYER drain calls every layer as
`cb(layer + 0x18, DAT_00885608)`, and DAT_00885608 is set at 0x00442330
and zeroed at 0x004426C3 once the drain finishes. FUN_00765650 passes it
straight to every frame's vtable +0x38 per-frame update, which is where
OnUpdate's `%f` comes from -- the same value visible threading through
both hooks in a recent backtrace.

Rename both parameters and correct the type rather than leave an `int`
sitting under a comment calling it a float. ABI-identical: both are
4-byte stack slots under __stdcall and both are forwarded untouched.

The Offsets.h note gains the rest of what was verified while checking
this: the caller discards the return value, `bounds` is the layer rect
and is never read by this callback, and ECX is not read on entry, so it
is not a __thiscall in disguise.
2026-09-06 10:43:00 -05:00
Brues 8706d1d99b docs: combine the launch switches into one API.md section
The two README rows covered one subject -- things you put on the command
line that starts the game -- and each carried its full detail inline,
which is the one place in that table where a row was doing a reference
page's job. Fold them into a single linked row and give the detail a
Launch section in API.md, next to the console commands, which are the
other entries that are not Lua functions.

The section also states what the two switches share, which neither row
had room for: the name matching is case-insensitive, `-name value`,
`-name=value` and `/name value` are equivalent, and a value with spaces
needs quoting. For -config it now says what does and does not follow a
profile, since the addon enable list living under WTF\Account\ is the
part that surprises people.
2026-09-06 09:59:17 -05:00
Brues 8637bf05e5 feat(config): add -gluescript / -gamescript launch switches
Four switches that run Lua as the client starts:

  -gluescript      <code>   run at the glue screens
  -gluescriptFile  <path>   the file's contents, run at the glue screens
  -gamescript      <code>   run once in-game
  -gamescriptFile  <path>   the file's contents, run once in-game

None of these exist in 1.12. The strings appear nowhere in the binary, so
there is nothing to parse them and nothing to un-gate -- the feature is
ours end to end.

Registration time is too early for either state. The in-game module
callback runs from FUN_LOAD_SCRIPT_FUNCTIONS, before FrameXML loads, and
the glue callback runs from FUN_LOAD_GLUE_SCRIPT_FUNCTIONS, before
GlueXML does. A script running there could not touch a frame, call a
FrameXML function or see an addon, which is most of what one would be
written for. So each is armed at registration and run from a tick, where
the UI is demonstrably up. Glue uses FrameTick, whose hook is the UI
render root and so fires at the login and character-select screens; it is
re-armed by the glue module callback on every glue boot, so a script that
logs in automatically still works after a logout. Game uses WorldTick,
which is world-only, so its first tick is past FrameXML, past the addon
load pass and past enter-world init; it latches for the life of the
process, since "run once in-game" says once.

FUN_LUA_RUN_STRING resolves the Lua state itself rather than taking one,
so a single call site reaches whichever state is current and the two
paths differ only in when they fire. It installs the FrameScript error
handler as the pcall's errfunc, so a faulty script reports itself the way
any script error does instead of failing silently, and because every
chunk goes through the shared compile chokepoint these scripts get the
same 5.1 syntax support the rest of the client's Lua has.

A *File is read with Win32 rather than the engine's file layer. The
engine resolves relative paths against a loose-file index built once at
boot, so it cannot see a file created afterwards and cannot open an
absolute path at all -- and an absolute path is what goes in a shortcut.
Reading it directly also lets both switches share one execution path, so
inline code and file contents cannot diverge.

The switch parser moves to Config::CommandLine, shared with -config
rather than copied: the quoting and token-boundary rules are exactly
where a second copy would drift unnoticed. Lifting it also fixed a latent
overread, where a switch name at the very end of the command line was
compared past its terminator.

Verified in-game on Turtle: inline and file forms in both states; the
in-game script silent across /reload and a second login while the glue
script re-ran on returning to character select; a syntax error and a
missing file each reported without a crash; and -config still applying
through the shared parser.
2026-09-06 09:53:58 -05:00
Brues 802039fd08 fix(texture): stop a zero-dimension texture hanging the mip accounting
The engine's mip-chain byte total FUN_GX_TEXTURE_MIP_BYTES (0x00594CE0)
walks a texture's levels by halving both dimensions until each reaches
exactly 1, and gates every halving on JBE. A dimension of 0 therefore
never shifts and never reaches 1, so the loop at 0x00594D47 spins
forever. It does no allocation and no I/O, which is why it presents as a
hard freeze at 100% of one core rather than a crash, and why the client
never recovers.

Caught live at 0x00594D78 by a SIGSEGV-forced backtrace taken during
login under Wine. The frame's four printed stack slots are this
function's own reused parameter slots, and read back as 4 bytes per block
(uncompressed 32-bit) with both dimensions 0. The call chain checks out
edge for edge from the region-layer draw down through the state flush and
the texture-stage apply, so it is a real stack rather than a heuristic
scan. Note that the state flush applies a dirty list, so the UI draw at
the bottom is where the flush happened, not necessarily what bound the
texture.

One branch above the loop the engine already handles the analogous case
correctly: a texture with no mip chain returns its base-level bytes and
stops. The guard gives a degenerate dimension the same answer. It
resolves the caller's arguments the way the original does and, when
either dimension would shift to zero, raises that one to the smallest
value the accounting can express before calling through. The loop then
terminates on its first pass. No mip math, format table or reduction
level is reimplemented. Clamping at the entry rather than at a call site
also covers the second caller, FUN_00594C80, which accounts for a lock by
passing a dirty rect's width and height and hangs identically on an empty
but still flagged rect.

A dimension can also reach zero without the texture being 0x0, via the
reduction level the accounting shifts by -- a caps field (caps + 0xE0,
the block being device + 0x23C per FUN_005923D0) filled from the graphics
backend. Measured 0 on a native D3D9 driver, unmeasured under wined3d.
So the guard tests the shifted value and clamps to 1 << reduce rather
than assuming either case.

Who feeds it a zero is a separate question, and the guard does not bury
it. ClassicAPI constructs no textures, and DimensionGate cannot admit a
zero it would otherwise reject, since the validator's power-of-two test
already yields "is a power of two" for 0. So the first occurrence is
logged with everything readable off the texture, plus
Texture::Mask::AnyMaskActive() to rule the mask path in or out -- passive
evidence that costs whoever hits the freeze nothing.
2026-09-06 09:07:11 -05:00
Brues d14f0b44c1 fix(compat): restore vanilla script args for LunaUnitFrames headers
Fixes #41.

LunaUnitFrames sets SetupGroupHeader(groupType) as its group headers'
OnEvent while also calling it directly with a group name. As a handler it
relies on groupType being nil so it falls back to this.unitGroup. Our
modern script arguments hand it `self` instead, so it looks the header up
by frame rather than by name, gets nothing, and indexes nil at
units.lua:358.

The addon is correct vanilla code. A function that is both called directly
and used as a script handler is an ordinary vanilla idiom, and passing
positional arguments to handlers breaks it wherever the first parameter
means something other than self.

Adds CAPI_VanillaScriptArgsCompat(frame, script), which rewraps one
handler in a no-parameter closure so the extra arguments stop there and
the original runs with the empty argument list it was written for. The
globals survive the nesting, so it still reads `this` and `event`. Same
shape as the existing CAPI_MouseoverClearedCompat.

Only the group headers need it. SetupRaidHeader takes the header frame
itself, so `self` is already the value it wants.

This covers one addon, not the class. Any addon using the same idiom hits
the same failure, and each will need its own entry here until handlers
opt in to modern arguments rather than receiving them unconditionally.
2026-09-05 16:02:37 -05:00
Brues 008282d65a fix(aura): revoke nibble polarity when the flags contradict it
Detection says a Turtle server writes polarity into the aura flag nibble.
If that stops being true — Turtle changes SetAuraFlag, or something else
identifies as Turtle without the patch — nothing noticed, and the failure
is the loud one: reading 0x08 as "harmful" under the stock encoding means
"effect index 0 has an aura", so nearly every buff reports as a debuff.

IsSlotHarmful now checks each nibble against the three values Turtle's
SetAuraFlag can produce (HELPFUL, HELPFUL|CANCELABLE, HARMFUL). Anything
else latches the slot range back on for the rest of the process.

Revocation only, never promotion. Agreement is not provable: a run of
0x08 readings is equally consistent with single-effect auras under the
stock encoding, so no observation can justify turning nibble reading ON.
Identity stays the only thing that does. Defaulting the other way would
misclassify every buff on a stock server for as long as it took a
contradiction to show up, which is the failure this guards against.

Does not help a non-Turtle server that copied the spill patch — that one
still falls back to the range and reports spilled debuffs as buffs, the
same answer native UnitBuff/UnitDebuff give there. Covering it needs
server-independent polarity (a port of the server's IsPositiveSpell
heuristic), which is a much larger change for a rarer case.
2026-09-05 15:40:50 -05:00
Brues 9a8c314d69 fix(aura): scope flag-nibble polarity to Turtle
The aura flag nibble does not mean the same thing on every server, and
reading it as polarity everywhere was badly wrong off Turtle.

Stock (vmangos SpellAuraDefines.h + SetAuraFlag): the bits are
CANCELABLE 0x01, EFF_INDEX_2 0x02, EFF_INDEX_1 0x04, EFF_INDEX_0 0x08 —
one per spell effect index that carries an aura, plus cancelable for a
positive aura. No polarity is encoded at all. So testing 0x08 for
"harmful" was really testing "effect index 0 has an aura", which is true
of nearly every aura, and reported almost every BUFF as a debuff.

Turtle (tortoise-wow SetAuraFlag) replaces those effect-index bits with
polarity: 0x04 positive, 0x08 negative. It needs to, because it also
drops the else in the slot search so a debuff spills into 0..31 once the
16 harmful slots are full — the range stops being reliable there and the
nibble is what preserves the answer. Stock keeps a strict either/or, so
nothing ever crosses over and the range is exact.

IsSlotHarmful now picks per server and is the one place that decides.
Every other site defers to it rather than testing either signal.

Identity detection rather than behavioral: on Turtle every nibble is one
of {0x04,0x05,0x08}, while stock nibbles routinely fall outside that set,
so an out-of-set nibble proves stock — but the converse never arrives,
since single-effect stock auras land on 0x08 by coincidence. Stock is
provable, Turtle is not, and the unprovable direction is the catastrophic
one. A Turtle fork still detects (clones keep the TURTLE_* global names).
A non-Turtle server that copied the spill patch falls back to the range
and reports spilled debuffs as buffs, matching what native
UnitBuff/UnitDebuff already do there.
2026-09-05 15:34:03 -05:00
Brues 4b1bf16ba5 refactor(settings): one place builds ClassicAPI's WTF\Account paths
Three modules resolved these independently. equipmentset/Storage.cpp and
friendlist/Notes.cpp had byte-identical copies of the same three engine
reads (account, realm, character), the same null and empty gates, and the
same separator joining — differing only in the leaf filename.
settings/Account.cpp had a third copy of the account half, with its own
inline pointer cast instead of Game::Read.

Settings::Paths now owns that, exposing AccountFile and CharacterFile.
Both return an empty string until the globals they need are populated, so
callers keep treating empty as "not available yet" and no longer null-check
the individual names. Behavior is unchanged: the paths built are the same
strings, and the readers moved across verbatim.

AddOns::SavedVarsFirst deliberately keeps its own copies. It mirrors the
ENGINE's saved-variable layout and has to match it byte for byte, which is
a different contract from naming ClassicAPI's own files — the two only
happen to share a directory, and tying them together would mean an edit
intended for one silently moving the other.

Storage.cpp and Notes.cpp no longer reference Game or Offsets at all, so
those includes go too.
2026-09-05 14:38:17 -05:00
Brues 5528fb5fa4 feat(config): add a -config launch switch for settings profiles
`-config Config2.wtf` makes the client read and write WTF\Config2.wtf in
place of WTF\Config.wtf, so one install can hold several profiles.

The engine already names its config file through a single pointer: boot
passes "Config.wtf" to the config initializer, which keeps it at
0x00C4EDD4 and uses it for both sides — the load at 0x0063D428
(MOV ECX,[0x00C4EDD4]; CALL 0x0063D820) and the save in FUN_0063D980,
which builds "WTF\" + the same pointer. Supplying a different string is
therefore the entire feature, with no second code path and no way for
reading and writing to disagree.

This is patched rather than hooked because of when it happens. The config
is read from FUN_00402350 during boot, several calls before VanillaFixes
invokes our Load export — VF hooks GetCPUFrequency (0x0042C060), which is
reached from the FUN_0063A230() that runs after the config is already in.
DllMain does run in time, since VF injects every dlls.txt DLL while the
process is still CREATE_SUSPENDED and resumes it only afterwards. So this
is the one module DllMain names directly. It is a 4-byte store into an
immediate operand, not a hook, so it carries none of the loader-lock cost
that keeps hook installation out of DllMain.

VanillaFixes forwards any non-.exe argument to the game verbatim
(CmdLineParse/AppendArg), so the switch works from the launcher shortcut.

The name must be a plain filename. The engine builds the save path as
"WTF\" + name, and a folder that does not exist makes the save fail
silently, which would discard a session's settings with no warning.
2026-09-05 13:15:04 -05:00
Brues 7ab32df2aa feat(texture): add texture:SetSpriteSheetCell
Crops a texture to one cell of an evenly divided grid, which is the
arithmetic every sprite-sheet call site would otherwise repeat. It is the
primitive behind raid target markers, whose eight icons share one 4x4
sheet, and this client already ships the FrameXML helper
(SetRaidTargetIconTexture) that wants it.

`cell` is 1-based and counts left to right then top to bottom — Blizzard
types the argument `luaIndex`, and its own callers pass GetRaidTargetIndex
straight through without adjusting it.

cellWidth and cellHeight are accepted and ignored. Both call sites in
Blizzard's UI pass the three-argument form, and the grid alone already
fixes each cell's coordinates, so honoring them would mean guessing at
their meaning.

The coordinates go through the engine's own SetTexCoord handler, so this
module contributes only the grid math.
2026-09-05 00:30:39 -05:00
Brues 8e1429bfac feat(texture): publish raid target markers as atlases
All eight markers live in one 4x4 sheet on this client, and the per-marker
files other clients ship are absent here — the art directory holds only
UI-RaidTargetingIcons.blp. So naming a single marker requires a sheet plus
a sub-rect, which is what an atlas is. A port referencing an individual
marker file otherwise gets nothing.

Blizzard publishes no atlas names for these. Checked: zero hits for
raidtarget / targeting / raidmarker in UiTextureAtlasMember, and current
Classic Era still draws them by computing texcoords in
SetRaidTargetIconTexture and by per-file |T markup in chat. The names here
therefore follow the standalone marker filenames other clients ship, so an
addon written against those finds the art under the name it already knows.

This lives in the addon rather than AtlasData.h on purpose: the DLL's
built-in table means "names Blizzard defined", and adding invented ones
there would quietly corrupt that contract. Cell math matches the chat
marker tokens, and markers 4 and 8 were confirmed on screen.

Also adds CreateAtlasMarkup alongside the existing texture markup helper.
2026-09-05 00:26:40 -05:00
Brues 9322382596 feat(texture): bind chatframe-button-highlightalert
First atlas binding derived by widget match rather than name match, and the
reason the table now documents both methods.

Classic Era's FloatingChatFrame.xml draws the chat menu button's Flash
overlay with atlas "chatframe-button-highlightalert". This client's
FloatingChatFrame.xml draws the same $parentFlash region with
UI-ChatIcon-BlinkHilight and no TexCoords, so the whole file is the sprite.
Both UIs are exported on disk, so the binding is read off the two trees
rather than guessed. Verified in-game as a blue glow ring.

Size comes from the 1.12 file (32x32), not the member table (34x32) —
packing added bleed that the vanilla art does not have.
2026-09-05 00:20:43 -05:00
Brues c3cf9e6f3a feat(texture): add atlas support — C_Texture, SetAtlas, and |A markup
An atlas names a texture plus a sub-rect inside it, so SetAtlas is the
engine's own SetTexture + SetTexCoord (+ the size setters for
useAtlasSize) driven off one lookup. Every step delegates to the engine's
Lua handlers, so the argument guards and the UI-scale conversion stay in
force and this module only adds the name resolution.

Adds C_Texture.GetAtlasInfo / GetAtlasExists / GetAtlasID /
GetAtlasElementID / GetAtlasElements, the RegisterAtlas extension for
addons that ship their own sprite sheet, texture:SetAtlas / GetAtlas, and
the |A:name:h:w|a inline markup alongside the existing |T form. All five
readers key off one bound set, so GetAtlasExists is true exactly when
GetAtlasInfo returns a table.

The built-in table is five rows on purpose. Measured against Classic Era's
UiTextureAtlas tables and the community listfile: 0 of 868 atlas sheets
exist in this client's art, and while Blizzard kept the original vanilla
filename as the atlas name for 16 members, only 5 have dimensions that
agree — vanilla's own scrollbar template draws a centered 16x16 out of a
32x32 file that the atlas calls 18x16. Texcoords are not derivable from
the two tables, so the rest grow from _classicapi_DumpAtlasMisses()
rather than from guesses. AtlasData.h carries the full derivation.

|A shares every scanner, measure, wrap and placement stage with |T —
ParseAtlasIcon fills the same IconDesc, since an atlas is exactly the
path-plus-sub-rect that struct already holds. That makes the chat
anti-spoof mandatory, not optional: IconFilter now defangs |A too, or a
player could render art by typing it into /say and the speech bubble.

GetAtlas stores the HTEXTURE it installed and clears itself when the
region points elsewhere, which gives the correct nil-after-SetTexture
behavior and avoids a second hook on FUN_SIMPLETEXTURE_CTOR — Texture::Mask
owns that target and MinHook refuses a duplicate, which would abort the
whole hook install.
2026-09-05 00:11:08 -05:00
Brues f5d6046523 feat(map): add C_Map.GetMapArtLayers
Describes the single fixed layer a map's background is drawn as: a
1002x668 canvas cut into 256-pixel tiles (the 4x3 grid of twelve the
world map frame draws), scale 1 to 1 with no extra zoom steps, since a
map does not zoom here. A map with no art returns an empty table.

Canvas and tile sizes come from the client's own WorldMapFrame.xml, and
move to Map::Area so the overlay hit-rect math shares them instead of
keeping a second copy.

They stay constants on purpose. A live read of WorldMapDetailFrame looks
more engine-driven but is wrong twice: the frame is addon-mutable while
the DBC coordinates it normalizes are authored against the shipped size,
and these are logical sizes -- an HD map patch ships larger tiles, which
Map::Overlays already detects and scales, and reporting a patched tile's
real size would break the canvas/tile division that yields the grid.
2026-09-04 22:57:22 -05:00
Brues e1ebf6ecce feat(map): add C_Map.MapHasArt and GetMapArtLayerTextures
A map's background is the tile set Interface\WorldMap\<dir>\<dir>1..12,
where <dir> is the WorldMapArea row's own name -- the path the world map
frame builds its tiles from. So "does this map have art" and "give me its
tiles" are both answerable by probing that set, even though the modern
atlas art model has no counterpart here.

MapHasArt is independent of whether a map has coordinates: the
whole-world map has art but a zero rect, and instance rows can have a
rect but ship no art.

GetMapArtLayerTextures returns texture PATHS rather than the numeric file
ids of the modern call. A texture is named by its path on this client and
SetTexture takes that path, so ids would be both unavailable and
unusable; GetMapOverlays already makes the same substitution for its
fileDataIDs. There is one art layer, so layerIndex 1 returns the
background and any other index an empty table.

Path convention and the 12-tile count taken from the client's own
FrameXML rather than assumed.
2026-09-04 22:38:49 -05:00
Brues 698827e9c5 fix(addons): report a real loaded state from IsAddOnLoaded
The engine sets an addon entry's loaded byte at the START of its load,
before dependencies and before the addon's own files run, clearing it
again only if a required dependency fails. That byte therefore means
"load has begun" -- it is loadedOrLoading, not loaded.

IsAddOnLoaded returned it for both values, so an addon checking itself
at file scope got (true, true) where it should get (true, false). The
old comment claimed the in-flight window was unobservable from Lua; it
is plainly observable, since the addon's own files and every dependency
pulled in during them execute inside it.

Add AddOns::LoadState, which co-hooks the per-addon loader and keeps a
stack of the names currently loading -- a stack because dependency loads
nest, and the name is copied because LoadAddOn passes a transient Lua
string. loadedOrLoading stays the engine byte; loaded now also requires
the addon not to be mid-load.

Known gap, documented: an addon asking about itself from its own
ADDON_LOADED handler still reads (true, false), as that event fires just
before the load call returns.

Also mirror the stock LoadAddOn global into C_AddOns. It already returns
the modern (loaded, value) shape -- 1/nil plus a locale-independent
reason token -- so it registers as the engine's own handler.
2026-09-04 21:48:13 -05:00
Brues 60530e32fc feat(faction): add C_Reputation inactive getters and by-id setters
Adds SetFactionInactiveByID / SetFactionActiveByID, which file a faction
into or out of the "Inactive" category by id rather than by
displayed-list position, plus IsFactionActive and IsFactionActiveByID to
read that state back.

IsFactionActive is a real backport and takes a sort index, returning a
boolean; the ByID forms are ClassicAPI extensions.

Both stock setters are just an index resolve around one shared engine
setter that already takes a faction id, so the by-id pair is that call
with 1 or 0. It sends the change to the server, rebuilds the displayed
list (so positions shift), and being the function UnitFactionPolyfill
hooks, fires UNIT_FACTION.

The inactive getter is the odd one out: unlike the at-war getter, its
worker takes the 0-based index and resolves internally. So both read
forms are built from Resolver() plus a factored rep-slot read, which
reproduces the engine's own index -> factionID -> repListID -> flag
chain and lets them share one implementation.

Also mirror the stock SetFactionInactive, SetFactionActive and
IsFactionInactive globals into the namespace, registering the engine's
own handlers rather than reimplementing them.
2026-09-04 21:32:14 -05:00
Brues 3cffb71b20 feat(faction): add C_Reputation.ToggleFactionAtWarByID
Flips a faction's at-war state by ID rather than by displayed-list
position. A ClassicAPI extension -- Blizzard has no such call.

The stock FactionToggleAtWar(index) resolves its index to a faction id
and then reads, negates and writes through two helpers that already take
an id, so the by-id form is that pair without the resolve. Every rule
stays in the engine: the refusal to make peace below -3000 standing, the
peace-forced flag, the loot-session bail, and CMSG_SET_FACTION_ATWAR.
Going through the engine's setter also picks up UnitFactionPolyfill's
hook on it, so UNIT_FACTION fires, and its change detection keeps that
silent when the engine refuses the toggle.

Declare the setter's newState as int, matching the polyfill's detour: a
char argument defines only the low byte of EDX and would leave the
detour's int parameter with undefined high bits.

Also mirror the stock global into the namespace as
C_Reputation.ToggleFactionAtWar, registering the engine's own handler
rather than reimplementing it. Adds the getter and script-wrapper
addresses, which existed only as comment references.
2026-09-04 21:18:00 -05:00
Brues 7887237a6e feat(faction): add C_Reputation.SetSelectedFactionByID
Selects a reputation-pane faction by ID rather than by displayed-list
position, matching what SetWatchedFactionByID gives over the stock
index call. A ClassicAPI extension -- Blizzard has no such call.

The engine already holds the selection AS a faction id: the stock
SetSelectedFaction(index) resolves its argument through the faction
index resolver and stores the resulting id, and GetSelectedFaction maps
that id back to an index. So this writes the id straight through, with
no list walk, and works even while the faction is not listed.

Also mirror the stock SetSelectedFaction global into C_Reputation. Its
handler already has the Lua C ABI, so it registers as-is rather than
being reimplemented.
2026-09-04 21:05:53 -05:00
Brues 98af79137b feat(faction): add C_Reputation.GetFactionDataByID
Keys the modern FactionData table by faction ID instead of by
displayed-list position. Reuses the shared ReadFactionData chain and
table builder, so it needs no new engine work.

Unlike GetFactionInfoByID this is not limited to the player's
reputation list: an unencountered faction fills cleanly with
currentStanding 0 and atWarWith false, so any real faction's name,
description and thresholds are readable.
2026-09-04 20:50:58 -05:00
Brues 622882725f feat(map): C_Map user waypoint (Tier 3)
Add the eight user-waypoint calls and USER_WAYPOINT_UPDATED: set, get,
has, clear, per-map position, the two hyperlink converters, and the
can-set check.

The pin is one piece of session state (a uiMapID, a 0..1 position and an
optional z) that survives a UI reload. GetUserWaypointPositionForMap
re-projects it onto any other map through world coordinates, so a zone
pin resolves on its continent and back. The hyperlink is the standard
worldmap:uiMapID:x:y payload with both coordinates scaled by 10000, and
the parser accepts a whole link or the bare payload.

UiMapPoint's factories go in the addon, matching where retail ships them.
Extract the shared vector2 marshalling to map/Vector2.h so the waypoint
and coordinate modules don't each carry a copy.
2026-09-04 20:46:22 -05:00
Brues 0517bb3753 feat(map): C_Map map hierarchy (Tier 2)
Add GetMapInfo, GetMapChildrenInfo, GetMapInfoAtPosition and
GetFallbackWorldMapID, giving the World -> Continent -> Zone tree.

Continents carry no AreaTable id (their WorldMapArea rows have areaID 0),
so they are named by a negative -(WorldMapArea row) -- mirroring the
engine's own zoneOrSort idiom, where positive is an AreaTable zone and
negative a QuestSort row. Names and mapType for those come from Map.dbc.

Move the row math into Map::Area (RowForUiMapID, ContinentRowForMapID,
RowRect, PercentInRow, WorldFromRow) and put the Tier 1 coordinate
functions on it, so they accept continent ids too and GetMapRectOnMap
honors topUiMapID.
2026-09-04 20:06:15 -05:00
Brues fb17488237 feat(map): C_Map coordinate transforms (Tier 1)
Add GetPlayerMapPosition, GetWorldPosFromMapPos, GetMapPosFromWorldPos,
and GetMapRectOnMap on the existing AreaTable-id=uiMapID scheme, reusing
Map::Area's world<->map projection. Positions returned as Vector2DMixin.
2026-09-04 19:34:45 -05:00
Brues b1ee8cc183 fix(texture): pool-free must skip oversized textures too
Regression from the size gate (be92d72 / 2ce5b00): the cave lets textures
larger than the recycle pool can index be created, but the pool FREE path
FUN_00448670 was left filing every freed texture into a bucket keyed by
each dimension's power-of-two factor, with no upper bound. A power-of-two
texture over 1024 (tz 6 per axis) files at bucket 36-42, past the 36-entry
table, and writes through a garbage list head — an ACCESS_VIOLATION at
0x004487D9 that fired whenever such a texture was freed, shutdown included.
Only power-of-two dimensions reach the bad index; NPOT has a small
power-of-two factor and stayed in range, which is why it went unseen until
a 2048x2048 was loaded and the client closed.

The allocator's cave already routes oversized textures around the pool;
this does the mirror on free — a cold hook on FUN_00448670 sends any
texture the bucket table can't index to the engine's own non-pooled free
FUN_0058AD60, exactly the guard's else-branch for too-small / too-many-mip
textures. Verified: a 2048x2048 texture renders and /reload (full texture
teardown) no longer crashes.
2026-09-04 18:46:22 -05:00
Brues c08ded6db4 feat(texture): BLP loads at any size; guard the async fallback
BLP decodes into the shared scratch BEFORE it calls the allocator, so the
size cave (which fires from the allocator) was always too late for it — a
2048x2048 BLP overran the scratch on this client. A pre-hook on the
decompressor FUN_005A8430, which carries the level-0 dimensions, grows the
scratch first and repoints the caller's already-copied scratch slot at the
new buffer, or fails cleanly for a texture the GPU cannot hold. It acts
only when the slot IS the shared scratch; the IMG path decodes into its own
right-sized buffer and is left alone. GrowScratch now retires the previous
buffer one generation late (frees at the next growth) so any unaccounted
holder reads stale bytes, not unmapped memory. Verified: a 2048x2048 DXT1
BLP renders and grows the scratch to 2048.

The async force-load path shoves a read that never fit the shared buffer
into a 512 KiB static fallback with no size check — the engine bug behind
"big BLPs crash". The hook refuses a request larger than the fallback; the
texture stays blank. Growing the fallback to fit was tried and reverted:
the read runs on the engine's async reader thread, which has no crash
handler, and a read into a right-sized heap buffer froze then killed the
process where the same read into the oversized shared buffer does not — not
yet isolated. Consequence: an uncompressed BLP file larger than the shared
buffer (2 MiB stock, 32 MiB with VanillaHelpers) does not load; DXT stays
far under it and TGA is synchronous, so only a pathological input is lost.
Verified: a 2900x2900 uncompressed BLP draws nothing and does not freeze.
2026-09-04 18:31:17 -05:00
Brues 640f78b2eb docs: texture size and shape
README gains an "Any texture size" row in Modern client behaviors; API.md
gains a "Texture size and shape" section under Frame, after the texture
methods: any width and height, no fixed upper limit beyond the graphics
card's maximum, memory allocated only when a large texture loads, and the
two remaining file-level limits (BLP files over ~2 MB / 32 MB with
VanillaHelpers stay blank; NPOT BLPs with DXT or mips are untested).
2026-09-04 17:32:51 -05:00
Brues a51ec40e52 refactor(texture): drop the NPOT toggle; non-power-of-two is simply on
_classicapi_NonPowerOfTwoTextures existed to A/B the same texture during
bring-up. As a knob it fails the same test the textureMaxDimension cvar
did: it reset every launch, so neither a user nor an addon author could
rely on either state, and disabling NPOT for real would be a code change
anyway. Removing it also removes the snapshot/restore machinery that
served only it. The enable path is byte-identical to before.

_classicapi_TextureLimits() stays as the read-only diagnostic, minus the
always-true NPOT field: scratchSide, poolMax, poolSide, deviceMax,
strideFixed.
2026-09-04 17:12:41 -05:00
Brues 2ce5b007af feat(texture): grow the decode scratch on demand; guard the async fallback
Layers 3 and 4 of Texture::DimensionGate. There is no number of ours
anywhere: the cave hands each rejected texture's width and height to
EnsureScratch, which refuses only what the device's own caps max refuses
(the field the create validator FUN_0058AB10 compares against, so we never
grow for a texture the engine would reject a moment later) and otherwise
replaces the scratch with one that fits, through the engine's decode-buffer
constructor FUN_005A4AF0 — the routine both decoders already use when the
scratch is NULL. The scratch is a high-water mark; nothing changes for
anyone who never loads a texture over the stock limit.

The "big BLPs crash" bug is fixed at its source rather than by enlarging
the shared async buffer: FUN_0044AD50 (the force-load every UI texture
takes on first draw) shoves a read that never fit the shared buffer into a
512 KiB static fallback at 0x00885804 with no size check — bounded exactly
by the pool globals that follow it. A hook refuses to force a request
larger than the fallback; it stays pending and the texture stays
invisible, the normal not-loaded state. BLP files are thereby bounded by
the shared buffer (2 MiB stock, 32 MiB with VanillaHelpers) gracefully.
TGA reads are synchronous and never touch that path.

Verified in-game: scratch reads 1024 at boot, a 2560x1080 TGA renders
with no configuration, and the scratch then reads 2560. Device max on
the test GPU is 16384.

_classicapi_TextureLimits() now returns scratchSide, poolMax, poolSide,
deviceMax, nonPowerOfTwo, strideFixed.
2026-09-04 17:06:35 -05:00
Brues be92d721f0 feat(texture): dimension gate — NPOT textures, bound follows the scratch
1.12 requires power-of-two textures at two software sites (allocator
FUN_00448450 and create validator FUN_0058AB10); 3.3.5 and 4.3.4 keep the
rule unchanged. Verified in-game that the D3D backend samples NPOT
correctly for the TGA/UI path, so Texture::DimensionGate relaxes both
sites, default on.

The real size ceiling is not the allocator's `< 0x400` but a single global
decode scratch buffer sized once at boot (512^2 stock, 1024^2 with
VanillaHelpers) and written with no bounds check. The validator's
device-caps max is raw hardware and protects nothing — a 2560x1080 TGA
faulted in the decoder's pixel writer at 0x004492E5. So the gate reads the
scratch dimension back from the boot immediates and enforces exactly that,
and every dimension failure — POT or size — routes through a 28-byte code
cave that applies the bound before the fresh-allocation tail. Routing POT
failures straight to that tail would jump over the size CMPs.

Also fixes VanillaHelpers' recycle-pool collision: it grows the table to
6x6 but leaves the index stride at 5, so 32x1024 shared a bucket with 64x32
(rendered nothing) and 64x1024 with 128x32 (worked by luck). Both index
sites are rewritten to stride 6 when its 36-bucket table is detected.

Lua: _classicapi_NonPowerOfTwoTextures([enable]), _classicapi_TextureLimits().
2026-09-04 16:16:11 -05:00
Brues b81f672ad7 fix(aura): classify auras by polarity flag, not slot range
The server seats buffs in slots 0..31 and debuffs in 32..47 only while it
can: once the 16 debuff slots are full, _AddSpellAuraHolder parks further
debuffs in free BUFF slots and sets UNIT_FLAG_AURAS_VISIBLE so the client
still renders them (tortoise-wow, verified). Classifying by slot range
therefore reported those as buffs -- absent from HARMFUL, and wrong in
isHelpful / isHarmful. Confirmed live on a 20-aura target: 18 harmful, two
of them sitting in buff slots, where the old code returned 16.

Every visible aura carries its real polarity in the per-slot flag nibble
(SpellAuraHolder::SetAuraFlag writes 0x04 positive / 0x08 negative), so
HELPFUL / HARMFUL now select on that instead. All the walkers -- by index,
by spell ID, by name, GetUnitAuras, GetAuraSlots -- share one order helper,
SlotInFilterOrder, which visits the polarity's home range first and the
other range after, so every index is unchanged whenever nothing has
spilled. Aura::Source's KindForSlot classifies the same way, keeping the
descriptor-drop fallback consistent with the query paths. The out-of-range
group array carries spell IDs with no flags, so that path stays
range-based -- the seating range is the only polarity it has.

GameTooltip:SetUnitAura now bridges the two index spaces. The engine's
SetUnitBuff / SetUnitDebuff index their own slot RANGE, which diverges from
the polarity index space as soon as a debuff spills, so the method resolves
(index, filter) to an absolute slot and hands the engine the index that
slot holds within its own range, picking the method by where the slot
lives. It counts with the engine's TOOLTIP visibility predicate
(FUN_GAMETOOLTIP_AURA_VISIBLE = 0x00534DF0), not the UnitBuff one
(0x00519860): the latter adds a per-player immunity-bitmap check off record
+0x2B0, so the two index spaces are not interchangeable. Both decompiled to
confirm the walks being mirrored.

The aura tooltip builder only ever receives spellId / level / stacks, so a
debuff parked in a buff slot renders identically through SetUnitBuff.

Note this is deliberately MORE than the engine does: stock UnitBuff /
UnitDebuff split by slot range and show a spilled debuff as a buff. Retail's
contract is the aura's actual polarity, and the descriptor already carries
it, so we report that.
2026-09-04 03:58:14 -05:00
Brues fdbe66b057 fix(aura): let a duration rule edit an aura its own trigger creates
Turtle's Bestial Wrath gives the hunter's pet Scent of Blood for 18s, but
C_UnitAuras reported 8s and then dropped the timer entirely while the buff
was still up.

Server-side (tortoise-wow spell_hunter_bestial_wrath) Bestial Wrath neither
applies the aura nor carries its duration on the wire: effect 0 is
TRIGGER_SPELL(Scent of Blood, 52995), and the script then stretches the
holder that trigger just created via SetAuraMaxDuration/SetAuraDuration.
Both are plain field writes, and 1.12's only duration packet is scoped to an
aura-bearer that is a PLAYER, which a pet is not -- so the client never hears
the 18s and keeps the 8s base it computed when the aura landed. Exactly the
class of edit Aura::Source's duration rules exist to mirror; two things had
to change before one could express it.

The affected-aura selector demanded a SpellFamilyFlags overlap, and every
Turtle custom spell carries flags of 0 (308 in the hunter family alone), so
no mask could ever name this aura. It now takes a family-flag overlap and/or
a SpellIconID, at least one of the two -- an icon is shared across a spell's
whole rank ladder, so it stays as rank-proof as a flag, and icon 2245 picks
out exactly the four Scent of Blood records and nothing else. Registrars
reject the mask-0 + icon-0 rule that would match a whole class family, and
RefreshDurationByFamily takes the same invariant so the two entry points
cannot disagree about what they match.

A trigger can also CREATE the aura it edits, which the immediate-apply model
could not see. The trigger's SMSG_SPELL_GO arrives before the triggered
cast's, so editing at trigger time either matches nothing or is overwritten
moments later when the triggered cast stores its own base duration -- the
edit is lost either way. Idempotent ops now ARM the target as well, and the
next matching store re-applies the edit, from the cast path or the
application path, whichever the aura arrives on. Only refresh and set arm:
re-running those lands on the same value, while reduce would shave twice and
remove would kill an aura that was legitimately re-applied, so Conflagrate
behaves exactly as before.

The rule reads Bestial Wrath's own duration from the client's spell data
instead of hardcoding the server's 18s, so a rebalance that patches the DBC
carries over on its own.

Fixes brues-code/pfUI#50
2026-09-02 19:39:59 -05:00
Brues bd1bd9f5d8 feat(aura): slot-batching API and lazy caster match
C_UnitAuras.GetAuraSlots / GetAuraDataBySlot / UnitAuraBySlot: enumerate a
unit's auras once into opaque slot ids and fetch each by id, so a full scan
walks the aura array once instead of once per index (the by-index getters
re-walk from slot 0 on every call). Slot ids cover live descriptor slots,
the stealth / range cache fallback, and the out-of-range group array, so
the slot path keeps every source the by-index path had.

GetAuraSlots also takes a table as a 5th argument (ClassicAPI extension)
and fills it in place, returning `continuationToken, n`. Lua 5.0 allocates
an `arg` table for EVERY vararg call (luaD_precall 0x006F6050 ->
adjust_varargs 0x006F6200 -> luaH_new, verified in Ghidra), so a Lua helper
receiving the retail multi-return costs one table per batch. The fill form
keeps per-frame scans allocation-free; AuraUtil.ForEachAura / FindAura use
it with a per-nesting-depth buffer pool instead of retail's vararg helpers.

The descriptor walkers (FindNthSlot, FindSlotBySpellID/Name, GetUnitAuras)
now evaluate IsPlayerCast only when the filter restricts on caster. It
scans the Aura::Source cache (~1000 entries in a raid) and was paid for
every populated slot on every call, PLAYER token or not.

Cache-fallback eligibility is centralized (EligibleFallbacks /
EligibleGroupFallbacks) so the by-index, bulk, and by-slot paths share one
ordering, which is the ordinal an opaque cache slot id encodes.
2026-09-02 16:19:31 -05:00
Brues b6698ecc7e docs(readme): list UnitCreatedBySpell in the Unit row
Already documented in docs/API.md; only the README summary table was
missing it. Inserted in alphabetical position.
2026-09-02 02:34:37 -05:00
Brues e123a6facc fix(cast): fire CHANNEL_STOP/START on same-spell re-channel
Recasting a channel while already channeling it (e.g. Fishing while
fishing) left the cast bar frozen: PollPlayer detected a new channel by
spellID only, but a re-channel keeps channelSpellID == g_chanSpell and
the continuous channel never lets +0x228 (and thus g_channel.spellID)
return to 0 in between, so neither CHANNEL_STOP nor CHANNEL_START fired.

Also flag a same-spell re-channel when the channel was re-stamped
(channelStartMs advanced) AND a fresh CMSG_CAST_SPELL is pending for the
spell (g_pendingGuid). Both are required so neither false-fire trap
triggers: the two-stamp-per-start sequence (SMSG_SPELL_START then
MSG_CHANNEL_START) is absorbed because the first CHANNEL_START already
consumed g_pendingGuid, and a rejected recast (SPELL_IN_PROGRESS) never
re-stamps so channelStartMs is unchanged.
2026-09-02 02:05:55 -05:00
Brues 695077b6da refactor(callbacks): lighter EventRegistry dispatch
Modernize the frame-event forwarder: OnEvent now takes its (self, event, ...)
positionally (modern script args, on by default) and forwards straight to
TriggerEvent — dropping the DispatchGameEvent hop and the unpack(arg) repack,
and forwarding the exact arg count instead of a padded arg1..arg9 (which
silently dropped args for events that emit more than nine). A fallback reads
the event/arg globals when SetModernScriptArgs is off, so the registry stays
robust to that switch.

Keep the ordinary {[event]=count} ref-count table rather than storing counts
as frame attributes: SetAttribute is heavier per call (it lowercases the name,
runs the secure-attribute parsing, and fires OnAttributeChanged) for the same
steady-state memory, so a plain table is lighter on the register/unregister
path.
2026-08-31 16:51:17 -05:00
Brues 4d744b6638 feat(interface): INTERFACE_VERSION global constant
Publishes INTERFACE_VERSION (11200 on this client) — the client interface/TOC
version, read from the engine's own accessor (FUN_ADDON_CLIENT_INTERFACE_
VERSION, the same value the addon loader compares each `## Interface:`
against) rather than a literal. A global number re-published every /reload
via ModuleAutoRegister, mirroring CLASSIC_API_VERSION, since it is a fixed
client constant.

Verified in-game: /dump INTERFACE_VERSION -> 11200.
2026-08-31 15:06:01 -05:00
Brues c2a4cbdf27 docs: drop WoW-version and vanilla-gap phrasing
The docs are a modern-API backport onto 1.12, so "added in <patch>" and
"vanilla 1.12 lacks/does X differently" are implied by the doc existing —
they were noise. Swept both across docs/API.md and README.md: dropped the
version-introduction and vanilla-limitation clauses, and where a version note
was the only thing explaining a hardcoded/degenerate return value, kept the
reason without the version. Behavior notes and "ClassicAPI extension"
provenance are unchanged. The large line count is mostly paragraph reflow
after clause removal; no API names, signatures, or code examples changed.
2026-08-31 13:23:09 -05:00
Brues d30ae53fbf feat(editbox): ClearHistory
Empties the up/down input history. The engine's SetHistoryLines internal
(FUN_0077cd90) frees the whole history ring when called with 0, so clear =
free (0) then reallocate at the saved max — dropping every entry and resetting
the write position while keeping the line limit, so the box keeps recording
afterward (matching modern semantics, not "history disabled"). No-op when the
box has no history.

New offsets: OFF_EDITBOX_HISTORY_MAX (+0x388, the ring capacity GetHistoryLines
reads), FUN_EDITBOX_SET_HISTORY_MAX.

Verified in-game: AddHistoryLine + ClearHistory leaves GetHistoryLines
unchanged and the up-arrow history empty; new lines still record.
2026-08-31 11:14:34 -05:00
Brues 8f32955823 feat(editbox): SetHighlightColor / GetHighlightColor
The engine paints the text selection with three Texture regions (start-line
+0x350, middle-block +0x354, end-line +0x358; positioned by FUN_0077d950),
and their vertex color IS the highlight color — there's no single color field.
So SetHighlightColor packs {b,g,r,a} and writes it to all three via the
engine's own generic region color setter (FUN_0077f750, the same one behind
Texture:SetVertexColor / FontString:SetTextColor), and GetHighlightColor reads
the first region back through the matching getter FUN_0077f8c0 (the read half
of Texture:GetVertexColor). The blinking caret is a separate region (+0x3d4),
left untouched.

Colors are 0..1, alpha defaults to 1. New offsets: FUN_REGION_GET_COLOR,
OFF_EDITBOX_HIGHLIGHT_REGION; FUN_FONTSTRING_SET_COLOR relabeled as the
generic region color setter it always was.

Verified in-game: SetHighlightColor(1,0,0) reads back 1 0 0 1 and a selection
paints red.
2026-08-31 10:53:04 -05:00
Brues 2778643f4f feat(editbox): GetUTF8CursorPosition, ClearHighlightText, HasFocus, HasText
Round out the EditBox method backports alongside Set/GetCursorPosition, all
reusing state the engine already maintains:

- GetUTF8CursorPosition — caret as a character index (vs GetCursorPosition's
  byte offset), via the engine's own byte->char counter FUN_0077bc80.
- ClearHighlightText — drop the selection but keep the caret (collapse
  selStart/selEnd onto the cursor + highlight-dirty bit). Vanilla can only
  clear a selection with HighlightText(0,0), which yanks it to offset 0.
- HasFocus — pointer identity against VAR_FOCUSED_EDITBOX (the global the
  engine's SetFocus writes / ClearFocus clears).
- HasText — text byte length (+0x338) is non-zero.

Registered on the EditBox method registry, so only EditBox frames dispatch
them. New offsets: OFF_EDITBOX_TEXT_LENGTH, FUN_EDITBOX_COUNT_CHARS.

The module now covers cursor / selection / focus / text-state, so it moves
from editbox/Cursor.cpp to editbox/Methods.cpp (namespace EditBox::Methods).
Documented in docs/API.md and the README under the Frame widget section.

Verified in-game: SetText+SetFocus reports HasFocus/HasText true and both
cursor getters 5; an empty box reports both predicates false.
2026-08-31 10:38:35 -05:00
Brues 3b60ca4094 docs(readme): drop addon-Lua functions from the DLL call table
The "In-game Lua calls" table lists what the DLL registers in C++, but it
included functions provided by the bundled !!!ClassicAPI addon's Lua:
AuraUtil.* and the secure-template Frame functions (SecureCmdOptionParse,
Register/UnregisterStateDriver, Register/UnregisterAttributeDriver,
Register/UnregisterUnitWatch, UnitWatchRegistered, SecureButton_GetAttribute,
SecureButton_GetUnit). Remove those; keep the C++-backed entries
(SetAttribute/GetAttribute/ClearAttribute, PreClick/PostClick, GetClickFrame).
2026-08-31 10:25:45 -05:00
Brues c20be0cef1 feat(editbox): SetCursorPosition / GetCursorPosition
Vanilla's EditBox registry has 48 methods (HighlightText, Insert, SetText,
...) but no cursor accessor, so modern addons that set text then place the
caret error with "attempt to call method 'SetCursorPosition' (a nil value)"
(reported: TwitchEmotes autocomplete).

The caret already exists in the engine — a byte offset at editbox+0x36c —
with reusable primitives: FUN_0077e360 clamps and sets it (the engine's own
"restore caret" step in the insert path), FUN_0077ccf0 collapses the
selection onto it. Modern SetCursorPosition is byte-based too, so it maps
1:1. New EditBox::Cursor module registers both methods on the EditBox method
registry (0x00CF5378); registering under that context means only EditBox
frames dispatch them, so `this` is always a real CSimpleEditBox. Set path:
clamp+set the caret, collapse the selection, flag the highlight dirty.

Verified in-game: SetText + SetCursorPosition + GetCursorPosition round-trips
and the caret lands at the requested offset.
2026-08-31 10:16:37 -05:00
Brues 1ad6b57202 fix(table): writer-side mark for deliberate nil appends
The v1.12.8 gap heuristic (keep the stored length when it overshoots the
border by exactly one) protected `table.insert(t, nil)` slots (#36) but
broke every 5.1-dialect table that is stale by exactly one — a
pairs-cleared one-element table, or a recycled table whose previous life
was one slot longer. Tablet-2.0's del()/copy() pool produces the latter on
every tooltip refresh, so FuBar/Ace2/Tablet menus and tooltips shifted by
one with a nil hole at slot 1. The two states are byte-identical, and both
consumers reach the heal through table.insert — neither the table nor the
caller can split them.

Only the writer knows which dialect the table speaks, and the write is
observable: co-hook the engine's table.insert (FUN_LUA_TABLE_INSERT =
0x7FB6B0, verified against the table-lib luaL_reg pair in .data and a
decompile matching 5.0.2 tinsert line for line) and record
{table -> stored length} in a weak-keyed registry table whenever the
two-arg form appends a literal nil. Rule 3 now heals every stale table to
the border (the 5.1 answer) and keeps the stored length only when the gap
is one AND the mark still matches. Stale marks die on their own: any later
insert/remove moves the stored length off the recorded value, and the weak
key collects with the table.

Verified in-game with a 21-test suite (directed regressions for
#29/#36/#39, byte-identical twin discrimination, metamethod isolation,
coroutine-side marking, and a seeded differential fuzzer against an
executable model of the contract): 15/21 on the broken build, 21/21 with
the fix, #36's nil-append cases among the passes both times.

New plumbing: LUA_SET_METATABLE (0x6F4020, from LuaCAPI.md) and
Game::Lua::SetMetatable for building the weak mark table from C.

Fixes #39
2026-08-31 01:56:03 -05:00
Brues 993c82cca7 refactor: route unit-token resolution through Game::ResolveUnitToken
Sweep the ~35 modules that each hand-rolled a `ResolveUnitToken_t` typedef
plus `reinterpret_cast<…>(Offsets::FUN_RESOLVE_UNIT_TOKEN)` onto the shared
`Game::ResolveUnitToken` helper. Behavior-identical — it is the same engine
function — and net -87 lines. The typedef now lives in exactly one place
(Game.cpp).

unit/Position.h is a header, so it gains an `#include "Game.h"`; every other
touched file already pulled Game.h in. No offsets, logic, or unrelated
typedefs were changed.
2026-08-30 16:57:04 -05:00
Brues 94e77ef5af feat(unit): UnitCreatedBySpell + consolidate the unit-token resolver
Add `UnitCreatedBySpell(unit)` — the spell that summoned a unit (a totem's
totem-drop spell, a pet/guardian's summon spell), read from the unit's
UNIT_CREATED_BY_SPELL descriptor field (byte +0x230). It is the same field
the engine's unit-title builder consults to pick the Pet/Minion/Guardian/
Creation title, and it is broadcast, so it resolves for any unit in range.
This is the summoning spell, distinct from the (server-only) spell a totem
casts.

Also add a single `Game::ResolveUnitToken(token)` helper that wraps the
engine token->CGUnit* resolver, and route unit/Pet.cpp through it plus the
Game::Read<T> field accessors — removing the hand-rolled ResolveUnitToken_t
typedef and raw reinterpret_casts from this module. The name was already
referenced in Offsets.h and CLAUDE.md but had never been implemented.
2026-08-30 16:43:54 -05:00
Brues 1458d60b51 feat(spell): GetSpellInfo accepts a spell name, link, or "Name(Rank N)"
The shared spell-arg resolver errored on any non-number arg1, so
GetSpellInfo("Fireball") raised instead of resolving. Match retail's
full argument set: arg1 may now be a spellID, a spell name, or a spell
hyperlink.

A name resolves against the player's then pet's spellbook (retail's
scope) and returns the highest rank you know; an unknown name returns
nil rather than raising. A trailing "(Rank N)" subtext pins that exact
rank -- the vanilla SpellName(Rank N) form CastSpellByName uses, with a
space before the paren tolerated. A link's embedded spellID is parsed
directly, so it works for any spell, learned or not.

Because GetSpellLink / IsPassiveSpell / IsHarmfulSpell / IsHelpfulSpell
share this resolver, they gain the same name and link forms.

Verified in-game: "Mind Blast" -> rank 9 (max known); "Mind Blast
(Rank 8)" and "Mind Blast(Rank 8)" -> rank 8; "Mind Blast (Rank 99)"
-> nil.
2026-08-30 13:36:07 -05:00
Brues 8b106ae0d6 fix(addons): define global HookScript for ModernSpellBook
ModernSpellBook's MSB_Spellbook.lua re-hooks its "show all ranks"
checkbox by calling HookScript(frame, "OnClick", handler) as a GLOBAL.
That global never existed on any client -- HookScript has always been
the widget method frame:HookScript, which our DLL provides -- so the
call errors with "attempt to call global 'HookScript' (a nil value)".

Define the global in AddOnCompat, forwarding to the method, gated on the
addon being present so the global namespace stays clean otherwise.
2026-08-30 08:52:01 -05:00
Brues 3c4d4eda5f docs(readme): link the Feature column instead of trailing "See […]"
Move each feature table's docs/API.md link onto the Feature name in
column one and drop the "See [x]." tail from the Effect column. Rows
with no docs section (Inline textures, Tooltip line cap) are unchanged.
2026-08-29 19:20:59 -05:00
brues-code 6aea4a1752 Retail-like /reload: new addons, new files, ## metadata edits, deletions (#37)
* feat(addons): retail-like /reload — new addons and new files load

Two engine limitations kept anything created after boot from loading
until a client restart:

1. File visibility: every relative-path read resolves through a
   loose-file hash index built once at boot (FUN_00646EA0, latched);
   the archive layer's live disk probe is dead code (DAT_00865B44
   ships 1, boot clears it) and writes never register. New files -
   including a new addon's TOC and first-ever SavedVariables - were
   invisible until restart.
2. Registry membership: the addon registry is built once at login;
   new folders are never walked.

Addons::Rescan runs per /reload from the ModuleAutoRegister callback
(before the AddOns.txt re-read, progress count, and load pass) and:

- re-indexes Interface\AddOns + WTF\Account with the engine's own
  dedup-safe boot indexer (FUN_VFS_INDEX_SUBTREE) - new files in
  existing addons then load natively, since the per-addon loader
  re-reads the TOC from disk on every load pass; a newly installed
  addon's first SV save now also survives /reload;
- replays login scan walk #2 verbatim (FUN_ADDON_SCAN_DISK_DIRS with
  the engine's own dir-to-parser callback) so new folders register as
  complete normal entries via the dedup-guarded TOC parser;
- mirrors the two structures the login scan would have filled:
  reverse-LoadWith links (tail-loop grow+append, restricted to pairs
  involving a new entry - the engine's lists have no dedup) and the
  flat GetNumAddOns display array (FUN_0051DA70 phase 2: filter byte
  +0x29, engine grow + qsort comparator).

Append-only by design: no teardown, no eviction, no mutation of
existing entries - the prior hot-reload attempt died re-running the
login-only FUN_ADDON_INIT teardown mid-reload. Still login-only
(no safe mechanism): ## metadata edits of already-registered addons
and folder deletions.

Also centralizes Embedded.cpp's addon-entry field constants into
Offsets.h now that a second module reads them.

* refactor(addons): centralize the registry list walk; record dedup-guard probe

The intrusive linked-list walk (head at [VAR_ADDON_LIST_HEAD], next at
entry + [VAR_ADDON_LIST_CTRL] + 4, low-bit-1/NULL sentinel) was
implemented twice -- a template in Rescan.cpp and an inline loop in
Embedded.cpp's FinalizeEmbeddedEntry. Move it to addons/Registry.h as
Addons::ForEachEntry, with a void- or bool-returning visitor (false
stops early). The early stop is load-bearing for Embedded: re-linking
the found entry to the head invalidates the current next-pointer, so
the walk must not continue past it -- the shared helper makes that
contract explicit.

Also record the TOC-parser dedup-guard verification in Rescan.cpp's
scan-call comment: the guard is the parser's FIRST block (hash lookup +
name compare, early return before the TOC path is even built), and both
the Storm hash (uppercases a-z, folds '/'->'\') and the SStrCmpI compare
are case-insensitive -- so the per-/reload scan replay can never re-read
or mutate a registered entry's ## metadata, and a case-renamed folder
matches its existing entry instead of registering a duplicate.

* feat(addons): /reload re-parses edited ## metadata and drops deleted addons

The TOC parser's dedup guard makes a registered entry's ## metadata
read-once: an edited ## SavedVariables: / ## Dependencies: / any ##
line never re-parsed until re-login, and a deleted folder's entry
lingered in the addon list. Both were documented login-only limits of
the retail-like /reload feature.

Rescan's new step 1.5 closes them with evict + re-register, all engine
machinery:

- Change detection: FNV-1a over the TOC's ## lines only (BOM skipped
  like the parser, line terminators excluded), read through the hooked
  FUN_FILE_READ so flavor selection is hashed exactly as the parser
  reads it. File-reference edits never trigger the evict path -- the
  load pass re-reads those natively. Baselines seed at login and for
  newly registered folders in the same Run(), so an edit is always
  diffed against what was actually parsed.
- Evict: scrub the victim from every other entry's reverse-LoadWith
  list (the one reference the destructor cannot clean -- the loader's
  post-ADDON_LOADED loop dereferences those entries), then call the
  engine's own complete per-entry destructor FUN_ADDON_ENTRY_DESTROY
  (0x005200A0, __stdcall, RET 4; vtable slot 0 of the registry node
  factory at [0x00BE1B60], dispatched per entry by the login teardown).
  Verified by decompile: frees every owned allocation (name, dep/SV
  arrays + buffers, reverse-LoadWith buffer, the ## metadata table) and
  self-unlinks from both the intrusive list (FUN_00520A60, no-ops when
  already unlinked) and the hash bucket chain.
- Re-register: feed the name back to FUN_TOC_PARSER -- the dedup guard
  now misses and the entry rebuilds from the edited TOC exactly like a
  fresh registration. Refreshed entries join the existing
  FixupReverseLoadWith/RebuildDisplayArray fix-ups; the refresh runs
  before the before-snapshot so an address-reusing allocator cannot
  make the added-diff double-count or miss one. Any eviction forces the
  display-array rebuild (it holds the dead entry's freed name pointer
  until then). Victims are collected during the walk and processed
  after it -- the dtor zeroes the link node under the iterator.
- Deletion: an unreadable TOC evicts without re-registering; a folder
  the scan still finds simply re-registers the same reload.

Exempt: !!!ClassicAPI (Addons::Embedded owns its entry) and ## Secure:
/ SMSG-managed entries (the parser cannot restore packet-delivered
state; new OFF_ADDON_ENTRY_SECURE = 0x28, parser write site verified).

Verified in-game: ## X-Test metadata edit picked up across /reload
(GetAddOnMetadata returns the new value), SavedVariables list edit
takes effect, folder deletion drops the entry from GetNumAddOns, folder
restore re-registers it, and a no-change /reload is a pure hash-compare
no-op.

* fix(addons): address review — hash commit timing, evict flag, README row

- README: the /reload row said `##` metadata edits still need a
  re-login — stale from before the metadata-refresh step landed. Now
  matches docs/API.md: edits take effect, deleted folders drop from
  the addon list.
- Rescan: commit g_metaHash only after the re-registration actually
  happened, so a failed resolve/parse retries next /reload instead of
  silently absorbing the edit forever; a victim the parse cannot
  restore is erased (treated as deleted) so a reappearing folder
  re-seeds.
- Rescan: RefreshChangedMetadata returns whether anything was actually
  destroyed, not whether victims were collected — no display-array
  rebuild when every victim failed to resolve.
- Rescan: comment the load-order consequence of evict + re-register
  (the fresh entry appends at the list tail; declared deps still
  force-load first).
2026-08-29 19:16:34 -05:00
Brues 6304a253dd feat(aura): Dark Harvest tick compression; channel-aura pushback restamp
Turtle's Dark Harvest (52550-52552) makes the caster's Affliction dots on
the channel target tick 30% faster - and live preserves each dot's tick
COUNT, so the dot's real remaining time drains at 130% rate during the
overlap and it falls off early with no client-visible aura change (report:
gone with ~3 s still showing; Cursive's community calibration models the
same `remaining -= 0.30 x overlap`). tortoise-wow's recreation only
re-times tick timers and leaves holder duration alone, which does NOT
reproduce the early fall-off - so the compression math mirrors live, while
the affected-set predicate mirrors the server script
(IsDarkHarvestAfflictionPeriodicAura): same-caster warlock-family auras
matching the Corruption/Drain Life/CoA/Drain Soul/Siphon Life/CoD mask
with a periodic damage/leech effect (the aura-type gate is load-bearing:
Turtle's Atrocity shares Corruption's 0x2 bit but is a proc aura - DBC
sweep verified; the trigger mask 0x4000000000 selects exactly the three
DH ranks).

Aura::Source::AddTickCompression: while a caster's trigger-mask aura is
live on a target (its cache entry's lifetime: SpellGo -> OnAuraRemoved
eviction), that caster's matching entries drain an extra pct% of real
time. Anchored math (expiration = anchor - elapsed x pct/100) so frame
pacing can't drift it; an external re-stamp (dot recast, duration mod)
re-anchors from the fresh value. Caster-paired like the server, so an
observed party warlock's DH compresses their dots' timing too. ~1/s
UNIT_AURA nudges for event-driven consumers, final nudge at release.
Registered Turtle-gated in turtle/DarkHarvest.cpp with the percent read
from the rank record's EffectBasePoints[1]+1 (-31 -> 30, fallback 30).

Also: MSG_CHANNEL_UPDATE now re-anchors the cached target-side expiration
of the player's channel-applied auras (Aura::Source::RestampPlayerChannel).
The server shortens every hit target's holder on channel pushback
(Spell::DelayedChannel -> DelaySpellAuraHolder) and only tells the caster
via the new remaining time, so the SpellGo-stamped expiration read late by
the accumulated pushback; self-target holders were already corrected
natively via SMSG_UPDATE_AURA_DURATION. This also bounds the compression
window under pushback for free.
2026-08-28 21:56:02 -05:00
Brues fbe40743c0 fix(table): keep length on a deliberate single nil append
The stale-length heal (Length.cpp) could not tell a cleared-and-reused
table from a deliberate table.insert(t, nil): both leave the stored
length pointing at a nil slot with no explicit n field, but they want
opposite answers. Rule 3 healed both, so the next table.insert on a
single-nil-appended array wrote over the nil and shifted every later
element down by one -- silent corruption in Ace2-era addons (Waterfall's
{key1,val1,...} arg builder inserts a nil whenever an option has no
passValue, the common case), with no error anywhere.

The issue's preferred fix -- make table.insert always use the raw stored
length -- reintroduces #29: Dewdrop clears `values` with a pairs loop +
no-op table.setn, then rebuilds it via table.insert, and that append is
exactly what the heal fixed. Both consumers reach the heal through
table.insert, so the caller cannot distinguish them; only the staleness
gap can. A cleared table is stale by many slots; a deliberate nil append
is off by exactly one. So heal only when the stored length overshoots
the border by more than one slot, and keep it otherwise.

Verified in-game via CAPI_DemoTableLengthHeal (AddOnCompat.lua): nil
append preserved (getn=3, t[2]=nil, t[3]=b), Waterfall pairs intact, and
the cleared-table rebuild still heals to slot 1.

Fixes #36
2026-08-27 15:37:54 -05:00
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
Brues a2d25cef8b fix(object): gate ByGuid on the registry root to survive out-of-world calls
The engine resolver FUN_OBJECT_RESOLVE_BY_GUID funnels unconditionally
into FUN_00464890, whose first action loads the registry root from
[VAR_LOCAL_PLAYER_PTR] and derefs its +0x24 hash mask with no null
check. That root is NULL out of world (login, loading screens, logout
teardown), so any resolve reaching it mid-transition dies with ERROR
#132 (MOV EAX,[EDX+0x24], EDX=0) - hit in the wild by Aura::Source's
SMSG_SPELL_GO path, whose Store/Claim eviction consults
DescriptorListsAura while packets still dispatch during transitions.

Promote the readiness predicate from Unit::TokenObserver's private
RegistryReady into Object::RegistryReady (object/Resolve.h) and gate
ByGuid on it, returning nullptr out of world. That is both the
contract ByGuid's comment already promised ("pre-world ... safe from
any context") and provably behavior-preserving: a zero result is the
engine's own handled "not found" case (verified in Ghidra - 0x468460
null-checks the node; 0x464870 itself returns 0 for guid==0), and out
of world the call had no non-crashing outcome. Every ByGuid call site
already null-checks. TokenObserver now delegates to the shared helper.

Fixes #34
2026-08-24 08:43:03 -05:00
Brues c3c79356be fix(tooltip): clear per-tooltip OnTooltipSet* cells on reload
Tooltip::SetEvents kept its handler cells in a fixed 32-entry table keyed
by tooltip pointer, assuming tooltips are permanent. They are not: every
/reload (and logout) destroys and recreates the tooltip objects, so the
table gained ~2 dead cells per reload with no eviction. After ~18 reloads
it filled, the resolver co-hook returned 0 for new tooltips, and
SetScript/HookScript failed with "doesn't have a 'OnTooltipSetItem'
script". Worse, a stale cell whose address the allocator recycled into a
new tooltip fired its old handler ref into the reset Lua registry - a
dead-epoch ref, garbage call, crash.

Add Tooltip::SetEvents::PrepareForReload() - a full cell-table clear -
and call it from FrameScript_Initialize_h alongside the other per-reload
resets. The clear is semantically right, not just leak plumbing: handler
refs never survive the Lua reset, so post-reload every cell held garbage
regardless; addons re-register in OnLoad and get fresh cells.

Fixes #33
2026-08-24 08:17:12 -05:00
PeapandBrues 6ae3299041 Add Secure Action Button Templates and Comma-Split Support (#32)
* feat: port SecureActionButtonTemplate + CreateFrame comma-split

- Hook Script_CreateFrame (0x007060B0) to split comma-separated template
  strings. Vanilla only accepts a single template name; modern addons pass
  lists like 'UIPanelButtonTemplate, SecureActionButtonTemplate'.

- Add SecureTemplates.xml registering SecureFrameTemplate,
  SecureActionButtonTemplate, SecureUnitButtonTemplate, and
  InsecureActionButtonTemplate as real virtual XML templates.

- Add SecureTemplates.lua with modifier/button attribute resolution helpers
  (SecureButton_GetModifiedAttribute, GetModifierPrefix, GetButtonSuffix,
  GetModifiedUnit) and OnClick dispatchers.

- Remove duplicate SecureButton_GetAttribute/GetUnit from SecureStateDriver.lua
  (now provided by SecureTemplates.lua which loads earlier).

- Include SecureTemplateTest debug addon for verification.

* Include AuraUtil.lua in ClassicAPI.toc

mistake from merge

* fix(frame): apply every template in a CreateFrame comma list

Vanilla 1.12 CreateFrame resolves the 4th arg as a single template name.
The initial comma-split hook only applied one template, and its tokenizer
dropped everything after the first entry for the common "A, B" format
(writing the NUL terminator clobbered the delimiter the advance step
checked). Rework it into real multi-inheritance:

- SplitTemplates: record whether a comma was hit before writing the
  terminator, so "A, B" / "A,,B" / leading-comma inputs all split.
- CreateFrame_h: build the frame with the first resolved template through
  the engine, then graft each remaining template onto the created object
  with the engine's own inherit primitive - content (frameObj->vtable[+8],
  FUN_00769820) and child <Frames> ((frameObj+0x24)->vtable[+8],
  FUN_0076a060), the two __thiscall calls the builder FUN_006ee280 emits
  per inherited node. Regions, backdrop, attributes, script handlers, and
  child frames all apply, in left-to-right override order; OnLoad runs once.
- Offsets: add FUN_FRAMESCRIPT_STATUS_RESET (the XML-build error
  accumulator reset, __thiscall) and document the status object layout.

Also fix the relocated SecureButton_GetUnit/GetModifiedUnit pet-token
pattern: "[^%%d]"/"[%%d]" matched literal % and d instead of the digit
class %d, so raid1pet never normalized to raidpet1. Restore single %d.

Verified in-game: a comma list applies both templates' regions/text in
either order; pet-suffix normalization works.

* refactor(secure): tidy SecureTemplates review follow-ups

- Guard RunMacroText (absent on this client) so a type=macro button with
  only a macrotext attribute no-ops instead of erroring.
- Honor a SecureUnitButton_OnLoad menufunc: the menu/togglemenu action now
  calls self.menu when set, else falls back to ClassicAPI_ToggleUnitMenu
  (self.menu was previously stored but never read).
- InsecureActionButtonTemplate now inherits SecureActionButtonTemplate
  instead of duplicating its OnClick block.
- Drop the committed SecureTemplateTest debug addon; test harnesses live in
  the WoW install, not the repo.

* refactor(secure): make Frame::Attributes the single click dispatcher

The Lua SecureActionButton_OnClick from the secure-templates work
duplicated the native C++ dispatcher and only backfilled the verbs C++
lacked. Fold those into DispatchVerb so C++ is the sole dispatcher for
every secure button (template or plain SetAttribute), and drop the Lua
redundancy.

- DispatchVerb gains `action` (UseAction), `pet` (CastPetAction), `click`
  (forward to the frame in the `clickbutton` attribute via
  delegate:Click), and a custom fallback (a function stored as a raw
  field on the frame named by the verb). `menu`/`togglemenu` now cancels
  spell-targeting when a spell is on the cursor (the old
  SecureUnitButton_OnClick nuance).
- Numeric spell IDs work as the `spell` attribute: SetAttribute("spell",
  id) (a Lua number) or a numeric string cast the EXACT rank by ID via
  the spellbook-slot resolver (Spell::AtUnit::CastByID at a unit,
  Spell::AtCursor::DispatchSpellCast with none) - not name resolution,
  which fired the highest known rank.
- CopyAttr coerces a number-valued attribute to its digits, so numeric
  IDs also read for `item` and any other string attribute.
- Remove SecureActionButton_OnClick / SecureUnitButton_OnClick from
  SecureTemplates.lua, simplify SecureUnitButton_OnLoad, and strip the
  <OnClick> from the templates (plain Button templates now; the C++
  closure installs on SetAttribute("type*")). The attribute-reader
  helpers stay - public API and SecureStateDriver depend on them.

* fix(frame): restore the Lua stack after the multi-template graft

The comma-template graft can run a grafted template's child-frame OnLoad,
and in this hook-saturated environment a nested Lua op can shift the stack
slot the caller reads its return value from. Snapshot lua_gettop after the
engine build and restore it once the graft finishes, so the caller always
reads back the frame the engine left. Mirrors the Tooltip::SetEvents
save/restore discipline.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-08-23 18:15:27 -05:00
Brues f97379795d Localize UnitAura call for performance 2026-08-23 13:45:02 -05:00
Brues 3c6b449df5 feat(aura): zero-alloc positional accessors + AuraUtil
C_UnitAuras.GetAuraDataByIndex builds a fresh Lua table per call, churning
Lua 5.0's mark-sweep GC when addons scan many units' auras in an OnUpdate
loop. Add Blizzard's own answer: positional (multi-return) accessors plus the
AuraUtil helper library, so hot loops allocate nothing.

DLL: C_UnitAuras.UnitAura / UnitBuff / UnitDebuff return the 15-value
Classic-Era UnitAura tuple with no table allocation. Built on a shared
Emit { Table, Positional } seam through PushEnriched -- selection, cache
fallback, out-of-range group, and timing resolution are the same code as the
table path; only the terminal leaf differs (BuildTable vs the new
PushPositional, both fed by an extracted ResolveDisplay). Namespaced under
C_UnitAuras so the native UnitBuff/UnitDebuff globals keep their vanilla
short return.

Addon: Util/AuraUtil.lua backports ForEachAura / FindAura / FindAuraByName /
UnpackAuraData over those accessors. ForEachAura (non-packed) and FindAura
both source from the positional accessor, so they allocate nothing per aura --
FindAura included, where retail itself allocates a table per aura scanned.

Verified in-game: positional values match GetAuraDataByIndex field-by-field
(#12 isBossDebuff / #13 castByPlayer differ by design, matching retail's
UnitAura-vs-AuraData divergence); ForEachAura counts match GetUnitAuras; and
the positional path allocates ~0 KB/scan where the table path allocates
~1.3 KB per aura.

Fixes #30
2026-08-23 12:16:53 -05:00
Brues f000fd6ed7 build(release): emit matched PDB and ship crash symbols as a zip
Add /Zi (compiler) + /DEBUG (linker) so the Release build produces a
line-level ClassicAPI.pdb alongside the existing linker map. /OPT:REF and
/OPT:ICF stay explicit so /DEBUG does not re-enable dead code and the
shipped DLL does not grow; the PDB is a separate file matched to the DLL
by signature.

CI release runs now bundle the pdb + map into one crash-symbols zip
attached to the release, replacing the loose renamed map. The zip name is
kept unappealing to normal players and carries the tag so a dev can match
symbols to the exact build.
2026-08-23 10:40:03 -05:00
Brues 7960266969 feat(addon): add [known] macro conditional to SecureCmdOptionParse
ClassicAPI extension (not a 3.3.5 conditional). [known:spellID] uses
IsPlayerSpell (broad knowledge: spellbook, talents, recipes, racials);
[known:name] falls back to a spellbook name scan via GetSpellName, since
1.12 has no name-to-id resolver -- so a name matches castable spellbook
entries only.

Verified in-game: [known:133] false on a non-Mage, [known:45651] and
[known:Aspect of the Viper] both true by id and by name.
2026-08-23 02:42:48 -05:00
Brues 85ed4eb378 feat(addon): backport SecureStateDriver + SecureCmdOptionParse
RegisterStateDriver / RegisterUnitWatch / attribute drivers, driven by a
Lua SecureCmdOptionParse whose macro-conditional grammar is reverse-
engineered from the 3.3.5 client. Builds entirely on the shipped frame
attribute system -- no DLL change.

- MacroOptions.lua: parse-once cached SecureCmdOptionParse. 33 conditions
  mapped to 1.12 / ClassicAPI queries; states 1.12 lacks (flying, vehicle)
  are constant-false, an unknown keyword warns once and never matches.
- SecureStateDriver.lua: 0.2s-poll manager with instant event rescans,
  state-visibility Show/Hide, state-* attribute drivers, unit-existence
  watch, SecureButton_GetAttribute/GetUnit. Registers via plain tables +
  an immediate top-level resolve instead of the upstream attribute
  bootstrap, so the synchronous OnAttributeChanged recursion guard never
  swallows a target frame's handler.

Verified in-game: parser grammar, both drivers, and druid [stance:N] bar
numbering.
2026-08-23 02:05:35 -05:00
Brues 7f1e632b49 feat(texture): add MaskTexture object API with multi-mask and rotation
Backport frame:CreateMaskTexture plus texture:AddMaskTexture /
RemoveMaskTexture / GetNumMaskTextures / GetMaskTexture -- positioned,
rect-based masks, the object form later clients use (SetMask(path) stays
the simple single-shape form).

Positioned masks sample via texgen (object-space vertex position through
a per-unit texture matrix), the mechanism of the engine's own minimap
disc mask, so no vertex UV stream is consumed per mask. That lifts both
v1 limits at once:
- Up to 7 masks apply at once (device stage cap); a texture shows only
  the intersection of all of them.
- mask:SetRotation rotates the clip shape (folded into the matrix), and a
  mask can move/resize each frame, so the clip animates.

State is restored in a co-hook on the indexed submit (FUN_GX_PRIM_INDEXED)
the engine issues after the stream call, not inside the stream hook --
restoring earlier reverts the state the queued draw is flushed with.

Two incidental fixes: a SetTexCoord-cropped base now masks against the
same rect the engine's corner store uses, and a recycled mask region is
detached from every base still holding it.

Offsets.h: add the texgen / coord-transform / texture-matrix / state-journal
/ indexed-submit constants (decoded from the D3D9 backend state flush
FUN_005a2f00), and fix the FUN_GX_TEXUNIT_ENABLE/_DISABLE mislabel (they
are texture-matrix push/pop, not stage enable/disable).
2026-08-22 23:19:33 -05:00
Brues 71d193073a docs(readme): merge modern-behavior highlights; add nameplate and focus rows
Fold the thin "Modern text rendering" and "Modern addon loading" sections into
one "Modern client behaviors" table, and showcase two more event-driven
features:
- Event-driven nameplates: the C_NamePlate API + NAME_PLATE_UNIT_ADDED/REMOVED
  events + nameplateN unit tokens.
- Focus target: FocusUnit/ClearFocus, PLAYER_FOCUS_CHANGED, the focus /
  focustarget tokens, and the predefined FOCUSTARGET / TARGETFOCUS keybinds.

Highlights is now two groups: Lua 5.1 compatibility and Modern client behaviors.
2026-08-22 19:33:54 -05:00
Brues eda44e6d2d docs(readme): drop the SavedVariables highlight; move Installation below the reference
Two README tweaks:
- Remove the "SavedVariables loaded first" row from the Modern addon loading
  highlights -- compatibility plumbing, not a showcase feature. Still fully
  documented in docs/API.md.
- Move Installation below Full API reference, so the page leads with the whole
  showcase (features + the complete API surface) before install steps.
2026-08-22 19:22:00 -05:00
Brues 81f04c82ad docs(readme): trim Lua 5.1 highlights to the features worth showcasing
Drop the Table lengths and Environment protection rows from the Lua 5.1
compatibility table -- both are compatibility plumbing, not features anyone
installs for. They stay fully documented in docs/API.md. The showcase now
lists Syntax, String methods, and Script-handler arguments.
2026-08-22 19:15:21 -05:00
Brues 54516ad22b docs(readme): note the function/event count in the intro
Mention the scale up front (550+ functions and 50+ events) and bump the Calls
catalog summary from the stale "400+" to match. Counts are approximate on
purpose so they don't go stale on every addition.
2026-08-22 19:10:25 -05:00
Brues 7e784005b9 docs(readme): de-stiffen the intro and section blurbs
Rewrite the prose the restructure introduced so it reads naturally instead of
like a controlled-language manual: merge the intro's clipped two-sentence
opener, drop the "transparent / no API to call / addons use it automatically"
clunk from the Highlights blurb, and replace "The complete surface." in the API
reference intro. No structural or content changes.
2026-08-22 19:05:26 -05:00
Brues d12ff75c6c docs(readme): lead with Lua 5.1 highlights, collapse the full API catalog
Restructure so the flagship features surface first. The page used to open
with a ~60-row function catalog and buried the headline behaviors (Lua 5.1,
inline textures, modern addon loading) in a table at the very bottom.

- Promote the former "Behaviors" table to a top "Highlights" section,
  reordered Lua-5.1-first (syntax, string methods, table lengths, environment
  protection, script-handler arguments), then modern text rendering, then
  modern addon loading. No rows dropped.
- Move Installation up, ahead of the reference.
- Group the full catalog under "Full API reference" with each table (Calls,
  GlueXML, Macros, Console, Events, Globals, Unit tokens, Bindings) behind a
  <details> block. Content is byte-for-byte unchanged -- every function,
  event, global, and token stays in the file and all docs/API.md links are
  intact.
2026-08-22 18:56:35 -05:00
Brues 76043fcdef fix(compat): stub WorldMapDeathRelease for Cartographer under the 5.1 probe
Cartographer_Notes gates a WorldMap release-spirit hook behind the Ace2-era
`lua51` probe (loadstring("return function(...) return ... end")), treating a
5.1-capable Lua as a modern client:

    if lua51 then
        WorldMapDeathRelease:SetScript("OnMouseUp", func)
    end

Our 5.1 syntax backport makes that probe pass, so Cartographer takes the modern
branch and hooks WorldMapDeathRelease -- a WorldMap frame 1.12 never had. The
nil index crashes Cartographer_Notes:OnEnable. On real vanilla the probe was
false and the line never ran.

Same 5.1-probe fallout as the Dewdrop table-length heal: making the client pass
5.1 probes makes addons assume modern-client frames exist. Provide an inert,
hidden WorldMapDeathRelease stub (gated on Cartographer being installed) so the
hook succeeds and does nothing -- the vanilla outcome. The embedded
!!!ClassicAPI addon loads first, so the frame exists before Cartographer's
OnEnable.
Fixes #29
2026-08-22 18:30:48 -05:00
Brues b9d23fbc8c feat(texture): add Texture:SetMask(path) alpha-mask backport
Backports the modern Texture:SetMask, clipping a texture to a mask's alpha
shape - round portraits, round minimap buttons, and other shaped art. Vanilla
1.12 has no general masking (only the special-cased minimap disc).

Mirrors the engine's own masked-quad draw (the minimap blip mask FUN_004eae10):
a co-hook on the vertex-stream primitive FUN_0058a2a0 recovers the owning
CSimpleTexture from the batch positions pointer (region = positions -
OFF_SIMPLETEXTURE_CORNERS), and for a region with a mask set binds the mask on
texture unit 1 with a MODULATE combiner, then re-runs the engine's own submit
with uv1 = uv0 so unit 1 samples the mask at the texture's own coordinates. The
unit is enabled/disabled around the draw so the mask never leaks onto other
textures. A cold co-hook on the region ctor clears a region's mask on pooled
reuse; a kill switch and SEH latch guard the draw path.

The recipe was pinned by an in-game probe on the live GL backend and matched
against FUN_004eae10; the full RE is in the "Texture masking" block in Offsets.h
and the Mask.cpp header. Masks must be BLP or uncompressed 32-bit TGA with the
shape in the alpha channel; two round masks ship in the client, other shapes are
addon-supplied content.
2026-08-22 17:14:36 -05:00
Brues a2c51a1ae6 fix(inline-texture): place chat icons pre-render to remove the one-frame lag
A ScrollingMessageFrame re-SetTexts every visible line on each new message, and
the engine builds each line lazily at paint. The icon regions are separate
objects whose placement is only known once a line builds mid-paint - after the
frame's texture pass already drew - so on a content change the new glyphs
appeared one frame before their icons caught up.

Co-hook the SMF display refresh (FUN_00788750), which runs pre-render from the
frame's own methods. After it, force each icon-bearing line to resolve+build via
the engine's own Realize(0) -> RebuildString -> ensure-built path and apply its
icon placement synchronously, before the frame draws. The placement math
(ComputePlacementsForNode) and the per-fs apply (ApplyDirtyBranch) are shared
with the existing paint-flush / FrameTick pipeline, so the later flush dedups to
a no-op.

Additive and best-effort: any line whose rect is not resolvable in time falls
back to the unchanged paint + tick pipeline (correct, one-frame lagged). Gated by
a new _classicapi_InlineTexEarly toggle (default on) with an SEH latch; the whole
feature keeps its _classicapi_InlineTexEnable kill switch.
2026-08-22 13:40:36 -05:00
Brues d5c8db9c2e docs+ci: contract-only table-length docs; rename release map asset
* README behaviors row + API.md section for the 5.1 table-length
  healing now describe the behavior (cleared tables count as empty
  without table.setn; arg tables and setn callers unaffected) instead
  of the implementation and the Dewdrop/FuBar bug story -- that history
  lives in the commit message and the Length.cpp comment.

* Release workflow ships the linker map as
  USE_FOR_DEBUGGING_CAPI_CRASHES.map (copy before upload), so users
  know to attach it to crash reports -- it resolves the logical
  addresses in an ERROR #132 stack trace to function names.
2026-08-22 12:13:25 -05:00
Brues 9c7c8dd8e5 fix(lua): clear the token vector between transpile passes + guard the hook
Tokenize never cleared its output vector, and RunPasses re-lexes into
the SAME vector after each pass that rewrites the buffer -- so every
chunk that triggered two rewriting passes walked a DOUBLED token
stream: stale tokens at old-buffer positions, then fresh tokens
starting back at 0. Two field-real failure modes:

* CRASH (hex pass -> vararg pass): a fresh token's t.start lands
  behind the splice cursor, `t.start - p` underflows as size_t, and
  append() throws std::length_error("string too long") straight
  through the loadbuffer hook into the engine -- fatal ERROR #132 at
  RaiseException. Reported from the field on WeakAuras' bundled
  Chomp\Internal.lua (hex BITS table + varargs); reproduced offline
  byte-for-byte with a standalone harness compiled from this file
  against the actual upstream Internal.lua.

* SILENT CORRUPTION (vararg pass -> ops pass): the same doubled stream
  made the operator pass read stale in-string positions as code -- a
  `%` INSIDE a string literal became __mod, emitting syntactically
  invalid output (diff-proven: Chomp's `channel:gsub("^[^%:]+", ...)`
  shipped as `channel:__mod(__mod(gsub("^[^,:]+",)) ...)`). Such files
  failed to compile behind WoW's soft error() -- dead file, half-loaded
  addon, no visible error. Any chunk combining `...` with `#`/`%` was
  at risk.

Fixes:
1. Tokenize clears at entry (the root fix). Verified on the real
   Chomp file: full pipeline transpiles cleanly -- hex -> exact
   decimals, (...) -> (unpack(arg)), #q -> __len(q), string-literal
   `%` untouched, the previously-mangled gsub line correct.
2. Catch-all guards at both hook boundaries (LoadBuffer_h and the
   _classicapi_Transpile diagnostic): any future C++ exception from
   the rewrite machinery falls back to compiling the ORIGINAL buffer
   untouched -- worst case the chunk behaves as stock 1.12, never a
   process kill.
2026-08-22 11:42:55 -05:00
Brues 813a10f696 fix(lua): heal stale 5.0 table lengths for 5.1-detecting libraries
The 5.1 syntax backport made the Ace2-era Lua-version probe pass:

    local lua51 = loadstring("return function(...) return ... end")
                      and true or false

Every Ace2 library gates on it, and Dewdrop-2.0 (the menu library
behind FuBarPlugin minimap buttons -- SuperAPI, NampowerSettings) uses
it to no-op table.setn: correct on real 5.1, where lengths are computed
borders, but wrong on this VM, whose table functions still read 5.0's
out-of-band length. Cleared-and-reused menu tables kept stale lengths,
table.insert appended past the nil'd slots, and the menus silently
broke ("clicking the minimap button does nothing"). Bisect confirmed:
forcing the probe back to 5.0 (VarargExpansion off) restores them.

Since we made the client PASS 5.1 probes, 5.1 length semantics must
hold. The engine funnels every length read through luaL_getn
(LUAL_GETN = 0x6F5050 -- table.insert/getn/remove/concat/sort/foreachi,
plus our unpack), so one co-hook closes the gap for every consumer:

  1. reported slot populated -> unchanged (one rawgeti of cost);
  2. t[n] nil but t.n is a number -> unchanged: an explicit n field is
     the 5.0 vararg-arg contract, where trailing nils are intentional
     (unpack({10,nil,30,n=3}) keeps all three slots);
  3. otherwise the out-of-band length is stale (keys cleared without
     setn) -> return the true border, the 5.1 answer. Read-only, no
     write-back: reads never mutate state, and the engine's own
     table.insert re-syncs the stored length on the next append.

table.setn keeps working; the heal only changes the answer when the
stored length points past the last populated slot -- exactly the case
where 5.0 and 5.1 disagree.

Docs: API.md "Stale table lengths (5.1 healing)" section + README
behaviors row.

Fixes #29
2026-08-22 11:08:32 -05:00
Brues 7225eeb32c feat(lua): close the remaining 5.0->5.1 stdlib gaps
Systematic sweep of the Lua 5.1 stdlib delta against what ClassicAPI
already backports found five gaps, all confirmed by in-game probes:

* unpack(list [, i [, j]]) -- 5.0's unpack silently ignored the range
  args, so unpack(t, 2) returned the WHOLE table (wrong values, no
  error; the only silent gap). Replaced with a port of 5.1's
  luaB_unpack: ranges via luaL_getn + lua_rawgeti, so a vararg arg
  table's n field keeps its embedded-nil count. Both states.

* string.gsub table replacement -- 5.0 accepts only string/function
  and errors on a table. Shim on string.gsub AND the bare gsub global:
  a table becomes an adapter closure over the engine's own gsub
  (FUN_LUA_STR_GSUB = 0x007FD0E0, pinned by registration-table
  position, name string, and decode). Because this engine's add_value
  drops a non-string function result (match -> empty) where 5.1 keeps
  the match on nil/false, the shim wraps the pattern in one outer
  capture (^/$ anchors kept outside) so the closure receives the whole
  match and can hand it back for missing keys -- exact 5.1 keep-match.
  Patterns with a %1..%9 backref skip the wrap (renumbering hazard);
  their missing-key behavior stays the engine's (documented residual).

* collectgarbage 5.1 options -- "count" -> gcinfo, "collect" ->
  original collectgarbage(0), "step" -> loop-safe true, stop/restart/
  setpause/setstepmul -> no-op 0, numbers forwarded untouched. The
  originals are function objects stashed in the state's registry
  before the overwrite, so no new engine offsets and each /reload
  re-stashes the fresh engine original. Both states.

* table.maxn -- 5.1 luaB_maxn port (largest positive numeric key,
  full next-walk so nil holes don't stop it). Both states.

* coroutine.running -- returns the running coroutine, nil on the main
  thread. 5.0 has no lua_pushthread, so the thread TValue (tag 8 +
  the running L, this build's {tt@0, value@+8} layout) is written to
  the stack raw; main-thread detection via the registration-time L.

Verified in-game: ranged/holed/n-field unpack shapes, all four gsub
shapes (populated table, keep-match on missing key, whole-match key,
anchored pattern), maxn past a nil hole, collectgarbage("count"/
"collect"), and coroutine.running from main + inside a wrap.

Docs: five new API.md sections + TOC entries; README Lua list updated.
2026-08-22 01:46:24 -05:00
Brues 5a1d94c001 feat(lua): harden string methods -- kill switch + fail-closed captures
Follow-up hardening for the 5.1 string-method backport (9b9d80d):

* _classicapi_SetStringMethods(false) -- diagnostic kill switch on both
  states, mirroring _classicapi_SetTranspileOption. While off the hook
  forwards everything to the original resolver: exact stock behavior.

* Close both stale-capture windows by clearing each slot BEFORE its
  state can die, instead of relying on "no Lua runs in the window":
  - game slot: PrepareForReload (new StringMethods.h), called from
    FrameScript_Initialize_h before the world Lua state is reset --
    covers /reload AND /logout;
  - glue slot: cleared at the top of the in-game registration -- once
    world scripts are loading the glue state is gone, and the next glue
    boot re-captures before any glue Lua runs, so a recreated glue
    global_State at the same address can never match a stale capture.
  A cleared slot fails closed (stock "attempt to index" error) until
  its re-capture.

* StringLib.cpp: replace the obsolete "method sugar can't work" header
  NOTE -- both call forms resolve through the same string table now.

* docs: kill-switch bullet in the API.md String methods section.
2026-08-22 00:57:26 -05:00
Brues 1536741594 docs(readme): list Lua 5.1 string methods in the behaviors table
Follow-up to 9b9d80d, which added the API.md section but missed the
README's behaviors table where the other Lua 5.1 backports are listed.
2026-08-22 00:14:40 -05:00
Brues 9b9d80d807 feat(lua): backport Lua 5.1 string methods (("s"):upper(), s:format(...))
Lua 5.0 has no string methods at all -- the shared string metatable with
__index = string is a 5.1 addition, and both halves of the would-be
mechanism in this build match stock 5.0 exactly: lua_setmetatable
(0x006F4020) accepts only tables/userdata, and luaT_gettmbyobj
(0x006F7BD0) hardcodes &nilobject for every other type. So nothing can
be re-enabled; the 5.1 read path has to be added.

Transplant 5.1's mechanism at the one choke every string index reaches:
co-hook FUN_LUA_INDEX_NONTABLE (0x006F7EE0, luaV_gettable's non-table
continuation; 3 call sites -- the gettable else-branch plus
luaV_execute's OP_GETTABLE/OP_SELF fallbacks). When the indexed object
is a string, answer with luaV_gettable(L, <string library table>, key,
loop) -- byte-for-byte what the original's own TM-table branch does had
gettmbyobj returned that table, loop passed through unchanged. The
engine's unmodified lookup then yields exact 5.1 semantics, including
nil (not an error) for unknown keys. Non-strings fall through to the
original; settable on a string is a different continuation, untouched.

The site is cold: table __index dispatch (all frame/OO traffic) reads
the table's own metatable via fasttm (FUN_006F7D60) and never lands
here -- today's only callers are about-to-error non-table indexes.

One captured slot per Lua state (in-game + glue), keyed by global_State
so coroutine threads resolve too; each capture anchors the string table
in that state's registry against GC and re-runs per /reload and per
glue boot. Since baselib/StringLib already registers string.match /
gmatch / reverse into the same table, modern idioms like
msg:match("^!(%w+)") work with no further top-up.

Docs: new API.md "String methods" section; replaced the now-obsolete
"only string.foo(s), never s:foo()" caveat under string.match with a
pointer to it.

Verified in-game: literal and variable receivers, :format, 5.1 nil-miss,
and resolution inside a coroutine thread.
2026-08-22 00:09:59 -05:00
Brues bac27b9b2b fix(chat): auto-size raid-target markers to the chat font
{rtN}/{skull}/etc. emitted a hardcoded :14:14 size, so a marker never
tracked the chat font-size setting. Emit :0:0 instead — the inline
emitter resolves height/width to the target line's font pixel height at
draw time, so markers grow and shrink with the chat font and scale up in
speech bubbles, matching retail's ICON_LIST `...Icon_%d:0`. The sheet
crop is size-independent, so cell selection is unchanged.
2026-08-21 23:06:02 -05:00
Brues 31e85731b6 Rename transpile helper API
Rename the Lua transpile entrypoint from `_classicapi_TranspileLength` to `_classicapi_Transpile` and update the backing C++ function symbol to match.
2026-08-21 22:47:47 -05:00
Brues 58ddcace32 perf(item): settle the item-cache gate on a wall-clock delay, not frames
The startup gate that defers item queries until the engine's dispatch is
ready used a fixed 60-frame count, which is FPS-dependent: on a fast
machine it could fire before dispatch was ready (orphan risk) and on a
slow login it stretched well past its intended ~1s, leaving bag icons as
"?" longer than needed.

Anchor the delay to VAR_IN_WORLD (set by the enter-world initializer,
cleared on every transition) and measure a fixed 1000 ms past world-live,
so it is identical on any machine and only starts once the loading screen
is gone. The engine-response fast-latch is untouched: a real item
response still settles the gate instantly, so a warm WDB has no delay and
only a cold WDB waits the floor. Drops the now-unused frame counter.
2026-08-21 22:25:18 -05:00
Brues 58ee86447b feat(item): proactively cache carried items on enter-world
A bag item's icon comes from its ItemStats cache entry (m_displayInfoID);
on a cold WDB an uncached bag item resolves displayID 0, and the icon
path draws INV_Misc_QuestionMark ("?"). Nothing in the bag-draw path
queries stats (GetContainerItemInfo and the icon getter both do
null-callback lookups), and the server pushes no item stats on login, so
a carried item stayed "?" until a hover, a loot, or an addon GetItemInfo
happened to query it. Equipped items are exempt (icon from the
server-pushed visible-items table).

Seed the request queue with every carried item once the startup gate
settles (one-shot per enter-world, re-armed on login and /reload) on the
existing owned-priority lane. This gives complete carried-item coverage
ahead of any addon's background flood, stays bounded by the same owned
budget so it adds no burst (issue #25), and is still deferred past
g_settled so it cannot orphan a cache entry before the engine's dispatch
is ready.
2026-08-21 22:12:48 -05:00
brues-code a4d6290b80 Lua 5.1 syntax transpile + modern addon-loading compatibility (#28)
* feat(lua): backport 5.1 `#` and `%` operators via source transpile

Vanilla's Lua is 5.0, which lacks the `#` (length) and `%` (modulo)
operators, so modern addon ports that use them fail to COMPILE. Rather than
patch the 5.0 parser/VM (no OP_LEN/OP_MOD, no free opcode), rewrite the
SOURCE before it reaches the parser.

src/luasyntax/Transpile.cpp co-hooks luaL_loadbuffer (0x006F5690) — the one
function every compile funnels through (file scripts, loadstring, XML
handlers) — tokenizes each chunk with a small Lua-aware lexer, and runs a
precedence-climbing parser that rewrites, in one pass:

    #operand  ->  __len(operand)
    a % b     ->  __mod(a, b)

`#` is prefix but `%` is binary infix, so its operands are delimited by
PRECEDENCE: a*b%c -> __mod(a*b,c), a+b%c -> a+__mod(b,c), a%b%c chains
left-assoc as __mod(__mod(a,b),c), a%b^c -> __mod(a,b^c). The two operators
compose in the same pass (#t%2 -> __mod(__len(t),2)). No newlines are
inserted, so error line numbers are preserved.

Runtime helpers (registered on both the in-game and glue states):
 - __len: string length, or a table border via bisection (5.1 `#`
   semantics — ignores any table.setn count).
 - __mod: a - floor(a/b)*b. NOT the engine's math.mod, which is C fmod
   (truncated toward zero) and disagrees with `%` for negatives
   (-1 % 3 == 2, but fmod(-1,3) == -1).

Safety: the rewrite runs only when a chunk contains `#`/`%`, and either as an
operator already fails to compile on 5.0 — so it cannot regress working code
except by misreading one inside a string/comment ("%d", "%a+", --[[ # ]]).
The lexer's string/comment skipping is the one safety-critical part and is
exact. Gated behind default-on toggles (_classicapi_SetLengthOperator /
SetModuloOperator); diagnostic _classicapi_TranspileLength returns the
rewrite. `...` is a separate, larger phase.

Adds FUN_LUAL_LOADBUFFER to Offsets.h with its derivation.

* feat(lua): honor the 5.1 `__environment` metatable field in getfenv/setfenv

Lua 5.1 lets a sandbox hide an environment: put `__environment` in the env
table's metatable and `getfenv` returns that value instead of the real env,
while `setfenv` refuses to change it. 1.12's engine already has this
protection but reads a RAW `__fenv` field on the env table itself — the older
5.0 form. Modern addons ported from 5.1 use the metatable `__environment`
spelling, which 1.12 silently ignored, so their sandboxes leaked.

getfenv (0x00702AC0) and setfenv (0x00702BF8) share one predicate
(0x00702BA0) that reads the marker and, when present, substitutes it / errors
"cannot change a protected environment". src/luaenv/Fenv.cpp co-hooks and
fully replaces that predicate to read `rawget(getmetatable(env),
"__environment")` first, falling back to the raw `env.__fenv` field. One hook
updates both consumers. The reimplementation preserves the predicate's exact
stack contract (push env, push marker, net +2, boolean return) that getfenv
(settop -2) and setfenv (settop -3) depend on; both metatable and env lookups
are RAW, so an `__index` metatable on the env is not disturbed.

The 5.1 mechanism was verified against 3.3.5's `FUN_0084F2F0` (raw
`__environment` off the metatable; no `"__fenv"` string exists there — Blizzard
renamed it and moved it to the metatable at the 5.0->5.1 jump). The change is
additive and inert: nothing on disk sets either marker, so every existing
getfenv/setfenv caller keeps getting the real env — it only activates when
code deliberately marks an environment.

Adds LUA_GET_METATABLE, LUA_GET_FENV, and FUN_LUA_ENV_PROTECT_PREDICATE to
Offsets.h.

* Use Lua length operator for class count

* feat(lua): backport the 5.1 `...` vararg expression via source transpile

This build is pure Lua 5.0 varargs: `function(...)` parses and populates the
`arg` table (with `arg.n`), but `...` used as an EXPRESSION is a parse error
("unexpected symbol near '...'") — verified in-game. So modern 5.1 addon code
using `...` (`{...}`, `local a,b = ...`, `f(...)`, `return ...`,
`select('#', ...)`) fails to compile.

Add a vararg pass to the transpiler (RewriteChunk runs it before the # / %
precedence parser) that rewrites the `...` EXPRESSION to `unpack(arg)`. This is
a faithful, position-independent substitution: `unpack(arg)` is itself a
multi-value expression, so it spreads in tail position and truncates to one
value elsewhere exactly as `...` does, and this build's `unpack(arg)` preserves
embedded nils via `arg.n` (verified: `f(1,nil,3)` -> `1 nil 3`). No precedence
analysis needed — unlike `%`, it's a token substitution once one case is
excluded: the `...` in a function's PARAMETER LIST (the vararg declaration that
creates `arg`) is left intact, found by scanning each `function` keyword and
skipping its param parens. Nested vararg functions work for free — each
`function(...)` makes its own `arg` and `unpack(arg)` binds to the nearest one
(verified: inner arg count 2, outer 3).

Safety mirrors # / %: only chunks containing `...` are touched, and `...` as an
expression already fails to compile on 5.0, so it can't regress working code;
`...` inside strings/comments is skipped by the lexer, and `.` (field) / `..`
(concat) are distinguished by run length. Gated behind the default-on
`_classicapi_SetVarargExpansion` toggle; `_classicapi_TranspileLength` now shows
the full rewrite (vararg + # + %).

File-scope `...` (the `local name, addon = ...` idiom) transpiles fine but only
yields values if the client passes varargs to addon chunks — a loader question,
separate from this syntax rewrite.

* feat(lua): provide addon-args so file-scope `local name, ns = ...` works

Modern addons open files with `local name, ns = ...` — the addon name plus a
per-addon shared namespace table, passed by the loader as the chunk's varargs.
Vanilla 1.12 never passed those (its main chunk has no `arg`), so with the
`...` backport in place the idiom resolved to `unpack(nil)` and errored. This
supplies the args ourselves.

In the luaL_loadbuffer hook, for an addon-file chunk (chunkname
`@Interface\AddOns\<Name>\...`, parsed case-insensitively) that uses a real
`...`, prepend a chunk-local `arg = {"<Name>", __addonns("<Name>"), n=2}`. The
existing `... -> unpack(arg)` pass then makes `local name, ns = ...` yield the
name and the namespace table. The preamble is newline-free (line numbers
preserved), placed after any UTF-8 BOM, and only injected for AddOns\ chunks
(FrameXML and loadstring are untouched); the addon name is rejected if it
contains characters that would break the string literal.

`__addonns(name)` returns the per-addon table — created once and returned
identically for every file of the addon (backed by a name->table map in the
Lua registry), matching modern WoW's shared second vararg. Registered in-game.

Verified in-game: an addon file's `local name, ns = ...` yields
`("<AddonName>", <table>)` with `ns == __addonns(name)` (shared across the
addon's files). File-scope `...` was the last piece; the in-function case was
already handled by the `...` pass.

* feat(lua): add C_AddOns.GetAddOnLocalTable(name)

Public alias of the addon-args namespace: returns the same per-addon table the
`local name, ns = ...` idiom yields — create-once and shared across every file
of the addon, backed by the same registry map as the internal `__addonns`
(both call Script_AddonNS). Lets code fetch an addon's namespace by name.

Registered via RegisterTableFunction on C_AddOns (non-destructive; coexists
with the existing C_AddOns.* functions regardless of module init order).

Currently ungated — it returns a table for any name, create-on-demand. TODO #99
records the follow-up to match retail: return nil unless the addon is loaded
AND its TOC declares `## AllowAddOnTableAccess: 1`, gating only this public
entry point while leaving the internal preamble path ungated.

* feat(lua): gate C_AddOns.GetAddOnLocalTable behind loaded + TOC opt-in

GetAddOnLocalTable was a raw alias of the addon-args namespace accessor:
it returned any addon's private table by name, loaded or not, with no
access control. Retail (11.0) gates this -- one addon reads another's
local table only when the target opts in via the `## AllowAddOnTableAccess`
TOC directive. Mirror that.

The public accessor now lives in addons/LocalTable.cpp and returns the
table only when the named addon is loaded (FUN_ADDON_IS_LOADED, by-name)
AND its .toc declares `## AllowAddOnTableAccess: <nonzero>` (scanned via
FUN_FILE_READ, read as a TOC boolean flag). Either check failing returns
nil. Directive spelling and function name both verified present in the
1.15.8 Classic Era binary.

The internal preamble path (an addon receiving its OWN table via the
injected `local _, ns = ...`) stays ungated -- an addon never needs
permission for its own namespace. Both paths now resolve to the same
per-addon table through LuaSyntax::PushAddonNamespace (AddonNamespace.h),
the single owner of the registry-backed name->table map.

Also close the bypass in the `__addonns` global itself. The map lives in
the Lua registry (unreachable from Lua -- this build ships no
debug.getregistry / debug introspection), so `__addonns` was the sole
Lua-visible door, and it was ungated. It is now context-gated: it answers
only while an addon's own chunk is mid-load, for its own name, one-shot.
At runtime it denies every name. Verified safe against the loader: the
addon file loader is strictly per-file load-then-run
(FUN_006edb90 -> FUN_006ede10 -> FUN_00704bc0 -> FUN_00704ae0, where
luaL_loadbuffer is immediately followed by lua_pcall), so nothing runs
between the grant being set and the preamble consuming it.

Net result: the only runtime path to another addon's local table is the
TOC-gated GetAddOnLocalTable.

* fix(lua): close the __addonns loadstring-forgery vector

The addon-args grant (`g_loadingAddon`) that lets a chunk's injected
preamble fetch its own namespace via the `__addonns` global was armed
whenever luaL_loadbuffer saw an `Interface\AddOns\...` chunkname with a
`...`. That chunkname is forgeable: `loadstring(s, chunkname)` takes a
caller-controlled chunkname (arg 2) and compiles WITHOUT running, so

  loadstring("return ...", "@Interface\AddOns\Victim\x")
  __addonns("Victim")   -- returned Victim's private table

armed the grant and leaked another addon's local table, with no
`## AllowAddOnTableAccess` opt-in.

Fix: arm the grant only when the loadbuffer call comes from the engine's
immediate-run file funnel FUN_00704AE0 (it pcalls the chunk right after
compiling, so the preamble consumes the grant before anything else runs).
The hook checks `_ReturnAddress()` against RET_LUA_FILE_COMPILE
(0x00704B11, the instruction after that funnel's `call luaL_loadbuffer`).
`loadstring` (FUN_00703280) and `RunScript` (FUN_00704C70) call from
different return addresses, so neither can arm — even a loadstring nested
inside a RunScript body that itself runs through the file funnel. The two
callers that DO reach 0x00704B11 (FUN_00704bc0 DoFile, FUN_00704cd0
inline-XML-script) both supply engine-built chunknames, not caller data.
Verified in-game: forged loadstring compiles but yields nil.

Also fix two lexer/scan bugs found in review:
- SkipNumber treated e/E as an exponent marker in hex literals, so
  `0xE-1 % 2` lexed `0xE-1` as one token and rewrote to __mod(0xE-1,2)
  (=1) instead of 0xE-(1%2) (=13). Hex literals now use p/P only.
- The addon-path marker matched a backslash separator only while its
  own terminator scan accepted both; it now matches `addons\` or
  `addons/`, consistent with addons/Embedded.cpp.

* refactor(addons,lua): dedup CI helpers, share TOC scan, table-driven toggles

Review cleanups, behavior-preserving:

- Drop the hand-rolled LowerAscii/EqualsCI copies in luasyntax/Transpile.cpp
  and addons/LocalTable.cpp for `_stricmp`/`_strnicmp` (the codebase norm).
- Add addons/Toc.h `FindValue(buf, size, directive, ...)` — the `## Key:`
  line-start scan in one place. Embedded.cpp (Version) and LocalTable.cpp
  (AllowAddOnTableAccess) both consume it; the file-read stays per-caller
  since Embedded's is entangled with its disk-vs-embedded decision.
- Collapse the six per-switch transpile toggle functions to a {name, bool*}
  table plus one `_classicapi_SetTranspileOption(name, bool)` /
  `_classicapi_GetTranspileOption(name)` pair (name = Length / Modulo /
  VarargExpansion). Nothing outside Transpile.cpp referenced the old names.

* feat(addons): load multi-flavor addons via _Vanilla/_Classic TOC selection

Modern addons target several game flavors from one folder by shipping
`<Name>_Vanilla.toc` / `_Mainline.toc` / `_Cata.toc` / … and frequently no
plain `<Name>.toc`. Vanilla 1.12 only ever opens `<Name>\<Name>.toc`, so such
an addon never registers -- it is invisible, not merely mis-loaded.

Backport the retail client's flavor-file selection at the file-read layer.
The scan's TOC parser FUN_0051C9B0 reads Interface\AddOns\<Name>\<Name>.toc
via FUN_FILE_READ (0x00648620) and registers the addon only if that read
succeeds; the load pass and GetAddOnMetadata read the same path. We already
co-hook FUN_FILE_READ for the embedded addon, so FileRead_h now calls
AddOns::FlavorToc::TryHandle in its non-!!!ClassicAPI branch: for a base-TOC
read it probes <Name>_Vanilla.toc then <Name>_Classic.toc via the original
reader and serves the first that exists in place of the base (the parser
passes outSize=NULL, so it just forwards args with a different path).

Precedence mirrors retail: flavor wins over an existing base, and _Vanilla
beats _Classic. Does NOT fall back to _Mainline/_Cata/etc -- an addon shipping
only those doesn't support vanilla and stays unlisted. Folder enumeration
already lists flavor-only folders, so only the TOC read needed redirecting.

Verified in-game: a folder with only FlavorTest_Vanilla.toc registers and
loads; GetAddOnInfo returns the _Vanilla title/notes.

* feat(addons): prefer _Turtle.toc flavor on Turtle-lineage clients

Extend multi-flavor TOC selection with a _Turtle.toc suffix, a ClassicAPI
extension (not a retail flavor) for addons targeting Turtle's server content.
Probe order becomes _Turtle -> _Vanilla -> _Classic, with _Turtle offered
first and only when Turtle::Detected() is true, so stock 1.12 never prefers
Turtle-only code.

The redirect fires at both the registration scan (glue/char-select) and the
in-world load pass, which must select the same flavor -- so detection has to
read consistently at glue-scan time and in-world. The in-world signal
(TURTLE_WOW_VERSION, engine-set) is absent on the glue state, so Turtle::Detect
now also recognizes Turtle's glue-time TURTLE_* GlueXML string globals
(AUTH_TURTLE_WEBSITE / TURTLE_ARMORY / TURTLE_KNOWLEDGE_DATABASE, set in
GlueStrings.lua at glue boot, before the scan). Clones keep those names and
only rebrand the URL values, so name presence is clone-robust where realmList
is not. Detected() now latches on either signal and works in both states;
Version() still fills from TURTLE_WOW_VERSION once in-world.

Verified in-game: a folder shipping only FlavorTest2_Turtle.toc registers and
loads on Turtle (GetAddOnInfo returns the _Turtle title), while the earlier
_Vanilla-only test still works.

* feat(addons): narrow flavor TOC selection to _Turtle + _ClassicAPI

Drop `_Vanilla`/`_Classic` from the flavor probe list. Those are the 1.15
Classic Era client's suffixes -- a modern engine with the full modern API and
modern FrameXML templates. Adopting them told a multi-flavor addon "I'm 1.15",
so its `_Vanilla` build would assume APIs/templates this 1.12 + partial-backport
client doesn't fully have, load, and then break. A clean non-load is better.

Select only the two flavors that describe THIS environment, most specific first:
  _Turtle      -- Turtle client/content, only when Turtle::Detected();
  _ClassicAPI  -- 1.12 + ClassicAPI, always (ClassicAPI is present by
                  definition -- it is the code doing the redirect).
Both are ClassicAPI conventions the addon author opts into, not an attempt to
impersonate a retail flavor. If neither exists, TryHandle returns false and the
caller does the normal base read, which chains through any other FUN_FILE_READ
hooker before reaching the engine.

Verified in-game: a folder with only `<Name>_ClassicAPI.toc` registers/loads; a
`_Turtle`-only folder registers on Turtle; a `_Vanilla`-only folder no longer
registers (correctly, now that `_Vanilla` is not a selected flavor).

* feat(addons): backport per-line TOC directives (conditions + variables)

Single-TOC multi-flavor addons gate individual file-reference lines and
expand path variables:

    [Family]\Init.lua                              -> Classic\Init.lua
    Vanilla.lua        [AllowLoadGameType vanilla]  kept
    Mainline.lua       [AllowLoadGameType mainline] dropped
    Localization\[TextLocale].lua                  -> Localization\enUS.lua

Vanilla 1.12's TOC readers understand none of it: the scan parser
FUN_0051C9B0 only parses `##` metadata, and the load pass FUN_006edb90
hands each file line to FUN_006ede10 verbatim, where a trailing ` [...]`
breaks the extension check so the file silently never loads.

New module AddOns::TocRewrite rewrites the TOC buffer at the FUN_FILE_READ
chokepoint (alongside FlavorToc/Embedded), so the engine's own load loop
sees clean paths and both parsers are covered by one edit.

On this client the tokens resolve to: [AllowLoadGameType] keeps iff the
list has `vanilla`; [AllowLoadTextLocale] keeps iff it has the client
locale; [AllowLoad] keeps `game` and drops `glue`; [Family]->Classic,
[Game]->Vanilla, [TextLocale]->the client locale code. Locale comes from
VAR_LOCALE_NAME_TABLE (0x008558A4), the exact source Script_GetLocale
reads, so it matches GetLocale() byte-for-byte.

Gated to ...\AddOns\...\*.toc reads (a .lua `t[1]` would otherwise be
mangled); bracket-free TOCs stay zero-copy via a memchr bail; a rewritten
TOC goes into a fresh Storm buffer the engine frees like its own. Unknown
conditions fail safe (drop the line); gated-out lines become `#` comments.

Verified in-game on Turtle: 8 keep-cases loaded, 4 drop-cases (bare
mainline, glue, deDE, unknown keyword) did not.

* docs: document the branch's Lua 5.1 and TOC compatibility features

User-facing docs for the feat/lua-syntax-transpile branch.

docs/API.md:
- New "Lua 5.1 syntax: length, modulo, and vararg" section: the source
  rewrite for `#`, `%`, and `...`-as-expression; what each form becomes
  (`#` = border, ignores table.setn; `%` = 5.1 sign-of-b, contrasted with
  math.mod); the `local name, tbl = ...` addon-args idiom; limits
  (string/comment safety, first-close long-bracket matching, preserved
  line numbers) and the diagnostic kill-switch.
- New "getfenv / setfenv environment protection" section: the 5.1
  `__environment` metatable field, with the `__fenv` fallback noted.
- New "Conditional and multi-flavor TOC loading" section under AddOns:
  `_ClassicAPI` / `_Turtle` flavor file selection and per-line
  `[AllowLoadGameType]` / `[AllowLoadTextLocale]` / `[AllowLoad]`
  conditions and `[Family]` / `[Game]` / `[TextLocale]` path variables,
  with the token resolution table and limits.
- Table-of-contents entries for all three.

README.md:
- Add C_AddOns.GetAddOnLocalTable to the AddOns calls row (was missing).
- Add three rows to the Behaviors table (Lua 5.1 syntax, Lua 5.1
  environment protection, multi-flavor & conditional TOC loading), each
  linking to its API.md section.

* feat(addons): accept multi-flavor `## Interface:` version lists

A retail TOC can list several interface versions on one line
(`## Interface: 120100, 50504, 38002, 20506, 11200`). Vanilla's parse is a
plain atoi (FUN_0064ade0) that reads only the first number into entry+0x1C,
and the loadability resolver FUN_0051e780 compares that to the client
version FUN_0051d7d0() (0x2BC0 = 11200): a mismatch is the OUT_OF_DATE
reason that blocks loading while checkAddonVersion is on. So a list whose
first entry isn't 11200 never loads even when 11200 appears later in it.

TocRewrite now special-cases the `## Interface:` line: parse the whole
list, and if the client version (read live via
FUN_ADDON_CLIENT_INTERFACE_VERSION, not hardcoded) is present but not
first, rewrite the value to that single number so the engine stores 11200
and marks the addon compatible. A list without 11200 (or already leading
with it) is left verbatim, so it stays out of date exactly as before. The
fast-path gate widened to `[` or `,`; the content-compare bail keeps
comma-bearing TOCs (e.g. `## Dependencies: A, B`) zero-copy.

Docs (API.md, README.md) describe the behavior and the 11200-only
compatibility rule.

Verified in-game on Turtle: GetAddOnInfo on an addon listing
120100,50504,38002,20506,11200 returned no reason (loaded); the ...,11509
control returned INTERFACE_VERSION (out of date).

* feat(addons): honor ## LoadSavedVariablesFirst

Modern addons use `## LoadSavedVariablesFirst: 1` so their SavedVariables
are restored before their Lua runs, letting file-scope code read config.
Vanilla always runs an addon's files first, then loads SavedVariables,
then fires ADDON_LOADED (verified in FUN_0051f240), and never parses the
directive — so file-scope SV is always nil.

New module AddOns::SavedVarsFirst co-hooks the per-addon file loader
FUN_ADDON_LOAD_FILES (FUN_006edb90). For an addon whose TOC declares the
directive, it loads the SavedVariables first, mirroring the engine's own
path construction two steps later:

  account : WTF\Account\<account>\SavedVariables\<Name>.lua
  per-char: WTF\Account\<account>\<realm>\<character>\SavedVariables\<Name>.lua
            (falling back to the realm-less path)

account = *VAR_ACCOUNT_NAME_PTR, realm = FUN_GET_REALM_NAME, character =
FUN_GET_LOGIN_ACCOUNT_NAME (whose offset label is a misnomer — it is the
character name). Then it calls the original so the files run with SV
present. FUN_FILE_EXISTS picks the same per-char variant the engine would;
FUN_LUA_LOAD_FILE no-ops on a missing file.

v1 caveat (documented): the engine still runs its own SV load right after
the files, so a file-scope READ works but a file-scope WRITE is overwritten
before ADDON_LOADED. Writes belong in an ADDON_LOADED handler, as usual.

Docs: API.md "SavedVariables loaded first" + a README behaviors row.

Verified in-game on Turtle (login -> /reload): flagged SVFirst saw its DB
at file scope (sawAtFileScope=true), control SVNormal did not (false).

* feat(addons): suppress the redundant SavedVariables re-load (LoadSavedVariablesFirst v2)

v1 loaded a flagged addon's SavedVariables before its files, but the engine
still ran its OWN SV load right after the files — overwriting any value the
addon wrote to its SavedVariable at file scope before ADDON_LOADED.

v2 co-hooks FUN_LUA_LOAD_FILE and skips that one redundant re-load per
pre-loaded path: RunLuaFile loads each SV via the trampoline (bypassing the
hook) and records its full path; LuaLoad_h matches the engine's imminent
FUN_00704bc0(svPath, 0, 0) (case-insensitive, one-shot erase) and returns 0
without loading. The SV-load call sites ignore the return and the SV file
feeds nothing into the TOC checksum, so the skip is side-effect-free.
FUN_00704bc0 loads files only (RunScript runs strings through a different
path), so the extra hook is a cold addon-load-time path.

Now file-scope reads AND writes both survive — matching true
LoadSavedVariablesFirst. Docs (API.md) drop the write-clobber caveat.

Verified in-game on Turtle (fresh SavedVariables, repeated /reload): flagged
SVFirst's file-scope write persists (runs counter climbs 2, 3, 4), control
SVNormal stays 1.

* feat(addons): flavor-specific addon Bindings (Bindings_Turtle/_ClassicAPI.xml)

The Bindings.xml analog of FlavorToc. A modern addon may ship a
flavor-specific keybinding file instead of / alongside a plain
Bindings.xml. Vanilla only ever builds Interface\AddOns\<Name>\Bindings.xml,
gates it on an exists-check (FUN_00648a30), and — only then — loads it via
FUN_004b6f70, which reads through FUN_FILE_READ. So flavor selection needs
two pieces (a FileRead redirect alone can't help a flavor-only addon,
because the exists-check is on the base name):

- AddOns::FlavorBindings::TryHandle, called from the FUN_FILE_READ hook
  after FlavorToc: for a …\AddOns\<Name>\Bindings.xml read, serve a flavor
  variant if present (flavor wins over a plain Bindings.xml). Probe order
  Bindings_Turtle.xml (Turtle only) -> Bindings_ClassicAPI.xml.
- A co-hook on FUN_FILE_EXISTS: report Bindings.xml as existing when the
  base is absent but a flavor variant is present, so the loader runs for a
  flavor-only addon. Non-Bindings paths pass straight through.

Suffixes are _Turtle / _ClassicAPI, never _Vanilla / _Classic (a _Vanilla
bindings file pairs with the 1.15 build we don't load, so its handlers
wouldn't exist). Docs: API.md flavor section + README behaviors row.

Verified in-game: on Turtle all three cases load (flavor-only ClassicAPI,
flavor-only Turtle, flavor-over-base with the flavor winning); on stock the
Turtle-only one correctly drops while the ClassicAPI ones still load.

* feat(lua): backport 5.1 hexadecimal number literals via source transpile

Lua 5.0's lexer reads only decimal digits + one '.' + 'e' exponent, so a
`0x...` literal is a compile error (hence addons resort to
`tonumber("0x...", 16)`). Lua 5.1 added hex literals. As with `#` / `%` /
`...`, we rewrite the SOURCE at the luaL_loadbuffer chokepoint: each hex
INTEGER token becomes the exact decimal it denotes (unsigned), which 5.0's
lexer accepts and reads as the same double 5.1 would.

RewriteHex runs first in the transpile pipeline, gated on a "0x"/"0X"
presence scan; it reuses the tokenizer (so strings/comments are never
touched) and inserts no newlines (line numbers preserved). Hex floats
(0x1.8p3) and > 64-bit literals are left as-is — vanishingly rare, and they
fail exactly as today (no regression). Also fixed SkipNumber to stop a
number at a `..` so `0xFF.."x"` (hex then concat) tokenizes cleanly.
Toggle: _classicapi_SetTranspileOption("HexLiterals", false).

Docs: API.md "Lua 5.1 syntax" section + README behaviors row.

Verified in-game (19/19 harness asserts) and cross-checked against retail:
0xFF->255, 0xFFFFFFFF->4294967295, bit.band(0xF0,0x0F)->0, "0xFF" untouched
all match modern WoW exactly.

* feat(frame): enable modern positional script args by default

Modern handler signatures — `function(self, delta)` / OnEvent
`(self, event, ...)` — are core Lua 5.1 behavior, so flip Frame::ScriptArgs
on by default instead of opt-in. Ports that use them now work with no
`SetModernScriptArgs(true)` call.

It's purely additive (the `this`/`arg1`/`event` globals are still set, so
vanilla-style handlers keep working). `SetModernScriptArgs(false)` remains
the escape valve — it reimplements the tail of the engine's hottest Lua
path (fires for every OnUpdate frame), and disabling it makes both runners
a straight passthrough to exact vanilla dispatch.

Docs + code comments updated from "default OFF (opt-in)" to "default ON".

* docs: surface modern script-handler arguments as a behavior

Add a README Behaviors-table row for the now-default modern positional
script arguments (function(self, delta), OnEvent (self, event, ...)),
alongside the Lua 5.1 syntax row. The SetModernScriptArgs / GetModernScriptArgs
functions stay in the Frame calls table as the off-switch.

* fix(lua): correct transpiler lexer edge cases and operator env-independence

Review findings against the Lua 5.1 syntax transpiler:

- Tokenize `.`/`..`/`...` as multi-char tokens like Lua's own lexer, so a
  `...` vararg adjacent to a `..` concat (e.g. `x .. ...`) is recognized
  instead of forming an unsplittable five-dot run that left `...`
  un-rewritten and failed to compile. Guard the `#`/`%` field-access check
  to a single-char `.` so `a..b` isn't misread as `a.b`.

- Nest level-0 `[[ ]]` long brackets in SkipLongBracket to match the engine's
  own long-string reader (FUN_00700010 keeps a nesting counter). First-close
  matching mis-identified nested-string boundaries and could rewrite `#`/`%`
  bytes the parser treats as string content.

- Capture `__len`/`__mod`/`unpack` as chunk-locals in the load-time preamble
  so the lowered `#`/`%`/`...` operators resolve under a setfenv sandbox with
  no _G fall-through, mirroring real 5.1's environment-independent operators.

- Skip precompiled bytecode (0x1B chunk signature) instead of tokenizing it
  as source and corrupting the chunk.

- Cap parse recursion at 200 (Lua's LUAI_MAXCCALLS) so a pathologically
  nested chunk fails to compile cleanly instead of overflowing the C stack
  inside the hook.

- Case-fold the addon-namespace map key in PushAddonNamespace so a
  case-mismatched C_AddOns.GetAddOnLocalTable request lands on the addon's
  real table instead of minting a fresh empty one.

The `.. ...` vararg and nested-long-bracket fixes verified in-game via
_classicapi_TranspileLength.

* fix(addons): gate LoadSavedVariablesFirst pre-load on the declared scope

LoadSavedVarsEarly chose which SavedVariables files to pre-load from file
existence alone, but the engine loads the account file only when the addon
declares `## SavedVariables` and the per-char file only when it declares
`## SavedVariablesPerCharacter`. So a stale file for a scope the addon no
longer declares got executed early (Lua the engine never runs) and queued in
g_pendingSuppress, which the engine then never drained — a leak of one entry
per stale file per /reload.

Mirror the engine: read the TOC once (ReadSvFlags, replacing
TocWantsSavedVarsFirst) for the reorder flag plus whether each SV scope is
declared, and load each file only when its directive is declared and the file
exists. Every suppress entry we queue is now a file the engine re-loads and
drains.

* fix(turtle): only trust glue markers on the glue Lua state

Probe() checked the `TURTLE_*` glue markers whenever detection wasn't yet
latched, on whatever Lua state was current — including in-world. Those names
are set by Turtle's GlueXML and are only trustworthy on the glue state; in
world any loaded addon can define a global by one of them (a Turtle-UI port
shipping the strings, say), which permanently mis-latched Turtle detection on
a stock client and skewed flavor TOC/Bindings selection for the session.

Gate the marker probe on a `g_onGlue` phase flag driven by the engine's own
per-state script-registration hooks: the in-world ModuleAutoRegister (fires
before the addon load pass) clears it, each glue boot's GlueModuleAutoRegister
sets it. Neither reads a forgeable Lua global. Turtle still detects via the
markers at the glue scan and via TURTLE_WOW_VERSION in-world; a stock client
can no longer be latched by an in-world global.

Also make Version() return nullptr (not "") in the glue-detected-but-no-version
window, matching the header contract.

* revert MAX_CLASSES

* fix(frame): only pass positional script args to handlers that declare them

Default-ON modern script args changed behavior for every handler on the
engine's hottest Lua path, and the docs' "purely additive" claim was wrong:
a handler that DECLARES a parameter received a real value where vanilla always
passed nil.

Gate the reimplemented positional path on the handler's arity: a Lua closure
that declares a parameter or is vararg (function(self, delta) / function(self,
...)) takes it; a param-less handler (the vast majority of vanilla handlers,
which read this/arg1 globals) and a C-closure handler tail-call the original
engine runner unchanged. So param-less handlers are provably identical to
vanilla AND off the hot path (also the efficiency win: OnUpdate handlers that
gain nothing no longer pay the modern tail every frame). Only param-declaring
handlers observe the (self, [event,] arg1..N) shape.

Arity is read from the handler's Proto; offsets verified against the engine's
own luaD_precall (numparams @ +0x45, is_vararg @ +0x46), lua_dump, and
lua_iscfunction/lua_tocfunction (closure @ TValue+8, isC @ +6, Proto @ +0xC).

The param-declaring-vanilla-handler case (a function reused as both a direct
call and a handler) is inherently ambiguous and still gets the value; documented
honestly in ScriptArgs.cpp, docs/API.md, and README with SetModernScriptArgs
(false) as the opt-out. Verified in-game across both runners, both paths, the
toggle, and the caveat.

* refactor(addons): centralize engine-IO typedefs and CI string helpers

The `__stdcall` FUN_FILE_READ / FUN_FILE_EXISTS / Storm-allocator function
types were copied into ~8 places across the addon files, and Lower/EqCI into
three. These are ABI-critical: a copy declared __cdecl by mistake drifts ESP
per call and kills the process with no crash log. Hoist them to one home:

- new addons/EngineIO.h — FileReadFn / FileExistsFn / SMemAllocFn / SMemFreeFn,
  used by Embedded, FlavorToc.h, FlavorBindings.h/.cpp, SavedVarsFirst,
  LocalTable, TocRewrite.
- addons/Toc.h gains Lower / EqCI, used by FlavorBindings, SavedVarsFirst,
  TocRewrite.

Also drop EvalCondition's dead `known` out-parameter in TocRewrite (nothing
read it — an unknown keyword already returns false). Pure refactor, no behavior
change.

* perf(lua): tokenize each chunk once and gate the #/% parse on an operator token

The transpiler ran on every compiled chunk at login/reload, and:
- RewriteHex / RewriteVararg / RewriteAll each re-tokenized the whole chunk, so
  a file that trips more than one pre-check was lexed two or three times;
- RewriteAll's fast-bail was a raw memchr for '%', which is present in nearly
  every chunk via format strings ("%d"), so almost every chunk paid a full
  recursive parse only to discard an empty edit list.

New RunPasses tokenizes once and shares the stream across the passes, re-lexing
only after a pass actually rewrites the buffer (rare). RewriteAll now gates the
parse on an actual '#'/'%' OPERATOR token — a '%' inside a string is a TK_STRING
token, not a punct, so the format-string case skips the parse entirely.
RunPasses also unifies the previously duplicated RewriteChunk / LoadBuffer_h
pipelines. Output is identical (verified in-game via _classicapi_TranspileLength:
vararg-next-to-concat, nested long brackets, and a format-string vs operator '%'
all rewrite exactly as before).

* feat(lua): backport 5.1 leveled long brackets; fix top-level vararg fallback

Adversarial testing of the transpiler surfaced two gaps beyond PR 28:

- Leveled long brackets ([=[ ]=], [==[ ]==]) are the one 5.1 syntax
  construct still missing. The 5.0 engine lexer has no =-level handling
  (verified in FUN_006ff610), so they fail to compile. A new source-walking
  pre-pass rewrites a leveled long string to [[body]] when the body is safe
  (byte-exact, keeps the leading-newline strip) or to a quoted literal with
  \-newline continuations otherwise, and blanks leveled long comments to
  spaces. Line numbers preserved. Gated by the new LongBrackets toggle.

- Top-level ... outside the addon file funnel (RunScript, XML <OnLoad>,
  loadstring) expanded to unpack(arg) and threw on nil arg, where 5.1
  yields nothing. Non-addon vararg chunks now get a local arg={n=0}
  fallback.

Adds a /capitranspile self-test suite (19 cases, all passing in-game) and
updates docs/API.md (also fixing a stale limits note that described plain
long strings as non-nesting: they nest by depth, matching the engine) and
README.
2026-08-21 20:16:54 -05:00
Brues 998deeac4a Fix pfUI HookScript compatibility shim
Tightens the pfUI compatibility shim in AddOnCompat.lua. The temporary CreateFrame wrapper now leaves the maintained brues pfUI fork alone when either its X-Website tag or the pfUI.handlesHookScript capability flag is present, and only applies the HookScript workaround when neither signal exists.
2026-08-21 13:27:00 -05:00
Brues af02ddadb1 fix(loader): stand down the init worker under VanillaFixes
VanillaFixes creates the process suspended and injects every dlls.txt
DLL sequentially via remote threads before resuming. The fallback
worker spawned from DllMain starts the moment our own LoadLibrary
releases the loader lock -- i.e. while VF is still injecting the NEXT
dlls.txt DLL -- so its ~90-prologue install (plus the MH_ApplyQueued
thread-freeze) raced that DLL's DllMain patching the same engine
functions. SuperWoWhook.dll failed to load whenever ClassicAPI
preceded it in dlls.txt.

DllMain now skips the worker when VfPatcher.dll is present in the
process: under VF the `Load` export is the only install trigger, and
it is inherently race-free -- VfPatcher calls it on the game's main
thread after the process resumes, when every DllMain in the injection
chain has already completed, serialized in dlls.txt order. VfPatcher
is always injected before any dlls.txt DLL, and the Load mechanism
shipped in the same VF release (v1.4) as dlls.txt support itself, so
VF present implies Load will fire. Non-VF injectors keep the worker
unchanged.
2026-08-20 10:26:54 -05:00
Brues 93f3131307 fix(text): drop obsolete 1.5-glyph auto-width wrap bail
The wrap-stepper co-hook special-cased auto-width fontstrings (single-anchor,
no explicit width — pfUI addon-list labels, TwitchEmotes labels): when the whole
line fit within 1.5 glyphs of exactly filling its budget it applied zero shrink,
to avoid a spurious wrap from ~1-glyph drift between the width and wrap hooks'
icon-sum computations. The cost was that real-width frames landing within 1.5
glyphs of their edge also gave up their shrink and let icons overflow instead of
wrapping.

The trailing-icon trim, outline-ink threading, and exact-K measure work have
since tightened that drift under half a glyph, so the existing 0.5-glyph
feasibility tolerance now carries the auto-width case on its own. Verified
in-game: pfUI/TwitchEmotes labels no longer spuriously wrap, and near-full
real-frame lines wrap correctly instead of overflowing.
2026-08-19 22:21:24 -05:00
Brues 653a2c6e3a Update README.md 2026-08-19 19:09:37 -05:00
Brues 85c5c924a9 fix(loader): install hooks off the loader lock to survive VanillaFixes' 10s injection deadline
DllMain enabled ~90 hooks individually, and every MH_EnableHook freezes all
process threads (CreateToolhelp32Snapshot + SuspendThread each) under the
Windows loader lock. On machines whose security stack intercepts thread
suspension, 90 serialized freezes ran past VanillaFixes' 10-second
remote-LoadLibrary deadline, so VF read the still-running injection thread as
STILL_ACTIVE (259) and showed its generic "compatible client" error — a false
diagnosis of a slow load that blocked launch entirely for affected users.

Move the whole install off the loader lock. DllMain now only spawns a worker
thread and returns immediately. Hooks install via a latched EnsureInitialized()
reached from two triggers: VanillaFixes' `Load` export (called on the game's
main thread after injection — VF's sanctioned extension point) or the fallback
worker (for any non-VF injector). Whichever arrives first installs; the other
observes the cached result. All hooks are queued and activated in a single
MH_ApplyQueued, so ~90 thread-freezes collapse to one.

- src/DllMain.cpp: minimal DllMain + InstallHooks/EnsureInitialized/Load export
- src/Game.cpp: RunHookRegistrations queues instead of enabling
- src/ClassicAPI.def + CMake /DEF: export `Load` undecorated
- src/Common.h: drop the now-dead HOOK_FUNCTION/UNHOOK_FUNCTION macros
2026-08-19 17:46:59 -05:00
Brues f2af2734f0 docs: trim internal implementation detail from FontString entries
User-facing API docs should describe the contract (behavior, inputs,
outputs, errors, observable caveats), not how a method is built or which
engine path it uses. Drop the "engine already computes this internally /
only adds the binding / comes from the engine's own wrap math / reads
what it last drew and compares" narration from the FontString entries,
keeping every observable behavior and caveat (the setup requirements,
the must-have-rendered-once note, the icon-inclusive widths, the <=1px
rounding note).
2026-08-19 17:04:02 -05:00
Brues dc13d7bbfc fix(fontstring): SetFormattedText uses engine str_format, not _G
SetFormattedText resolved _G.string.format and called it, so an addon
that replaced string.format could hijack or break it. Push the engine's
own str_format C function instead (strlib "format" entry 0x007FD3D0,
verified by decode) and pcall it -- immune to global replacement, and
matching retail, whose SetFormattedText formats in C. Also simpler: one
PushCClosure replaces the _G table walk and its two failure branches.

Verified in-game: with both string.format and the format global replaced
by a stub, SetFormattedText("%d apples", 5) still renders "5 apples".
2026-08-19 16:58:56 -05:00
Brues 99c0ab3ba3 refactor(tradeskill): use SetFormattedText
The trade-skill link frame's rank and summary FontStrings built their
text with SetText(string.format(...)). Use the backported
FontString:SetFormattedText instead -- one call, and it routes through
the engine's own SetText path.
2026-08-19 16:48:38 -05:00
Brues 87acb70c5b feat(fontstring): add IsTruncated, SetMaxLines/GetMaxLines
Backport three FontString methods, each working WITH the engine's own
text-layout machinery instead of reconstructing it:

- IsTruncated(): did the engine cut the text off with an ellipsis?
  Reads render truth -- the built text node keeps a copy of the string
  it actually laid out (node+0x48), the ellipsized form on truncation
  -- and compares it to the source. Same "displayed vs full" check
  retail does (5.4.8 inner fn 0x0045E001). Re-calling the display-text
  resolver from Lua cannot work: it reads the laid-out rect (fs+0x64),
  which is zero between frames, so it never sees the bound.

- SetMaxLines(n)/GetMaxLines(): cap the fontstring to n wrapped lines,
  ellipsizing the rest. Writes the engine's own per-fontstring maxLines
  field (fs+0x128, already honored by the truncation resolver) and
  re-invalidates the layout the way SetText does (drop caches, release
  node, notify region). Vanilla has no SetWordWrap -- the fs->layout
  flag translator exposes no no-wrap bit -- so SetMaxLines(1) is how you
  make a single-line, ellipsized label.

Also correct a mislabeled bit in the inline-texture notes: fs+0x120 bit
0x1000 (gxu/node bit 0x40) is NON-SPACE-WRAP (what SetNonSpaceWrap
toggles), not a dedicated "editable" flag. The inline-texture code uses
it as an editbox proxy, which works because multi-line editors enable
non-space-wrap while display text does not; the comments now say so,
with the rare-edge-case caveat. Documentation only, no logic change.

Verified in-game: IsTruncated true/false across bounded/unbounded boxes;
SetMaxLines caps of 1/2/9/0 with matching GetNumLines and IsTruncated.
2026-08-19 16:46:55 -05:00
Brues 92a959c381 feat(fontstring): backport GetWrappedWidth
The rendered width: the widest wrapped line -- the method that
completes the width trio (GetStringWidth and GetUnboundedStringWidth
both measure the string on ONE line; verified in-game they agree to
float noise). Uses the tooltip auto-size's own recipe: break positions
from FUN_FONTSTRING_BREAK_ARRAY, widest per-segment measure through
FUN_FONTSTRING_MEASURE_SUBSTRING -- both icon-aware through the
existing co-hooks. Segments are trimmed of the whitespace the wrap
consumed (the render never draws it, and a trailing space flips the
last real letter from ink to full-advance treatment, +~1.5px measured).

The wrap budget (shared with GetNumLines' unbuilt fallback via
WrapBudget) is rectWidth / fs+0x7C, calibrated EMPIRICALLY against the
render with a three-point probe on a 100px box at ~0.91 scale, using
text whose candidate lines measure 78.1 / 94.6 / 101.6 px:

  raw rectW    -> effective budget ~91px  -> broke one word EARLY
  rectW/scale^2 -> effective budget ~110px -> broke one word LATE
  rectW/scale  -> effective budget 100px  -> breaks exactly where the
                  render does (94.6 <= 100 < 101.6)

All three observations fit budget_px = pxOf(param) x scale. A paper
derivation from the rebuild's node-budget chain predicted /scale^2 --
one hop of that chain models live behaviour wrong; the probe data is
recorded in the code comment so the broken paper chain doesn't get
re-derived. (FUN_00772B60 multiplying its width arg by fs+0x7C before
gxu, and FUN_0044DB50 normalizing through FUN_0041AE40, are verified
decompiles.)

Verified in-game: 100px box, wrapped 93.8 / one-line 165.7 / 2 lines,
break at the render's own position. Residual <=1px vs a direct measure
of the line text -- the engine's own per-glyph measure conventions
(ink-vs-advance, kerning-variant flag), the same class GetStringWidth
carries; documented in API.md.
2026-08-19 15:04:21 -05:00
Brues efc6b29b6b docs(fontstring): correct GetUnboundedStringWidth vs GetStringWidth
The entry claimed GetStringWidth measures inside the wrap box -- it
does not, on any client: both methods measure the string on ONE line
(verified in-game: a fontstring wrapping in a 100px box reports ~165px
from both). They differ only on modern clients and only for
ellipsis-truncated text, where GetStringWidth reports the displayed
width; 1.12's getter never applies truncation, so the two always agree
here. The as-rendered width (widest wrapped line) is GetWrappedWidth,
which 1.12 lacks.
2026-08-19 14:30:22 -05:00
Brues b09db4d5a5 feat(fontstring): backport GetUnboundedStringWidth, GetNumLines, GetLineHeight, SetFormattedText
Four modern FontString bindings 1.12 never shipped, all thin wrappers
over engine machinery already verified in this codebase
(fontstring/Metrics.cpp grows from the GetStringHeight backport into
the general metrics module):

- GetUnboundedStringWidth(): the substring measure
  (FUN_FONTSTRING_MEASURE_SUBSTRING) over the whole string (len 0).
  Icon-aware for free -- the call routes through the InlineTexture
  co-hook. Verified in-game it agrees with GetStringWidth to float
  noise, which is retail parity: both measure unwrapped (the classic
  gotcha; the rendered width is GetWrappedWidth, a future backport).

- GetNumLines(): render truth from the node's built-line count
  (OFF_TEXT_NODE_BUILT_LINES = 0x9C, the draw builder's own counter /
  early-out gate) once painted; for an unbuilt node, the engine's
  break-array computer (FUN_FONTSTRING_BREAK_ARRAY = 0x00772B60, the
  tooltip auto-size's own segment source -- icon-aware via the
  wrap-stepper hook) against the fs's rect width. Empty text 0; no
  wrap constraint 1. Verified: 165px text in a 100px box reports 2.

- GetLineHeight(): the fs font-height getter (FUN_007727b0) through
  the standard push conversion; excludes spacing, like retail.

- SetFormattedText(fmt, ...): resolves the LIVE string.format (addon
  replacements honoured), pcalls it over the varargs, propagates
  format errors as real Lua errors, and sets through the engine's
  FUN_FONTSTRING_SET_TEXT so sanitizer/escape handling is identical
  to SetText.

New Offsets entries carry the derivations; docs/API.md documents all
four under the FontString section.
2026-08-19 14:26:02 -05:00
Brues 0ce9d159e9 fix(text): wrap-shrink axis error; substring measure; trailing-icon trim
Three inline-|T measure fixes, the first one load-bearing for chat.

1) Wrap shrink was overscaled by the render aspect. The wrap stepper's
inputs are gxu-normalized PER AXIS -- fontH normalized-Y (x rasterY =
pen px), wrapWidth/outWidth normalized-X (x rasterX = pen px); both
caller flavors land there (the draw builder passes node+0x1C/+0x3C,
pre-normalized at block creation via FUN_0041ae50/ae40, and the
fs-level callers x-normalize inside FUN_0044d670 before gxu, verified
by decompile). The hook converted the pen-x icon sum with fontH/fontHPx
-- a Y-AXIS factor -- overshrinking the wrap budget by rasterX/rasterY:
x1.33 at the 4:3 setups it was calibrated on (subtle, and the
glyph-relative tolerances were inflated by the same factor, masking
it), x2.37 at 2560x1080 -- icon-bearing chat lines wrapped a word or
two early per icon. The correct pen-x -> width-units factor is
1/rasterX; the auto-width bail, feasibility band, escalation step and
bisect threshold now derive from fontHPx/rasterX so a "half glyph"
tolerance is an actual glyph width.

2) The substring measure (FUN_00772AE0, new Offsets entry) is now
icon-aware. An earlier note claimed nothing consumed it; its xrefs
refute that: the GameTooltip auto-size measures each WRAPPED SEGMENT of
a wrap-enabled line through it (breaks from FUN_00772B60, already
icon-aware via the stepper hook) and takes the max as the tooltip width
-- so icon-bearing wrapped tooltip lines undersized their tooltip. Same
pen-exact adjustment as the width hook; the editbox caret/selection
callers (10 of its 11 xrefs) keep measuring raw via the established
editable-bit / focused-buffer gates.

3) A string-final icon now reports its INK edge instead of its full
advance (TrailingIconTrimPen: subtract the trail half-pad + half the
outline ink when the text ends in a well-formed span), matching the
engine's own last-glyph convention -- the measure loop ends on ink, not
advance. Render/justify/wrap keep the full advance (the pen genuinely
moves); only the reported width changes. The visible beneficiary is the
money-string shape ("...|TCoin:0|t"): a right-anchored auto-width money
fs sizes to the coin's drawn edge instead of ~2px past it. Remaining
width residual is sub-pixel (region placement rounding + the base
loop's ~0 payload-0 token contribution).
2026-08-19 14:07:01 -05:00
Brues 23b622acff fix(text): snap inline-icon drawn rects to whole render-target pixels
Icon regions placed at fractional pen positions through the anchor
math, so 1:1-sized art (a 16px emote at :16) sampled between texels and
rendered soft. Snap the drawn rect in the flush, gated on the node's
pixel-snap mode (bit-7 clear -- the same condition the engine's glyphs
snap under): position rounds to whole pen px, and SIZE rounds
independently of position so a :16 icon is exactly 16px, never 15/17
from the two edges rounding apart. Floors at 1px.

An integral pen rect survives to the screen because pen px = render
px, the fsLeft/fsBottom terms cancel exactly through the anchor
round-trip (the engine adds the same rect corner back at resolve), and
the pool's width-convergence multiplier is linear.
2026-08-19 13:48:43 -05:00
Brues f806f17f40 fix(text): snap icon advances to pen pixels; make fs measure hooks render-exact
Two changes to the inline-|T pipeline, both anchored in the engine's
own conventions.

1) Post-icon text rendered on half-pixel positions. Native glyphs
always sit on INTEGER pen pixels -- the origin finalize rounds
(FUN_005cdf70) and every glyph advance is truncated (the emitter's
__ftol when node bit-7 is clear) -- but IconAdvancePen added a
fractional advance (w + 1.5 x fontH x 0.18 + ...), shifting every glyph
AFTER an icon onto half-pixel positions: bilinear-filtered, fuzzy or
ghosted post-icon text, with visibility depending on the machine's
filtering config (the "artifacting only on the text after the icon"
report). IconAdvancePen now truncates when the node snaps, the
centre/right justify pre-shift snaps the same way, and the wrap
stepper's shrink probes carry the real snap flag so the budget matches
the render advance exactly.

2) The fs-level GetStringWidth / GetStringHeight hooks now compute the
icon contribution in TRUE PEN PX -- the exact numbers the emitter
reserves, outline ink and snap truncation included -- and bridge it
into the getter's return space via the font height known in both
spaces (sumPen x fontHInt / fontHPen). ResolveFsPenFont replicates the
render chain hop for hop: nodeFontSize = internal x fs+0x7C /
[0x832A48] (the rebuild feeds internal x 0x7C to FUN_0044d420, which
normalizes it through FUN_0041ae50 -- a hop whose omission on first
flight undersized fontHPen ~40%, growing icon-bearing chat lines with
phantom tall-icon overflow and pushing money-tooltip coins off their
right anchor), floored at [0x801628]/rasterY = 2 pen px (the node
ctor), realized by the emitter's own height helper. The outline ink
resolves through face = [[fs+0xE0]+0x20] -- verified stored verbatim at
node+0x44 by FUN_005c1c30 -> FUN_005cd6d0. fs-built nodes are always in
snap mode (no fs-flag maps to node bit 7 in FUN_0044d420), so the
snapped sums are exact for every fontstring. Replaces the old
SetPoint-push-factor bridge, whose units cancelled for :0 icons but
could not express the truncation or the ink.

New Offsets: OFF_FONTSTRING_FONT_HANDLE (0xE0), OFF_FONT_HANDLE_FACE
(0x20), FUN_TEXT_NODE_INVALIDATE derivation notes extended; the 2.0
outline constant's double duty as the minimum font size is documented.
Remaining measure residual: only the engine's own trailing-icon
ink-vs-advance <=1px.
2026-08-19 13:31:46 -05:00
Brues e9407f6564 fix(text): follow text-colour changes on icon-bearing fontstrings
The glue AddonList greys a disabled addon's title through SetTextColor
RGB alone (gold <-> gray, alpha stays 1.0). An icon-bearing title
followed neither channel: the icons only ever mirrored the colour's
ALPHA byte, and the TEXT was frozen at its bake-time colour -- a
segmented (bit-3) node carries baked per-glyph colours, and the
engine's colour setter (FUN_005CCB40) skips the rebuild-invalidate for
bit-3 nodes because UNIFORM bit-3 text recolours live at paint. Plain
titles swapped fine; icon-bearing ones didn't.

Two mechanisms, matching what each colour channel means:

- Text: re-bake on base-RGB change, everywhere. The emitter stamps the
  node's base colour (node+0x2c) at bake; the flush compares it against
  the live value and, on an RGB divergence, calls the engine's own node
  invalidate (FUN_TEXT_NODE_INVALIDATE = 0x005CDEF0 -- exactly what the
  colour setter does for accumulation nodes: clears the built state and
  frees the page buffers, so the next paint re-emits). The re-bake
  recolours base-coloured glyphs while |c runs keep their own colours
  -- baked per-glyph RGB cannot be patched in place. Alpha-only changes
  still take the cheap in-place alpha mirror (fades animate per frame;
  every baked glyph carries the node alpha, so the byte-patch is safe).

- Icons: brightness-follow on the GLUE screen only. The pool's fade
  signal widens from the colour's alpha byte to the whole folded BGRA
  colors[0] dword (FsColorKey), so a pure-RGB SetTextColor now trips
  the change detector at all; FadedColor then scales the icon by the
  text colour's VALUE (max of R/G/B) when no local player exists.
  Value-follow dims but can never tint -- gold and red titles have a
  255-max channel, factor 1.0 -- and in-world icons keep following
  alpha only (retail semantics: guild-green chat must not tint emotes).

Verified on the glue addon list: toggling now swaps title text AND
icons together (gold + bright <-> gray + dimmed), |c-coloured segments
keep their colours through the re-bake.
2026-08-19 13:10:28 -05:00
Brues f42f7459e2 docs(text): update InlineTextureEscapes.md for the exact placement pipeline
Current design gains the verified coordinate-space story (pen units are
render-target pixels; per-axis K = raster / anchorExtent from four live
globals, with the failed empirical and SetPoint-factor forms recorded),
the glyph baked-alpha mirror, and the outline-ink pads. The bit-3
section documents the per-glyph colour consequence, the positioning
steps reference the per-axis conversion, and the width-hook section
explains why its own ~1468 factor is a different, self-cancelling
conversion from the placement K.
2026-08-19 12:32:15 -05:00
Brues 968335debe fix(text): place inline icons with the engine's exact pen conversion
Inline |T icon regions were positioned right only at the resolution the
placement math was calibrated on. Root cause: the pen->anchor scale (K)
was derived EMPIRICALLY (node origin / fs rect justify edge) -- chat
could never derive its own (its rect edge sits near screen x = 0 and
failed the divide-guard), so it rode a global cache seeded by whichever
fontstring derived first and clamped to +/-10% forever. Wrong seed =
icon size and position drifting together, amplified by screen distance
(the skull rendering lines away from its chat message).

The engine's own conversion chain, decompiled end to end this session:

  FUN_0041ade0: block/node positions are stored NORMALIZED -- fs-local
    anchor x / [0x832A44] (screen width in anchor units), y / [0x832A48]
    (its previously unmapped y sibling).
  FUN_005cdf70: node origin (+0x70/+0x74) = round(normalized x
    [0xC2B9A4 / 0xC2B9A0]) -- integer render-target pixel dimensions,
    justify shift and vertical align folded in.
  FUN_005c2b50: writes those raster ints from the live render-target
    rect; every font re-rasterizes when they change.

So pen units are render-target pixels and K = raster / anchorExtent,
per axis, from four live globals -- no calibration, no cache, no fs
scale term. Verified against a live probe: rasterX/anchorW matched the
measured origin/rect-edge quotient to four digits, and icons now land
correctly at 2560x1080 and 1024x768 (previously 1080p-only).

Also fixes the coin-into-digits clip the exact K exposed: outlined
faces (pfUI money bars) draw INK past the glyph advance, which the old
miscalibrated K had been masking with accidental slack. The engine
quantifies that ink itself (emitter prologue: face+0x180 bit 3 -> 4.0
pen px, bit 0 -> 2.0, both .rdata constants); OutlineInkPen reads the
same flags and constants, half leading and half trailing every icon,
threaded through the shared advance helper (emitter advance, justify
pre-shift, wrap-stepper shrink probes). The fs-level GetStringWidth
adjustment passes ink 0 (it cannot cheaply resolve the gxu face) --
outlined icon text measures 2-4px short per icon there; render-side is
exact.

New Offsets: VAR_TEXT_RASTER_X/Y, VAR_UI_ANCHOR_SCREEN_H,
OFF_FONTFACE_FLAGS, FLOAT_OUTLINE_EXTRA_THICK/THIN, each with the
derivation chain.
2026-08-19 12:28:30 -05:00
Brues 04d4bf3326 fix(text): inset rotated glyph UVs half a texel against font-atlas bleed
An axis-aligned glyph quad samples its atlas cell on exact texel
boundaries, so bilinear filtering never crosses into a neighbouring
glyph. A quad rotated by FontString:SetRotation samples along
diagonals, and at the cell border the filter pulls in texels from
ADJACENT cells -- rendering as dotted fragments of other glyphs strung
along the rotated text's edges. Machine-dependent (renderer, driver
filtering, resolution/UI-scale phase decide whether samples land inside
the cell), which is why it reproduced on a user's 1440p setup but not
locally.

The engine has the same hazard with its bit-7 font nodes and ships the
fix: FUN_TEXT_EMITTER's init-once block (0x005CCBE0) sets four globals
to +/-0.001953125 (half a texel of the 256px font page) and shrinks
each glyph's UV rect by that per edge. Mirror exactly that inset for
quads we rotate: InsetGlyphUVs walks the node's page buffers in
four-vert quads and nudges each vert's u/v toward the cell centre.

The rotation baseline now captures/restores UVs alongside positions so
the inset never compounds across restore->rotate cycles, and
SetRotation(0) puts the untouched cell edges back. Unrotated text is
unaffected.
2026-08-19 11:28:56 -05:00
Brues c54556f6a1 refactor: centralize engine field/global access via Game::Read/Ref/Ptr
Replace the raw `*reinterpret_cast<const T *>(base + Offsets::OFF_X)`
idiom (and its double-cast variant when base wasn't already a byte
pointer) with three typed accessors in Game.h:

  Game::Read<T>(base, offset)  field value read
  Game::Ref<T>(base, offset)   writable field lvalue
  Game::Ptr<T>(base, offset)   pointer to a field (arrays / out-params)
  Game::Read<T>(address) / Ref<T>(address)  fixed-VA globals

Pure mechanical refactor, zero behavior change: ~330 cast sites across
84 files collapse to 651 helper calls. Offsets stay in Offsets.h per the
single-source-of-truth rule — the helpers only remove the cast noise and
fold away the inner `reinterpret_cast<uint8_t*>(obj)` base casts.

Left as raw casts by design: FUN_* function-pointer casts, void*/char*
VA handles passed as arguments (caches, method registries), subobject-
anchor pointers fed to __thiscall helpers, `void *volatile` player-ptr
readiness gates (converting would strip volatile), and VA-as-array-base
captures that are subscripted later.
2026-08-19 11:01:19 -05:00
Brues bd14a93a11 fix(text): keep baked glyph alphas in sync with the fontstring's live opacity
Text with an inline |T...|t icon stopped respecting its parent frame's
alpha: the icon faded, the glyphs stayed fully opaque. Iconless text was
unaffected.

Root cause: a fontstring's live opacity (SetTextColor alpha x the frame
chain's effective alpha, re-folded by FUN_0077fac0 on every alpha
change) lands in the node's uniform colour at node+0x2c, which the
paint consults PER FRAME for uniform text. But a segmented icon line
carries baked PER-GLYPH colours (the emitter hook clears node-flag bit
3), which the paint copy-out FUN_005c8710 uses verbatim with no later
modulation -- and FUN_005ccb40 skips the colour-change rebuild for
bit-3 nodes, so those baked alphas never refreshed. On top of that the
emitter hook force-baked alpha 0xFF: a misdiagnosis of the pfUI-bubble
"black text" bug, where the observed 0x07 was the bubble's live folded
alpha at build time (it built while faded out), not a stale default.

Fix, systemic for both bugs:
- Drop the 0xFF force -- colorState's build-time alpha (a node+0x2c
  copy) is already correct.
- Mirror the node's live alpha byte into every baked glyph colour from
  the flush walk, change-detected per page (a byte compare per frame
  until an actual fade). Same signal and cadence as the icon fade
  mirror; bit-3-clear (chat) nodes excluded -- the engine re-bakes
  those on colour change itself.

Adds OFF_TEXT_PAGE_COLOR_COUNT (0x1C), OFF_TEXT_PAGE_COLORS (0x20) and
OFF_TEXT_NODE_COLOR (0x2C) to Offsets.h with the derivation chain.
2026-08-19 10:17:25 -05:00
fuffcandBrues 5978d7dd62 fix(texture): measure vertex offsets against the untouched layout rect (#27)
* fix(texture): measure vertex offsets against the untouched layout rect

* fix(texture): honor SetTexCoordModifiesRect instead of dropping the crop

The flag is not inert in 1.12. Script_SetTexCoordModifiesRect
(0x0079C080) writes the Lua boolean to region+0x124 and
Script_GetTexCoordModifiesRect (0x0079C120) reads it back (1/nil), and
all three FUN_REGION_TEXCOORD_CROP call sites gate on that field: the
4-arg and 8-arg SetTexCoord writers (FUN_00770410 / FUN_007704C0)
crop+store only when it is set, and the layout-resolve store path
(FUN_00770670) crops when set / stores the raw anchor rect when clear.
The earlier "toggling it changes nothing" probe was a timing artifact:
the crop applies at the next SetTexCoord or layout resolve, never
retroactively.

So instead of removing the crop call, ApplyFromRect now applies it
under the engine's own gate. Default state (flag clear) behaves exactly
as this PR intends -- untouched layout rect, wedges fixed -- while a
region that DID opt in keeps its offsets measured against the same
cropped rect the engine stores, so the immediate apply and the
corner-store co-hook can never disagree about the base rect in either
flag state.

Adds OFF_REGION_TEXCOORD_MODIFIES_RECT (0x124) to Offsets.h with the
derivation, and corrects the FUN_REGION_TEXCOORD_CROP comment that
implied a partial SetTexCoord always shrinks the drawn quad.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-08-19 09:44:11 -05:00
Brues 67172c95f7 feat(model): add Model:SetCreature; dress character displays natively
SetCreature(creatureID) resolves through the client creature cache to a
display ID, then loads like SetDisplayInfo (uncached entry = no-op,
documented with a RequestLoadCreatureByID recipe).

Character-based displays (extendedDisplayInfoID != 0) are now dressed by
the engine's own CharComponent compositor, mirroring
CGUnit_C::UpdateCharacterCustomization's NPC branch field for field:
baked body texture, hair/facial-hair geosets (CharHairGeosets,
CharacterFacialHairStyles), equipment geosets (sleeves, robe->trousers,
tabard), and helm/shoulder attachment models with HelmetGeosetVisData
hiding. Dress jobs run on WorldTick behind the engine's own
model-loaded gate, one compositor per Model frame, kept until the frame
loads another display or the reload teardown (PrepareForReload).

Attached helm/shoulder children additionally get the frame's light/fog
pre-render callback: the frame only registers it on its own instance,
so the children rendered pure black (verified in-game -- a light tint
colored the body but not the equipment). Weapons cannot show: NPC
weapons are server-pushed per spawned unit, not in any client table.

The manual baked-skin/hair-texture appliers are superseded by the
compositor and removed, along with the geoset debug probes
(_classicapi_ModelInstance/Peek/Poke).

Creature::Info gains a public DisplayID(creatureID) for the cache
resolve.
2026-08-19 09:28:30 -05:00
Brues 59c3bf9e0f feat(text): add FontString:GetGlyphVerts() introspection
The fontstring analog of Texture:GetCorners — returns the first glyph's
four baked vertex positions plus the bounding box of all glyph verts (12
numbers). Because the text paint (FUN_005c8710) is translate-only, these
node-local coords track the on-screen positions directly, so a 0-vs-90
dump reads the rotation direction arithmetically.

Also documents, on RotateVerts, why that dump can NOT settle rotation
CHIRALITY on its own: node-local glyph-vert Y handedness is not
determinable from the verts alone, so the visual comparison against the
retail-verified Texture:SetRotation is the arbiter. The RotateVerts sine
is unchanged (matches Texture:SetRotation / retail CCW-for-positive).
2026-08-18 19:27:11 -05:00
Brues 54782df95e feat(model): add Model:SetDisplayInfo(creatureDisplayID)
Backport the retail Model widget method (present since 5.4.8, string
verified in the 5.4.8 and 1.15.8 binaries) that points a Model frame at
a creature by its display ID rather than a raw .mdx path.

Resolve creatureDisplayID -> CreatureDisplayInfo[+0x04] ModelID ->
CreatureModelData[+0x08] ModelPath, load it through SetModel's own worker
(vtable+0x94), then apply the display's TextureVariation columns as
replaceable-texture skins (MONSTER_1/2/3 = slots 11/12/13). The DBC
column offsets are verified two ways: parsing the extracted 1.12 DBCs and
the engine's own unit-display resolver FUN_0060afb0.

Verified in-game: displays 13/330 (human NPCs) load correctly textured
and lit; missing assets fall back to the engine's error cube.

Only the single-model form is implemented; the optional mountDisplayID
(rider-on-mount) second arg is a separate follow-up.
2026-08-18 19:26:58 -05:00
fuffc 3ab690ac53 fix(texture): correct vertex-offset units and the corner-store contract (#26)
* fix(texture): correct vertex-offset units and the corner-store contract

The SetVertexOffset/SetRotation corner writes were wrong in four coupled
ways, found by driving pixel-ruler and wedge fixtures against a raw
corner-array readback:

- Offsets converted px->anchor with the global 1024-normalized factor
  alone, so a region scaled 0.9 got every offset 1/0.9 too large (a 24px
  request measured at 26.67px). Offsets are now stored in the caller's
  LOCAL pixels and folded through the region's live effective scale
  (+0x7C) inside WriteCorners, which also makes them track later scale
  changes. Verified at two scale points (0.9 and 0.45): a 24px offset
  lands at 24.00px on both.

- The anchor space is Y-DOWN (a rect reads top=0.222 < bottom=0.277),
  so +offsetY -- up, the retail contract -- is numerically negative
  there. It was added positive, sending every vertical offset the wrong
  way.

- The draw consumes the +0xD4 array with y INVERTED about the rect's
  horizontal midline, and CULLS a quad whose slot y-parity flips: quads
  stored at their target positions rendered as exact y-mirrors of the
  stored corners, and mirroring the values in place culled every
  transformed quad, including a plain rotated square. Each corner's
  mirrored data is therefore written into its VERTICAL PARTNER's slot
  (BL<->TL, BR<->TR): positions land on target after the draw's flip,
  and the slot parity keeps the winding the draw accepts. For an
  axis-aligned rect this degenerates to exactly what the engine itself
  writes -- which is why none of it was visible on plain rects or
  centered squares, both mirror-invariant as point sets.

- With that store contract, the y-down-transposed rotation matrix is
  the one that renders a positive angle counter-clockwise (settled with
  a rotated-bar fixture; squares and near-equilateral arrows are
  direction-blind).

Only regions carrying an active transform are affected: the corner-store
co-hook passes untracked regions through unchanged.

* feat(texture): GetCorners debug binding

texture:GetCorners() returns the raw drawn-quad corner array (+0xD4)
and the resolved layout rect -- 12 numbers, no unit conversion.
Diagnostic tooling: comparing stored corners against rendered pixels is
what made the corner-store contract measurable from Lua. Kept for
future transform triage; note that with the mirrored-partner store the
raw values deliberately differ from the on-screen positions.
2026-08-18 17:34:08 -05:00
Brues 6b13368e65 feat(fontstring): backport FontString:SetRotation / GetRotation
Generalizes the region-transform module (formerly texture-only) to serve
the FontString method registry too, backporting the modern
`fontstring:SetRotation(angle [, cx, cy])` and `GetRotation()`.

Rotation is visual only, matching retail: GetStringWidth/GetStringHeight/
GetRect/SetPoint stay axis-aligned. A positive angle is CCW, same
convention as Texture:SetRotation; the optional cx,cy pivot is a superset
of retail (centre-only).

How it works: the text paint copy-out (FUN_005c8710) is translate-only,
so a rotation baked into the node-local glyph verts survives to screen.
SetRotation rotates the live verts immediately (like the texture path)
around the vert bounding-box centre, idempotently via an axis-aligned
baseline snapshot (restore -> rotate). The baseline is re-captured on
every fresh vertex bake, wired through inline-texture's DrawBuilder
co-hook (gated on g_buildEmitSeq > 0 so clean paints never double-rotate,
since inline-texture owns every text-render hook). Node page-buffer
vertex layout added to Offsets.h (cross-verified across the emitter,
FUN_005c8710, and FUN_005ce0c0).

Known limitation: inline |T icons in a rotated fontstring don't turn with
the text (separate anchored regions). Plain text rotates correctly.
2026-08-18 16:54:42 -05:00
Brues 5456295e2e fix(item): throttle item-cache queries; prioritize carried items
Post-settle `WarmCache` fired one CMSG_ITEM_QUERY_SINGLE per item
immediately, and `OnWorldTick` escalation issued every pending item in a
single tick. A `/reload` that makes addons (pfQuest/Questie/Bagnon) look
up hundreds of items in one frame therefore emitted an unbounded packet
burst — a reported 1,325 requests in ~14 ms exhausted a consumer
router's NAT table and dropped the machine's internet connectivity.

Make `OnWorldTick` the single point that issues queries and rate-limit
it. All warmups now route through the pending queue (`WarmCache` ->
`Track`); background misses go out at most one per 50 ms (20/sec). The
timeout now counts only after a query is actually issued, so a throttled
backlog no longer fires spurious failures for items never queried.

To keep the throttle from delaying the player's own inventory on a cold
cache, add a priority tier: the carried items (equipment + backpack +
equipped bags) issue first on a separate budget (up to 6/tick, no
spacing floor). The owned set is a bounded snapshot built by a pure-C
inventory walk (no Lua stack — safe at world-tick time), refreshed at
most once per second and only while there is queued work. Peak issue
rate stays ~7 packets/frame, far below the flood.

Fixes #25
2026-08-18 15:31:33 -05:00
Brues 9b34ceff9e feat(unit): add UnitCreatureID(unit)
The unit-token twin of C_CreatureInfo.GetCreatureID — resolves the token
to a GUID and reads the creature-template entry vanilla packs into bits
24-47. nil for players, empty tokens, and non-creature/pet GUIDs.

Factor the entry extraction + creature/pet gate out of GetCreatureID into
a shared Guid::CreatureEntry so both callers use one source of truth for
the GUID bit layout.
2026-08-18 14:44:06 -05:00
Brues a373a775cf Clarify UnitSpellTargetName docs 2026-08-18 14:34:32 -05:00
Brues e9014801b6 docs: move UnitSpellTargetName to the Unit section
It's a Unit* function taking a unit token, so it belongs with the other
Unit calls, not under Spell. Relocates the API.md section + ToC entry and
the README calls-table row.
2026-08-18 14:28:20 -05:00
Brues dc8a510611 feat(spell): add UnitSpellTargetName(unit)
Returns the name of the unit a caster is casting/channeling a spell at,
or nil. The cast's target rides in SMSG_SPELL_START (SpellCastTargets:
u16 mask + packed GUID when TARGET_FLAG_UNIT) — we already parse that
packet for cast timing and just stopped before the target block. Extend
the parse to capture the target GUID for the player (g_castTargetGuid)
and remote units (RemoteCast.targetGuid), gated on an active cast so a
stale target is never returned.

nil when the unit isn't casting, the spell has no unit target
(self/ground/item), or the target's name can't be resolved.

Factor the GUID->name chain (object manager -> friends -> NameCache) out
of UnitNameFromGUID into a shared Player::Info::NameFromGuid so both
callers use one source of truth.
2026-08-18 14:23:59 -05:00
Brues d514dac465 docs(readme): mention inline-texture rendering in the Behaviors table
Adds a Behaviors row for the inline `|T…|t` texture backport (icons in
FontStrings, chat, and tooltips; icon-inclusive GetStringWidth/Height).
Raid marks were already covered by the `mark1`..`mark8` Unit tokens row.
2026-08-18 13:39:06 -05:00
Brues 621d1a9db9 feat(attributes): cast spell without a unit via CastSpellByName
A `type="spell"` click-cast button with no `unit` attribute did nothing:
the `spell` verb bailed the moment no unit resolved. Now it reads the
`spell` attribute first, then branches — with a `unit` it casts at that
unit via C_Spell.CastAtUnit (unchanged), and with no `unit` it falls back
to the plain global CastSpellByName on the current target, like `/cast`.

Fixes #18.
2026-08-18 13:28:54 -05:00
Brues 7d566f3787 fix(spell): stop false cast interrupts on grenades / movement-immune casts
Throwing a grenade and moving mid-cast fired a false UNIT_SPELLCAST_INTERRUPTED
and cut the bar short, even though the throw completed (issue #23). A cast is
interrupted by movement only if its Spell.dbc InterruptFlags carry
SPELL_INTERRUPT_FLAG_MOVEMENT (verified against the server's HandleMovement-
Opcodes and the client's own CheckCast); thrown items (e.g. spell 4068) lack it,
so the server never interrupts them on movement, but the engine still drops the
client cast-state, which our poll surfaced as an interrupt.

Fix: when the movement path clears a movement-immune cast WHILE THE PLAYER IS
MOVING (PlayerMoving mirrors the engine's 0x200f cast-drop mask), keep it tracked
instead of ending it; it then finishes as SUCCEEDED (no INTERRUPTED) or, if its
SPELL_GO never comes, ends a grace past its computed end. A real cancel/interrupt
happens with the player stationary, so it clears normally. Gated on a per-cast
latch, so normal (movement-interruptible) casts are unchanged.

Also de-dup UNIT_SPELLCAST_INTERRUPTED: the client fires Spell_C_SpellFailed AND
drops the tracked cast for the same interrupt (e.g. an Esc cancel), which fired
the event twice; PollPlayer now skips its own when SpellFailed_h already fired
one for the same spell. SuperWoW-style kicks (no Spell_C_SpellFailed) stay owned
by the poll.

New Offsets.h constants: SPELL_INTERRUPT_FLAG_MOVEMENT (InterruptFlags bit 0),
MOVEFLAG_MASK_CAST_DROP (0x200f). Wrap-safe deadline/window checks use
Time::Clock::Reached / Elapsed.

Fixes #23.
2026-08-18 13:10:11 -05:00
Brues acc9a85bc6 feat(spell): CastSpellNoToggle accepts an optional unit token
CastSpellNoToggle(name | spellID [, unit]) now takes a unit token as an
optional second argument, so the spell fires at that unit without
changing the current target:

    CastSpellNoToggle("Auto Shot", "focus")
    CastSpellNoToggle("Shoot", "targettarget")

The spam-safe toggle gates run first and are unchanged: if the requested
spell is already auto-repeating or its self-aura is already up, the call
stays a no-op and the unit is ignored. When the spell does cast and a
unit is supplied, it dispatches through the existing Spell::AtUnit core
(resolve token -> GUID -> dispatch) instead of the plain CastSpellByName
-- a unit-target/auto-repeat spell fires straight at the unit, a ground
spell lands at its feet, and an unknown token raises the engine's
standard "Unknown unit" error. No new offsets or hooks.

Fixes #22.
2026-08-18 12:02:04 -05:00
Petr KomogortsevandBrues 207d47c8b8 feat(bindings): backport direct-action and override binding APIs (#19)
* feat(bindings): backport direct-action and override binding APIs

Add SetBindingSpell/Item/Macro/Click plus the owner-scoped
SetOverrideBinding family. Store permanent commands through vanilla
SetBinding, execute SPELL/ITEM/MACRO/CLICK in the resolved-command hook,
and layer priority overrides ahead of the native binding table.

Factor raw and saved macro dispatch into Macro::Execute so click
attributes and binding commands share the same parser fallback. Preserve
key-down/key-up pairing when overrides change during an action.

Document return values, persistence, precedence, macro-text usage, and
the deliberate 1.12 differences in README and docs/API.md.

* fix(bindings): normalize override key order and preserve command exec-context

Two fidelity gaps in the override binding layer, both verified against the
1.12 binary:

- Override key matching now normalizes modifier order to the engine's own
  keypress form (ALT-CTRL-SHIFT- before the base key, per FUN_004b6630), so a
  caller passing "CTRL-ALT-F" matches the "ALT-CTRL-F" the engine builds at
  keypress. Prefix-stripping keeps the minus base key intact ("SHIFT--").

- Override-dispatched commands now run inside the same execution context the
  engine wraps around a native keypress (save/zero/restore DAT_00ceeac0, its
  nesting depth DAT_00ceeac4, and the manager +0xD8 mid-command flag, per
  FUN_004b7990). Without it, an ordinary Bindings.xml command routed through
  SetOverrideBinding ran without the context its handler expects. The native
  binding-table path is untouched (the engine already establishes context
  before the co-hooked FUN_004b7b50).

Adds the three verified offsets to Offsets.h and documents the any-order,
case-insensitive key handling in docs/API.md.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-08-18 11:32:30 -05:00
brues-code 76f48de67f Inline |T…|t texture escapes (with coin strings, texture methods, and TextureUtil) (#24)
* feat(text): inline |T...|t texture escapes in chat and display text

Backport modern inline-texture markup to the 1.12 text engine: |Tpath:h|t
renders an icon inline in FontStrings / chat, for BLP and uncompressed TGA.

- Rendering primitive: resolve a path to a resident CGxTexture via FUN_0044acf0
  and draw it as a textured quad through the UI text VB path.
- Positioning: co-hook the per-line glyph emitter (FUN_005ccbe0); render plain
  runs by delegating to the original per segment (threading the pen through
  linkState[4], read as a float), record icon quads at the pen, and flush them
  in the paint pass (FUN_005c8fe0) translated by each node origin. Handles the
  FontString pipe-doubling (|T -> ||T), the bit-3 per-call batch-clear mode,
  multi-icon and multi-line accumulation, and font-relative vertical centering.
- Measure/wrap: co-hook the shared tokenizer (FUN_005c2810) so an inline-texture
  span is one near-zero-width token, so icons no longer force early line wrap.
- Editbox exclusion: read the focused-editbox global (DAT_00cf4dc8) and suppress
  icon recording while an input field is focused, so editboxes show raw,
  editable markup while cached display text keeps its icons.

Diagnostic scaffolding (stats/capture Lua helpers) is still present. Follow-ups:
exact icon width in measure (hover-box accuracy), texcoords for sprite sheets,
vertex color, and the already-built editbox case. See docs/InlineTextureEscapes.md.

* fix(text): exclude editboxes from inline textures via node flag bit 6

Editable text (node flags [+0x5c] bit 6 / 0x40 -- verified in-game: the macro
editbox is 0x4D vs chat display 0x20D and FontStrings 0x0D) now shows raw,
editable |T...|t markup instead of rendered icons, checked per node in the
tokenizer, emitter, and flush. This is the 1.12 analog of 4.3.4's per-render
texture-disable flag (tokenizer bit 0x1000).

Replaces the earlier focus-global-only exclusion, which only caught single-line
inputs that rebuild on each keystroke; bit 6 also covers multi-line editors
(the macro editor) that build once while un-focused. The keyboard-focus global
(DAT_00cf4dc8) is kept as a fallback. Removes the failed monochrome heuristic.

Diagnostic scaffolding remains; a docs update and cleanup pass follow.

* feat(text): inline-texture texcoords + fix vertical flip

- Add the width / offset / texcoord fields to the escape
  (:width:offsetX:offsetY:texW:texH:left:right:top:bottom), so a sprite sheet
  such as UI-RaidTargetingIcons can be cropped to a single cell.
- Fix a vertical flip: the UI device backend is OpenGL (bottom-left texture
  origin), so top screen corners map to v1 and bottom corners to v0. The flip
  was invisible on symmetric icons but obvious on directional ones (raid-target
  markers, swords).

* docs(text): document the completed inline-texture RE map

Fold this session's findings into InlineTextureEscapes.md now that the feature
ships: the frame -> renderNode -> group -> node -> line render hierarchy;
segmented-delegation positioning (the float linkState[4] pen read, the bit-3
per-call batch-clear handling, first-line multi-line accumulation); font-relative
vertical centring; the FontString pipe-doubling (|T arrives as ||T); the shared
tokenizer measure/wrap fix; editbox exclusion via node flag bit 6 (0x40), with
the failed focus-global and monochrome attempts recorded so they aren't retried;
and the texcoord fields plus the OpenGL bottom-left vertical flip.

* chore(text): enable inline textures by default on this branch

* feat(text): inline-texture vertex colour tint (:r:g:b)

Parse the trailing r:g:b (0-255) positional fields of the inline-texture
escape and apply them as the quad's vertex colour, so |T...:r:g:b|t tints
the icon (the font stage's default MODULATE COLOROP does texture.rgb x
tint; white = untinted). The bytes pack to 0xFFrrggbb -- the same
0xAARRGGBB order the tokenizer builds for |cAARRGGBB text, verified from
FUN_005c2810's colour branch -- so the value flows straight into the
existing vertex colour slot. Threaded parse -> IconDesc -> IconRecord ->
DrawTexturedQuad. Verified in-game (red/green/blue/white diamonds).

Also record the hover-accuracy (measure-width) verdict in the docs: the
tokenizer reports an icon as ~zero width, so GetStringWidth/wrap/hit-test
undercount it. Scoped by disassembly (FUN_005c6940 width backend,
FUN_005c6b70 per-glyph advance, FUN_005cdc20/FUN_005c7260 wrap): the token
contract has no width field, there is no single cold choke, and the only
fixes are hot per-glyph hooks (against the MinHook-collision guidance) or
~6 parallel measure-loop hooks -- for a mostly-cosmetic gain. Deferred.

* docs(text): record editbox/measure findings; strip inline-texture debug scaffolding

No behavior change — functionally identical to the shipped inline-texture
feature. This captures what a long investigation established and removes the
temporary debug instrumentation added during it.

Comments (src/text/InlineTexture.cpp):
- The tokenizer's `flags & 0x40` gate is load-bearing for RENDER, not just
  measure: a suppressed editbox delegates to the ORIGINAL emitter, which
  re-enters the tokenizer to lay out glyphs, so bit 0x40 (EDITABLE) must make
  the tokenizer stand down or the macro editor draws BLANK instead of raw.
- bit 6 (NodeEditable) and the focus global (InputFocused) are COMPLEMENTARY,
  not redundant: bit 6 catches the un-focused macro editor; the focus global is
  the only signal for single-line focused inputs (chat box, pfChatCopyBox),
  whose nodes lack bit 6 (0x0D/0x20D, indistinguishable from display).
- Removed the tokenizer call/pipe/span counters and the ZZWIDTH TokCap capture
  (debug-only), and the now-unused g_lastFocused/g_lastMono stats fields.

Docs (docs/InlineTextureEscapes.md):
- Editbox exclusion: two complementary signals, and VERIFIED against retail —
  typing `|T` into a chat box or macro editor shows raw there too; only
  addon/system text renders. Our editbox-raw + display-renders split matches.
- Measure gap: added the focus-time caveat (icon ~0 width unfocused; counts the
  literal path text while an editbox is focused — the editbox-raw tradeoff).
- Vertex-colour tint documented in the descriptor-fields section.

* feat(chat): strip player-injected |T icon spoofs from chat + bubbles

Vanilla neutralizes player-TYPED escapes in chat (a typed |c/|H/|T shows
raw); only trusted text (addon AddMessage, shift-clicked links) renders
them. Our Text::InlineTexture backport broke that parity for |T alone: it
detects the neutralized ||T form and draws the icon anyway, so a player
could /say |Tpath|t and put a real icon in everyone's chat AND the speech
bubble over their head. This restores vanilla behavior for |T while leaving
|c/|r/|H/|h exactly as vanilla.

It can only be done at the chat source, not the text emitter: addon |T and
player |T reach the emitter as byte-identical ||T (vanilla doubles the
unrecognized |T for both), so the only place they differ is provenance --
server chat flows through the chat dispatcher FUN_0049A870, addon print does
not. That one function copies the message into a single buffer fed to BOTH
the chat frame and the say/yell bubble spawn (FUN_00608AC0), so sanitizing
on entry covers both. (ECX is the MESSAGE, not the "sender name" the old
note claimed -- verified from the call site in FUN_0049D560.)

Structure mirrors Net::PacketDispatch (one hook, fanned out), since MinHook
allows only one hook per target and this choke point already had the
GUID-capture concern on it:
  - Chat::Dispatch      -- single owner of the FUN_0049A870 hook; orchestrates
  - Chat::IconFilter    -- pure Sanitize(); no hook, no engine state
  - Chat::CurrentGUID   -- GUID globals + getter + DispatchScope RAII (no
                           longer owns a hook)

Defang detail (the subtle bit): the message arrives doubled (||T). Blanking
the PIPE would leave a lone `|` + space -- an INVALID escape the chat frame
tolerates but the bubble text setter chokes on, producing an empty bubble
that fades instantly. So we keep the `||` (a valid literal-pipe escape) and
blank the `T`; for a lone |T we blank both chars. No dangling `|`, no |T
opener survives. Verified in-game: typed |T shows raw in chat and bubble,
addon icons still render, colours and links untouched.

* feat(text): per-editbox inline-texture suppression

Inline-texture rendering was globally suppressed whenever any editbox held
focus (VAR_FOCUSED_EDITBOX != 0), so opening the chat box flipped every
rendered icon/emote in chat history to raw |T...|t.

Replace the global check with per-editbox buffer correlation: suppress inline
rendering only for text that belongs to the FOCUSED editbox, matched by
pointer range against its own text buffers. Chat history keeps rendering while
you type.

The editbox keeps its text in two buffers (both verified via Ghidra), and both
must be matched or the field desyncs (raw width but a rendered icon):
- INPUT buffer ([fe+0x32C]/[fe+0x334], selected by [fe+0x318]&8) — the
  caret/width MEASURE path reads it in place (FUN_0077da80 -> FUN_00772ae0 ->
  FUN_005c6940, which loops the tokenizer).
- DISPLAY buffer (*([fe+0x328]+0xF0)) — a SStrDup'd copy the editbox actually
  RENDERS from (FUN_00771d80); the emitter node text and the re-entrant render
  tokenizer see this one.

TextInFocusedEditbox() bounds each buffer by a tight strlen (distinct heap
allocations -> no false-match cap) and runs only on pipe-leading tokens after a
null-focus short-circuit, so it stays off the hot path. A display FontString
measured while an editbox is focused matches neither buffer, so its icons now
measure correctly -- an improvement over the old global.

Editbox struct offsets centralized in Offsets.h (OFF_EDITBOX_BUFFER_SELECT /
BUFFER / BUFFER_MASKED / TEXT_FONTSTRING).

* feat(chat): raid-target marker substitutions ({rt1}/{skull}/…)

Expand the modern raid-target marker tokens in chat into inline icons, backported
onto the inline-texture renderer. {rt1}..{rt8} plus the named aliases ({star},
{circle}/{coin}, {diamond}, {triangle}, {moon}, {square}, {cross}/{x}, {skull};
case-insensitive) each become a |T escape cropping Interface\TargetingFrame\
UI-RaidTargetingIcons to the matching 64x64 cell (mapping verified against the
client's UnitPopup.lua: col=(N-1)%4, row=(N-1)/4).

Chat::RaidMarkers::Substitute runs in Chat::Dispatch AFTER the |T anti-spoof
sanitize, so players get the fixed, safe marker icons without a path to inject an
arbitrary texture. It emits the pipe-DOUBLED ||T…||t form: the inline emitter
renders both, but this is what survives into speech bubbles — the vanilla bubble
text builder (FUN_004b1600) truncates a lone |T while preserving ||, and pfUI's
bubble reskin copies the bubble's FontString text into its own FontString, which
then renders the icon through the normal paint path. (This is the form bubbles
rendered before the anti-spoof filter defanged the ||T opener.)

InlineTexture emitter fixes for the standalone-FontString (bit-3, batch-clear)
render path that bubbles/tooltips use — chat lines are unaffected:
- Colour: clearing bit 3 switches the engine to per-glyph colour from
  colorState=[node+0x2c], whose alpha byte is a stale ~0x07; force the glyph
  alpha opaque (keeping RGB) so a FontString coloured via SetTextColor with plain
  text doesn't render near-transparent (which showed only pfUI's dark outline =
  "black text"). |c-coloured text already has full alpha, so it's a no-op for chat.
- Horizontal justify: the engine positions centre/right-justified text using the
  MEASURED width, which counts inline icons as ~zero (the measure gap), so the
  rendered line overflows its box. Pre-sum the line's icon widths and shift the pen
  (half for centre, full for right) so text+icons justify as a unit.
- Default centerFrac 0.5 -> 0.6 (better vertical centring across chat + bubbles).

* fix(text): suppress inline textures in editboxes by content match

The per-editbox suppression missed the chat input box: a pasted `|T…|t` rendered
as an icon instead of raw markup. An in-game probe showed why — the editbox
renders its text through a TRANSIENT copy: same bytes as the input buffer, but a
distinct heap allocation with no pointer link to the editbox in either direction
(every offset/back-pointer scan of fe / its FontString / the render node came back
-1). So the prior pointer/node-identity checks (input buffer, SetText copy,
FontString +0x48, node == *(fe+0x328)) could never match the render.

Match on CONTENT instead:
- Emitter: EmitLineIsFocusedEditbox compares the render line's bytes against the
  focused editbox's input buffer (the emitter is handed the whole line, so a
  bounded strcmp identifies it). Chat-history lines differ, so their icons keep
  rendering while an editbox is focused.
- Measure (caret/GetStringWidth): unchanged pointer path — the tokenizer reads the
  input buffer in place, so TextInFocusedEditbox still matches by range.
- Re-entrant render: the suppressed emitter brackets its delegated raw layout with
  a text range (g_reentryLo/Hi); the tokenizer stands down across the whole span
  via TextInReentry, so `|T` isn't eaten as a zero-width token (which drew BLANK).

Drops the dead node-identity/second-and-third-buffer heuristics. Covers any focused
input (chat box, pfChatCopyBox, macro editor).

* fix(text): drop stale icon records for reused chat line FontStrings

Inline-texture icons could paint as a ghost strip at the bottom of the screen
after chat had been busy for a while. The chat frame reuses its line
FontStrings: when a line is cleared (text set empty) or reused for markup-free
text, the draw builder early-returns on it, so the emitter never runs — and so
never erases that node's old icon record. The paint flush still walked the node
and drew its now-stale record at the FontString's parked position.

Gate the flush draw on the node's LIVE text still containing `|T`: if a node has
an icon record but its current text has no markup, the record is stale — drop it
and skip drawing. Kills the bottom-of-screen ghost.

(The separate scroll-freeze — icons only refreshed on the chat's dirty repaints —
is a different, deeper issue tracked next.)

* fix(text): stop chat icons vanishing — suppress only input boxes, not editable chat display

pfUI renders the chat scrollback through EDITABLE nodes (flags 0x45: bit 6
editable, no bit 3). The inline-texture emitter's blanket NodeEditable gate
suppressed inline rendering for ALL editable nodes, so those chat icons blanked
whenever that display was live — during scroll and as messages arrived, which
read as icons "disappearing/reappearing."

Gate suppression on a true INPUT box instead: editable (bit 6) AND bit 3 (0x08).
Macro editor 0x4D and name/chat input 0xC8 all carry 0x08; the chat scrollback
0x45 does not — so real input boxes still show raw |T markup while the chat
display keeps its icons. Also drop the flush's NodeEditable draw-gate: a
suppressed input box never records, so any record reaching the flush is a real
display line.

Pointer/content match alone can't cover a focused input box because its render
form is pipe-doubled (||T) while the input buffer is single-pipe, so the compare
misses.

* feat(text): inline |T icons as fontstring-anchored engine regions

Port 4.3.4's CSimpleEmbeddedTexture model. Each icon the emitter records
becomes a pooled CSimpleTexture ANCHORED TO ITS OWNING FONTSTRING,
configured off-render on the WorldTick, and drawn by the engine's own
region pipeline. 1.12 chat lines are real CSimpleFontStrings (the
ScrollingMessageFrame display refresh FUN_00788750 drives one per visible
line), so a co-hook on CSimpleFontString::RebuildString (0x7724A0) maps
every text node to its owner and one mechanism covers chat, tooltips, and
standalone FontStrings.

This replaces the raw-GxU-quad renderer and every overlay attempt:
- engine-drawn regions keep their textures resident: no flicker, verified
  across three concurrent clients
- the anchor system moves icons with their lines: scroll costs nothing
- icons mirror the owner's shown state: faded lines hide their icons
- all engine mutation happens outside the render pass: no pending-layout
  corruption, survives /reload (pointers dropped in PrepareForReload)
- placement verified pixel-exact against owner rects

RE landmarks recorded in Offsets.h:
- fs+0xF8 is an HTEXTBLOCK handle; the text node is at handle+8
- Show (0x77FCB0) no-ops unless desired-shown (+0xC4) is set, and
  SetParentAndLayer(show=0) clears it on reparent
- the renderer draws the corner array (+0xD4), stored from the rect by
  SetTexCoord - realize (0x768060) must run between SetPoint and
  SetTexCoord or the corners go stale (the historical invisible-icon and
  frozen-top-left-icon bugs)
- pen coords are y-down from the owner fontstring's BOTTOM edge; anchor
  offsets use Script_SetPoint's pixel scale (LinePool::PixelToInternal)

* refactor(text): inline |T icons = pixel-perfect quads + residency holders

Replace the fontstring-anchored region approach with a hybrid that
decouples position from residency, because the two live in different
coordinate spaces that no single scale could reconcile:

- POSITION: draw each icon as a raw GxU quad in the text engine's own
  render space (pen + node origin), the same coordinate system and
  dynamic VB the glyphs use. Pixel-exact by construction — no anchor/
  layout-space conversion. This is the original quad math; the region
  detour proved pen-space and anchor-space differ by the text paint's
  projection, not a scalar, so region anchoring could never be exact.

- RESIDENCY: a raw quad binds an unowned texture the engine evicts under
  VRAM pressure (the flicker on scroll / blank on a 2nd client). So for
  each distinct texture path, Text::InlineTexturePool creates ONE managed
  CSimpleTexture, draws it every frame (a ~2px, alpha 1/255 corner box),
  and never touches it again — its engine-managed draw is the live
  reference that keeps the texture resident for the quads to bind.

Verified in-game: icons pixel-perfect across chat / bubbles / wrapped
lines / sizes / tint, no flicker on scroll, and two concurrent clients
both render — the residency-holder premise (untested before: the earlier
"disproof" had non-drawing holders) finally validated with a holder that
actually draws. Non-zero holder alpha is load-bearing: a fully
transparent region gets culled and residency is lost.

Diagnostics (probe, perf counters, scale/bias tune knobs) stripped; the
SEH fault guard on the flush stays.

* feat(text): render inline |T icons as engine regions anchored to their fontstring

Replace the raw-quad + residency-holder hybrid as the default renderer with
the 4.3.4 CSimpleEmbeddedTexture model: one pooled CSimpleTexture per visible
icon, anchored RELATIVE TO THE OWNING FONTSTRING. Engine-drawn, so texture
residency (the chat scroll flicker / blank 2nd client) is impossible by
construction; engine-anchored, so icons track their line for free.

The pen<->anchor bridge that unblocked this: RebuildString (0x7724A0)
multiplies every text-unit quantity by fs+0x7C when creating the text node,
and the node origin is the fontstring's justification anchor point mapped by
a single measurable scale K (verified with two-position probes: origin =
rectJustifyRef x K, K ~ 1470 = physical px per anchor unit, both axes, no
drift). Placement pipeline:

- RebuildString co-hook records node -> owning fontstring (a node only
  speaks for its fs while it IS fs+0xF8->block+8, killing the stale-node
  clear race around rebuilds).
- The paint hook converts each icon's pen-space quad through K and queues
  fs-relative placements; regions are keyed BY FONTSTRING (nodes die on
  every SetText - node keying orphaned regions into an accumulating wall).
- Placements apply on WorldTick, never mid-render. SetPoint offsets are
  divided by the region's effective scale (+0x7C; anchor resolution
  multiplies stored offsets by the scale chain - measured 0.0319 stored ->
  0.0290 resolved = x0.91), then converged exactly by a per-region rect
  readback correction each tick (deterministic, self-healing; a same-call
  readback read stale pooled rects and shipped 7.4px crests).
- Engine SetTexCoord (0x770410) takes the 4-float rect Y-FIRST INTERLEAVED
  {v0,u0,v1,u1} (diagnosed in-game: {u,v,u,v} rendered the raid-mark moon
  as the circle cell); it is absolute, and the +0x124 shrink-by-UV-span
  flag stays clear so crops stretch to the rect like modern clients.
- Expired/hidden lines are swept every tick (regions parent to the chat
  frame, not the line, so they cannot inherit the line's own hide).

The quad renderer and residency holders remain behind
_classicapi_InlineTexMode (0 = quads, 1 = regions [default], 2 = overlay
A/B) as the bring-up oracle, plus diagnostics (_classicapi_InlineTexProbeFS
/ RegionDump / RegionCal / HolderCfg). Calibrated residual: RegionCal
(3, -1) pen units.

* fix(text): apply the inline-icon LEAD pad at draw time

The emitter reserves w + 1.5x pad in every inline icon's advance (lead 1x,
trail 0.5x), but FlushLayout drew the icon at the raw pen - all reserved gap
landed AFTER the icon, none before. Mid-text icons looked balanced only
because their surplus trailing gap padded the following text; a string-FINAL
icon (the money-string copper coin) sat jammed against its digits, and the
locale format strings had grown per-coin offsetX hacks to compensate.

Draw at pen + w x iconPadFrac (quads and regions share the cx), matching the
emitter's reservation. The coin formats drop to zero offsets - verified
against the texture itself: the three coin arts in UI-MoneyIcons are
byte-identical in alpha (same bounds, same center of mass, measured from the
exported BLP's DXT3 data), so no coin ever needed a positional nudge.

RegionCal's baked x constant drops 3 -> 0: the +3 calibrated pre-fix was
exactly this missing lead pad (user re-calibrated (0,-1) post-fix). The 1px
y residual remains the pen->anchor map's one true constant.

* fix(text): make inline-icon state lifetime-exact; fix every scroll-landing loss

Chat icons randomly landed shown-or-hidden when lines scrolled, and stale
icons ghosted at parked positions. Root causes, each found by in-game
triangulation (FsDump/Broken/Stats diagnostics, included), all fixed:

- Placements are FS-RELATIVE, computed at PAINT time in one coherent
  snapshot (icon coords + fs rect in the same flush). The old apply-time fs
  rect read raced the chat relayout after SetText and parked icons off
  their line, where the dedup froze them.
- The queue tail gate now matches the per-icon build gate EXACTLY (incl.
  K); any not-ready input skips-and-retries instead of queueing {} - an
  empty queue froze lines iconless via the dedup (early-session K window).
- K (pen->anchor scale) is derived PER NODE from its own fontstring - pen
  space scales with each fs's frame-scale chain, so a global chat-derived K
  mis-sized icons on differently-scaled fontstrings. Global cache kept as a
  +/-10%-clamped fallback.
- Stuck-blockless fontstrings (RebuildString releases the block on a
  SetText that lands on an unresolved rect and never rebuilds; the zombie
  node keeps painting) are re-dirtied so the engine rebuilds - the icon
  pipeline then resumes naturally.
- First-line-of-build detection comes from a draw-builder co-hook
  (FUN_005CDC20) build stamp - exact - with the old text-pointer heuristic
  only as fallback for emitter paths outside the builder.
- THE LIFETIME FIX: co-hook the gxu text-node free (FUN_005CD950, the
  single site where every node dies and its address becomes reusable) and
  erase ALL per-node state there. Anything in the maps now refers to a
  live node by construction: inherited ghost records on recycled nameplate
  fontstrings, orphaned owners (dropNoFs 61k -> 0), and reload leftovers
  lose their mechanism of existence.
- Ghost guard rescans the FONTSTRING's text (fs+0xF0, proven trustworthy),
  not the node text pointer (which lied on pfUI chat lines and made the old
  scan erase LIVE records every frame - the persistent iconless LFG lines).
  False matches can only false-keep, never false-erase.
- Freshness TTL: regions stay only while the paint keeps re-queueing their
  fontstring (deduped touches count); parked/orphaned fs regions expire in
  ~1s. Do NOT build-version records against the builder counter - the
  builder runs every paint but only emits when dirty, so a version check
  erases good records on every clean paint (the all-icons-gone regression).

Diagnostics added (Lua): _classicapi_InlineTexFsDump (pipeline triangulation
with chain classification), _classicapi_InlineTexBroken (names the broken
lines), _classicapi_InlineTexStats gains queued/drop/nudge counters and the
SEH fault address.

Also removes the FrameTick glue-screen attempt (b164d68): hooking the UI
render root regressed in-world chat; glue-screen icon support will be
re-approached without touching the in-world render path. The
FUN_UI_RENDER_ROOT offset stays documented for that retry.

* fix(text): pointer probes must allow Large-Address-Aware heap (>2GB)

LooksReadable capped plausible pointers at 0x7FFF0000. This client is LAA
(VanillaFixes), so heap allocations above 0x80000000 are valid and routine
once the heap grows - and the flush's layout walk BREAKS on an "unreadable"
node, so a single high-heap node silently truncated the walk and every node
AFTER it in the layout list lost its icons. That was the irreducible random
per-ROW missing-chat-icon bug that survived every renderer architecture
since the guard shipped with the first inline-texture commit (aa94ea5): it
fired only when the allocator placed a node/fontstring above 2GB, varying
per session with addon load and uptime. The same check also rejected
high-heap fontstrings (dropNoFs storms, "unreadable" owner chains).

Bound raised to 0xFFFF0000 in both copies.

Diagnosed with the per-node build/emit instrumentation added here: the
smoking-gun Broken() trio was builtKnown=1 (engine built the node),
emitOutcome=8 (emitter recorded its icons), nodeSeenAge=-1 (our walk never
once saw it). _classicapi_InlineTexBroken now reports both new fields.

* feat(text): render inline |T icons on the glue (login) screen

Inline icons never appeared on the login / character-select screens: the
text-pipeline hooks are engine-generic and fire on glue (the |T spans are
consumed there), but InlineTexturePool::Maintain - the step that creates and
shows the icon regions - was driven by Tick::WorldTick, and FUN_WORLD_TICK
(0x0066FD50) is the world-simulation tick, silent on glue. Queued placements
were never applied.

Add Tick::FrameTick, hooked at FUN_UI_RENDER_ROOT (0x00764330) - the
CSimpleTop singleton's per-frame render callback, registered by both the
world-init (FUN_0048FBF0) and glue-boot (FUN_0046A7B0) paths and drained
every frame by the master scene-render pump. Subscribers run at the tail of
the callback (strata walk complete, no frame mid-draw). The pool's Maintain
moves onto FrameTick as its ONLY tick: one driver, fires wherever the UI
renders.

An earlier version of this change was blamed for an in-world chat regression
and reverted. That regression was the Large-Address-Aware pointer-bound bug
(dc61f77) rolling its allocation dice at the moment the tick moved - the
symptom persisted after the revert, which already exonerated the hook.

Glue boot (LoadGlueScriptFunctions_h) now also clears the inline-icon maps:
the world->glue teardown bulk-frees every world fontstring and text node they
reference (glue->world was already covered by FrameScript_Initialize_h, and
the node-free hook covers individual deaths in both states).

WorldTick keeps its world-only subscribers (aura eviction, cast state, raid
targets) - they read world state that is null on glue; the two ticks stay
semantically distinct: WorldTick = "world advanced", FrameTick = "a UI frame
is rendering".

* feat(text): icon-inclusive GetStringWidth + FontString:GetStringHeight backport

GetStringWidth now counts inline |T...|t icons. The old "deliberate
measure gap" analysis was right that the gxu engine has no cold choke
(parallel measure/wrap/hit-test loops, no width field in the token
contract, hot per-glyph helpers) - but the choke sits one level up:
FUN_00772890 = CSimpleFontString::GetStringWidthInternal, a cold,
MinHook-safe funnel for exactly 4 callers (Script_GetStringWidth,
GameTooltip auto-size, editbox caret positioner, effective-width
vmethod). The co-hook calls the original and re-adds the icon advances
the tokenizer hook hid, so measured width matches rendered width - and
tooltips/auto-width layout now size correctly for icon lines.

Shared-source refactor so measure and render can never disagree:
- InlineInterceptActive: the tokenizer's stand-down set factored into
  ONE predicate (tokenizer passes gxu flag 0x40; the width hook passes
  fs+0x120 & 0x1000, the fs-level bit FUN_0044D670 translates into it,
  so editbox carets keep measuring raw markup).
- IconAdvancePen/SumIconAdvances: the emitter's reserved advance
  (w + 1.5*pad + positive offsetX) factored out and shared by the
  emitter loop, the justify pre-shift, and the width hook. Side fix:
  the justify pre-shift previously omitted the positive-offsetX term.

Units (bit us on first flight): escape sizes are UI pixels; convert
px->anchor by the push factor K = [0x832A4C]*1024/[0x832A44] (~1468),
NEVER by fs+0x7C - that's the layout UI scale (~0.68), and dividing by
it measured a 16px icon as +44k px. The hook never writes the fs+0xFC
cache (original may serve cached; the sum is re-added per call).
Verified in-game: delta +19.5 for a 16px icon = 20.32 exact advance
minus the known 0.8 trailing-icon ink-width residual. Wrap-break,
substring measure, and hit-test stay icon-blind (documented).

FontString:GetStringHeight() (2.3.0+ binding) backported in new
src/fontstring/Metrics.cpp: 1.12 already ships the internal wrap-aware
getter FUN_007729B0 (cache fs+0x100, lines*fontH + (lines-1)*spacing,
same wrap engine the render uses, empty -> 0) - it just was never
bound. Registered on the FontString method registry; mirrors
Script_GetStringWidth's resolve + anchor->px push conversion.
Verified in-game: one-line 11.7, wrapped 46.9 (4 lines), empty 0.

* fix(text): wrap lines account for inline icon advances

Wrap decisions measured inline |T icons as ~0 (the tokenizer hook), so
icon-bearing chat lines broke as if the icons weren't there and the
emitter's real advances ran past the frame's right edge.

Choke: FUN_TEXT_WRAP_STEPPER (0x005C7260), the wrap-stepper dispatcher
that lays out one wrapped line per call. Its exactly 4 callers are
every wrap consumer - the draw builder (render breaks), the height
measure (GetStringHeight), the chars-that-fit counter (ellipsis), and
the break-array computer - so one co-hook keeps render, height,
truncation, and break arrays mutually consistent. outBreak and
outNext-text are byte counts (==len means "all fit"); outWidth is the
measured icons-at-zero line width in the caller's units.

The hook shrinks the wrapWidth argument by a minimal feasible shrink,
found by probing the stepper sandboxed (local out-params + a copy of
the p10 first-line state byte): feasible(s) iff the line's icon
advances fit in the shrink plus the spare the break left
(iconSum <= s + probeW - outWidth). s=0 feasible -> no shrink (the
common fits-anyway case); otherwise escalate by the measured deficit,
then bisect the [infeasible, feasible] bracket to a quarter-glyph
(<=8 probes). Never overflows; packs each line to its physical
capacity. Gated on the shared InlineInterceptActive predicate + the
editbox flag bit 0x40 the dispatcher already carries.

Unit trap #2 (cost one flight): each caller passes fontH/wrapWidth in
its OWN space - node text units from the builder, the small
anchor-converted space from the fs-level callers chat wraps through.
px -> caller units = fontH / FUN_TEXT_FONT_HEIGHT(flag, fontH), the
engine's own pixel realization of the fontH param (FUN_005C6940's
final scale proves the convention for every gxu caller).

Rejected en route (documented in docs/InlineTextureEscapes.md): raw-px
subtraction (shredded lines to 2-glyph fragments), whole-remaining-
text sums (8-icon line -> one word per line), icon-count fixed-point
iteration (oscillates - 55-byte zero-width escapes make the
break<->count coupling discontinuous), max/average tiebreaks.

Cross-checked against 4.3.4 (renders |T natively): Blizzard extended
the token contract instead - texture token type 7 + a shared parser
(FUN_00617ba0) called inline by all five layout loops, fontH passed in
for :0 defaults, plain width, no padding. No single-choke trick exists
at source level; the probe search is the 1.12-shaped equivalent.

Diagnostics: _classicapi_InlineTexWrap(n) dumps the last 8
icon-bearing calls (widths, per-probe sums/breaks/raw out-params,
final shrink, floor hits).

* fix(text): wrap-shrink search refinements from in-game shakeout

Three fixes to the minimal-feasible-shrink search (2450522), each from a
live regression the _classicapi_InlineTexWrap diag pinned down:

- Full bracket bisection (<=8 probes, quarter-glyph epsilon). The first
  cut abandoned the [infeasible, feasible] bracket after one stale
  escalation candidate, costing the Marks harness line a whole
  mark+word pair per line (3+5 instead of the optimal 4+4).

- Half-glyph feasibility tolerance. The width hook and the wrap hook
  derive the icon sum through different unit chains (FUN_007727B0xK vs
  FUN_005C6FA0 ratio, OUTLINE extras, the trailing-glyph ink/advance
  quirk); the drift can read "fits exactly" as "1px over" and shrink a
  zero-slack line. Genuine icon overflow is >= a full icon, so half a
  glyph separates drift from real overflow.

- Auto-width bail (all text fits at s=0 AND slack <= 1.5 glyphs). A
  single-anchor, no-width fontstring (pfUI's addon-list labels) wraps
  at its own text-only measure plus a ~1-glyph engine margin (measured
  1.07xfontH), so icons "never fit" its budget - but the box is
  synthetic, icons draw past it harmlessly, and any shrink FABRICATES a
  wrap ("Twitch Emotes" split across two lines). Real frames stay
  covered: overflowing lines break, fitting lines carry frame-sized
  slack (Marks measures ~3.5xfontH). The narrow give-up band - text
  within 1.5 glyphs of exactly filling a real frame - reverts to the
  pre-hook overflow, bounded by the line's icon sum.

Diag reshaped for /dump's ~30-value print cap: 8 numeric headers plus
ONE pass-summary string (shrink candidate, icon sum, line length, raw
outBreak/outNext/outWidth per probe), so no record truncates.

* feat(texture): add Texture:SetRotation via corner-vertex rotation

Backports the modern texture:SetRotation(angle [, cx, cy]) method, which
vanilla 1.12 lacks entirely.

4.3.4's SetRotation (Script FUN_0052cb50) rotates the four texture
COORDINATES around a centre and feeds the 8-arg SetTexCoord, which clips
the corners of an off-axis square. 1.12 can't mirror that — its
CSimpleTexture::SetTexCoord takes only a min/max UV rect.

1.12 has a cleaner seam: a CSimpleTexture stores its drawn quad as four
independent corner positions at +0xD4, and the draw enqueue (FUN_00772fd0)
hands region+0xD4 straight to the vertex batch as four free vertices — no
axis-aligned rect is re-derived. So rotating those four corner positions
draws a truly rotated quad with no corner clipping.

The engine fills the corners axis-aligned from the layout rect via
FUN_REGION_STORE_CORNERS; a co-hook there re-applies rotation right after
each store, so a static rotation is written once and costs nothing per
frame while moves/resizes re-rotate automatically. Angle is radians
(positive = counter-clockwise); optional (cx, cy) is a normalized pivot
in [0,1], default centre; an angle of 0 clears.

Per-region state keys on the raw region pointer and is cleared on /reload
and world->glue (Texture::Rotation::PrepareForReload). A texture freed and
instantly re-pooled mid-session could briefly carry a stale rotation —
accepted; a destructor-evict hook is the later hardening.

New in Offsets.h (all verified against WoW.exe): OFF_SIMPLETEXTURE_CORNERS,
FUN_REGION_TEXCOORD_CROP, FUN_REGION_GET_RECT.

* feat(texture): add Texture:SetVertexOffset, generalize corner transforms

Backports Texture:SetVertexOffset / GetVertexOffset (plus GetRotation),
generalizing the SetRotation module (texture/Rotation.* -> texture/Transform.*)
into one corner-transform primitive that backs both methods.

Both write the four drawn corner POSITIONS at region+0xD4 — the vertices the
draw enqueue FUN_00772fd0 hands straight to the batch; no stock 1.12 function
exposes them. Per-region state widened from an angle to {rotation, four vertex
offsets}, applied through the same FUN_REGION_STORE_CORNERS co-hook: after the
engine writes the axis-aligned corners, rotate about the pivot, then add the
offsets. The two transforms compose (matching retail) and persist across layout
resolve / move / resize / SetTexture with no per-frame cost.

SetVertexOffset offsets are UI coordinate units (like SetPoint x/y), converted
to the engine's internal layout space with the same factor Tooltip::LinePool
uses; +y is up. vertexIndex maps to a corner via VertexSlot; the
UPPER_LEFT_VERTEX / ... constants are defined FrameXML-style in the embedded
addon's Util/Constants.lua.

Non-inverting warps (perspective, skew, trapezoid, wave) are free; a warp that
mirrors the quad past edge-on inverts its winding and the region draw culls it
(documented).

* feat(texture): add Texture:SetColorTexture

Backports the 7.0 SetColorTexture(colorR, colorG, colorB [, a]) as a second
name on the engine's own Script_Texture_SetTexture handler (0x0079BB40): its
numeric branch already clamps r/g/b/a to [0,1] and fills a solid colour via
FUN_00770360 (the string branch loads a path). So SetColorTexture is exactly
vanilla's numeric SetTexture form under the modern name — zero reimplementation,
with the clamp and opaque-alpha default coming straight from the engine.

The alias also accepts a path string (a harmless superset of the retail
contract). SetDesaturated / IsDesaturated are already native (real Desaturate.bls
pixel shader); SetDesaturation is not addable — vanilla desaturation is a fixed
effect handle with no strength constant in the setter, draw command, or effect
table.

* fix(text): correct the emitter's lazy pen read-back; drop quad render mode

The inline-icon emitter hook threaded the pen between text runs by
reading the engine's linkState[4] after each delegated run. That value
is LAZY (verified in FUN_005ccbe0): the engine places each glyph at
pen + pairAdvance(prev, cur) and its final write re-adds the LAST PAIR
as a stand-in for the last glyph's own advance. For a one-glyph run the
stand-in is 0 (no pair exists), so the run read back as zero-width and
the icon drew on top of the digit — the money-string "coin covers the
lone 0/1" bug. For "] 1" the stand-in was the space's advance, ~3px
short: the single-digit clip. "11" matched by luck (same-glyph pair).

Fix (the 4.3.4 model — FUN_0061ea10 case 7 computes the pending last-
glyph advance explicitly instead of trusting a stored pen): drawRun now
token-walks each run with the engine's own tokenizer and, when it ends
in a glyph, replaces the stand-in with the truth:

  pen = linkState[4] - pairAdvance(prev, last)*scale
                     + baseAdvance(last)*scale

using the engine's own advance functions (FUN_005ca240 base,
FUN_005ca2d0/FUN_005ca4b0 pair, per the node's kerning flag) and its
per-placement __ftol snap. Runs ending in a non-glyph token (trailing
|c/|r) need no correction — the trailing iteration already folded the
last glyph's base advance into the write.

Also:
- The per-icon breathing pad is now FONT-relative (fontH * padFrac),
  not icon-width-relative: the gap no longer scales with icon size, so
  a small icon doesn't jam its neighbour while a big one floats.
- Quad render mode is removed entirely (DrawTexturedQuad, residency
  holders, _classicapi_InlineTexMode/_InlineTexHolders/_InlineTexHolderCfg).
  Engine regions (the 4.3.4 CSimpleEmbeddedTexture model) are the only
  render path.

* feat(currency): GetCoinTextureString / C_CurrencyInfo.GetCoinTextureString

The retail coin-icon money string, backported as a C function
(src/currency/CoinText.cpp) the way retail ships it (behaviour from
3.3.5's Script_GetCoinTextureString FUN_00510d00): split copper into
gold/silver/copper, emit only non-zero denominations in that order,
zero shows "0<copper>". Each denomination formats through the
GOLD/SILVER/COPPER_AMOUNT_TEXTURE GlobalStrings, backported in the
embedded addon's locale layer (stock 1.12 doesn't have them), so
locales can override.

1.12 has no per-coin icon textures — the |T markup crops vanilla's
UI-MoneyIcons 4-cell sheet (gold 0:1, silver 1:2, copper 2:3; the
three coin arts are byte-identical in alpha, verified by decoding the
exported BLP's DXT3 data). height/width 0 = size to the display
font's height (the retail default, honoured by the inline-texture
renderer). No offsetX nudges and no separator spaces: correct spacing
comes from the renderer's font-relative pad plus the lazy-pen fix
(550cf5e) — per-coin offsets were compensations for that bug and must
not return.

FormattingUtil.lua comment updates only (GetMoneyString stays the
text-symbol form; the coin form now exists). docs/API.md: new
Currency section.

* docs(readme): list GetCoinTextureString in the API table

* refactor(text): purge the quad-mode leftovers

Follow-through on 550cf5e (quad render mode removed): delete everything
that existed only for the raw-GxU-quad path and no longer has a single
reference.

- Offsets.h: drop the GxU device primitives (dynamic-VB lock/data/
  submit/unlock, texture bind, vertex stride/selector), the standalone
  path->CGxTexture loader trio (FUN_TEXTURE_LOAD_BY_PATH,
  PTR_TEXLOAD_DESC_VTBL, FUN_GX_TEXFLAGS_INIT), the colorop render-state
  and direct-D3D state setters, FUN_TEXTURE_FORCE_DECODE, and
  FUN_TEXTURE_GET_RENDERABLE. All were quad/residency-era scaffolding;
  the VAs stay recorded in docs/InlineTextureEscapes.md and git history.
  FUN_TEXT_PAINT (the flush co-hook site) and VAR_TEXTURE_BLEND_DEFAULT
  (the pool's SetTexture blend arg) remain, with comments rewritten for
  the region path.
- InlineTexture.cpp: drop IconRecord.z / penZ (only the quad draw read
  them); rewrite the paint-flush section comments to describe what the
  flush actually does now (queue fontstring-relative region placements).

* feat(addon): backport TextureUtil.lua (Blizzard_SharedXMLBase)

The non-atlas slice of the Classic Era reference, ported to Lua 5.0
(string.format instead of string-method syntax):

- SetClampedTextureRotation / ClearClampedTextureRotation — the retail
  90-degree-step texcoord shuffle with width/height swap. Works
  unchanged because 1.12's Texture:GetTexCoord() natively returns the
  8-value corner form and SetTexCoord accepts it (both operate on the
  same engine corner array, verified at Script_Texture_GetTexCoord
  0x0079BDF0). One deviation, commented in-file: Clear also nils
  rotationDegrees — the reference leaves 0 behind, which is truthy in
  Lua and breaks the next Set's origTexCoords re-capture.
- GetTexCoordsByGrid — pure math.
- CreateTextureMarkup / CreateSimpleTextureMarkup — |T markup builders;
  output renders via the inline-texture backport.
- TextureUtil = {} for namespace parity.

Omitted: everything atlas-based (CreateAtlasMarkup*, the TextureKit
family, CheckSetAtlas, GetAtlasSize, SetTextureWithAddressModeOptions —
1.12 has no atlas system), the LFG role-icon tables, and
GetTextureInfo (reads the atlas/fileID getters).

* refactor(text): remove the inline-texture bring-up diagnostics

The pool's _classicapi_InlineTexRegionDump / _InlineTexFsDump /
_InlineTexBroken were bring-up triage for the scroll-landing /
ghost-icon bug class, which the node-free lifetime hook ended
(b5df20d) — they have no remaining job. Removing them also kills their
entire support tree, none of which had another consumer:

- the five Debug* chain-state exports on Text::InlineTexture
  (DebugChainState / NodeFlags / NodeSeenAge / NodeBuiltKnown /
  NodeEmitOutcome),
- g_nodeSeen + g_flushSeq (flush visit stamps),
- g_nodeEmit (per-node emitter-outcome tracking — map churn on every
  emitted line, purely diagnostic),
- g_nodeBuilt + g_buildCounter + NodeIcons.builtSeq (write-only: the
  build-version check they were made for was deliberately REJECTED —
  the builder runs every paint but only emits when dirty, so version
  mismatches on clean paints erased live records). g_buildNode /
  g_buildEmitSeq stay — they are the live firstLine detection.

NodeIcons collapses to a plain std::vector<IconRecord> map value, and
the pool drops its Game.h / InlineTexture.h includes (nothing left
uses them). The stale "versioned by build" struct comment is rewritten
to describe the actual invariant (node-free hook + firstLine erase).

Kept: _classicapi_InlineTexEnable / Suppress / Tune / Stats / ProbeFS /
RegionCal / Wrap — the live control surface and field telemetry.

* refactor(text): reduce the inline-texture Lua surface to the kill switch

Only _classicapi_InlineTexEnable remains — the feature toggle the SEH
latch pairs with. Removed with their entire backing state, none of
which had a non-diagnostic consumer:

- _InlineTexSuppress + g_suppressInline (the manual global override —
  editbox exclusion has been per-node/per-buffer for a while) and the
  now-unreferenced InputFocused() helper
- _InlineTexTune: g_vBias / g_sizeScale / g_centerFrac / g_iconPadFrac
  become constexpr (calibrated during bring-up, fixed now)
- _InlineTexRegionCal: g_regionCalX/Y become constexpr (0 / -1)
- _InlineTexStats + the six flush-gate counters (the queue gate
  if/else collapses to the plain condition; the nudge drops its
  counter-guard and just sets the dirty bit — idempotent)
- _InlineTexWrap + the WrapDiag ring and every capture site in the
  wrap-stepper hook (the minimal-feasible-shrink algorithm is
  untouched — it always ran on locals)
- _InlineTexProbeFS (the pen<->anchor bridge verification probe)
- the SEH filter no longer records fault code/address (nothing read
  them); the latch still disables the feature on a flush fault
- the Arg() Lua helper and <cstdio> (last users removed)

* feat(text): inline icons fade with their chat line

The one visible seam left in the region renderer: icon regions parent
to the CHAT FRAME (regions cannot parent regions), so they inherited
the frame's alpha but not the LINE's — a fading chat line's text
dimmed while its inline icons stayed opaque until the end-of-fade
hide.

RE (verified in the 1.12 binary): chat fading is engine-side in the
ScrollingMessageFrame's fader FUN_00788460 — gated on the SetFading
flag (smf+0x360; the 40-method SMF registry's SetFading 0x007939A0
writes it), it counts down each visible line's timeVisible then
fadeDuration ({rgba@+4, shown@+8, timeLeft@+0xC, fadeLeft@+0x10} in
the stride-0x10 line array at smf+0x3A4) and animates the LINE
FONTSTRING's color alpha byte through the fs SetColor (0x0077F750)
every frame, hiding the fs at zero. SetColor stores the dword at
(*(u32**)(fs+0xB8))[0] (count fs+0xB4; alpha = byte 3), and the
per-line setter FUN_00788af0 resets alpha to 0xFF on message reset —
so that byte IS the line's live fade state, whoever wrote it.

The mirror (InlineTexturePool): Maintain reads FsColorAlpha(fs) each
tick and, on change only, rewrites the shown regions' colors with the
markup tint's alpha modulated by the line's alpha (RGB preserved).
ApplyPlacement folds the live alpha in at placement time, so a line
placed mid-fade starts at the right opacity. Composition is exact by
construction: the fs's on-screen alpha is frameAlpha(+0xC8) ×
fsColorAlpha, and the regions share the same parent frame, so
mirroring the fs byte alone makes icon and text alpha identical.
Steady state costs one byte compare per icon-bearing fontstring per
tick; scroll-back/un-fade restores (the SMF resets the line color and
the mirror follows). Verified in-game: fade lockstep, reappear on
scroll.

* feat(text): line-height growth for tall inline icons

An inline icon taller than the font (a 32px TwitchEmotes emote in 15px
chat) used to overlap its neighbouring lines — the line box stayed
fontH-sized. Retail grows the line: 4.3.4's measure and wrap loops
export a max-texture-height out-param (FUN_00618b90 / FUN_00618e40
case 7) and the layout takes it.

1.12 equivalent, one cold co-hook: FUN_FONTSTRING_STRING_HEIGHT
(GetStringHeightInternal, cache fs+0x100) gains the tallest icon's
overflow past the font height (MaxIconOverflowPx — explicit |T heights
only; the :0 default IS the font height). Its three binary consumers
(verified via xrefs) split exactly right:
- FUN_00772A60, the anchor effective-height vmethod — chat line
  fontstrings get only a SetWidth from the ScrollingMessageFrame
  refresh, so their rect height resolves here -> the rect grows;
- FUN_00788750, the SMF display refresh — budgets vertical space and
  anchors each line to the previous line's rect -> the stack spaces by
  the grown height;
- FUN_0077D4D0, the multi-line editbox self-size — excluded by the
  same editbox gate as the width hook (editboxes render raw markup).
Same rules as the width hook: shared InlineInterceptActive predicate,
px->anchor via the push factor (never fs+0x7C), the fs+0x100 cache is
never written (delta re-derived per call — idempotent). The backported
fontstring:GetStringHeight routes through the hooked VA and becomes
icon-inclusive automatically.

Draw side: tall icons CENTRE on the line like any other icon. The text
centres itself inside the grown rect, so the extra space appears half
above and half below — a centred icon fills exactly that, matching
retail. (A bottom-aligned first cut clipped the neighbouring line;
verified in-game against retail's centred, no-clip rendering.)

v1 limit (documented in-code): the delta is the whole text's max
overflow — exact when a message's tall icons share one wrapped line
(the emote case); tall icons on two different wrapped lines of one
message under-grow.

Verified in-game: 32px emotes between normal chat lines each take
their own vertical room, centred, no neighbour overlap.

* fix(text): full-height hyperlink hover for tall inline icons

With line-height growth (49934b0), a tall emote inside a |H...|h link
was only hoverable across its text-high middle band: the hyperlink hit
rect is registered at layout time (FUN_TEXT_LINK_RECT_ADD 0x005CD310,
the GXUFONTHYPERLINKINFO append — record {y,x,y,x} normalized + link
ptr/len pairs) with the TEXT band's y extent, fontH tall.

Consumer geometry (FUN_00788c00 -> FUN_007a3350 decompile + two in-game
experiments): the ScrollingMessageFrame rebuilds a hit-region frame per
record, anchored to the LINE FONTSTRING's top-left with the record's
band as offset/height. The band's y values are Y-UP (numeric max =
screen top — extending the max visibly grew the region into the line
above), and the band is TEXT-relative — but the grown rect's top sits
half the icon overflow above the text (the text centres in the grown
rect), pre-shifting the whole hit band up. Net: the unmodified band
already covered from the icon's top down to textBottom − overflow/2,
and the single correct fix is pushing the screen bottom DOWN by the
full overflow — decreasing the numeric MIN edge.

Co-hook on the append: when the |H...|h escape span contains a |T icon
taller than the line's font (the same MaxIconOverflowPx the
string-height hook grows the line by), decrease the band's min edge by
the overflow before the original stores it. All consumers of the
record (hover, click) inherit the expansion. Gated on the shared
InlineInterceptActive predicate so raw-rendered contexts stay literal.

Known v1 rough edge (commented in-code): a tall icon outside the link
but on the same line grows the line without this hook firing for that
link, leaving its band half-overflow high.

Verified in-game: a 32px emote link hits across its full height, no
bleed into neighbouring lines.

* docs(text): truth-pass on the inline-texture RE docs

InlineTextureEscapes.md and InlineTextureResidency.md described the
removed raw-quad renderer and a bring-up plan as if current. Bring them
in line with the shipped engine-region design.

InlineTextureEscapes.md:
- New "Current design (shipped)" section up front: region renderer, the
  three fs-level measure hooks (width/height/wrap), the lazy-pen fix,
  chat fade, tall-icon line growth + full-height hover, editbox
  exclusion, the payload, and anti-spoof — each with its commit.
- Banner the quad "rendering primitive" section as REMOVED (bring-up
  record; the address log for code deleted in 56c2670).
- Fix the DrawTexturedQuad / quad-flush references to region-queue
  language; vertical centring is g_centerFrac (0.6) with the tall-icon
  grown-rect note; the flip note becomes the region SetTexCoord
  Y-first order.
- "Remaining/optional": diagnostics removed (only InlineTexEnable
  left), measure/height/wrap DONE, animation is addon-side, the TGA
  convert command is -compress none only.
- "Reality check": correct the prediction that we would reimplement the
  emitter — the shipped design segment-delegates and co-hooks instead.

InlineTextureResidency.md: rewritten from a "not-yet-implemented plan"
into an accurate reference. States the region design, records the
CSimpleTexture entry points / layout the pool uses (VAs verified
against Offsets.h), and corrects the root cause honestly — the flicker
was the LAA pointer-bound truncation (dc61f77), NOT texture residency;
regions are kept for 4.3.4 parity and are resident by construction as a
bonus. Keeps the D3D "ruled out" notes as a do-not-re-investigate
record.

* fix(text): stop inline-icon Maintain from dereferencing stale fontstrings

A destroyed chat-line fontstring left a dangling key in the icon pool's
per-fontstring map. Its heap memory was reused as a string buffer, and
Maintain's weak LooksReadable() range check waved the reused pointer
through; reading the "parent" field (fs+0x9C) then yielded string bytes
(ASCII "-Rac"), which the engine's region attach (FUN_0076a750)
dereferenced at *(parent+0x1B4) -> ACCESS_VIOLATION (ERROR #132 at
0x0076A7CE).

Two compounding defects, both in Maintain:
  - the stale-entry expiry was gated on shown > 0, so a scrolled-off line
    (shown == 0) never expired and its dead key was re-dereferenced every
    frame, waiting for its memory to be reused;
  - LooksReadable is a bare VA-range test that a reused buffer passes.

Fix: verify a key is a LIVE fontstring by its object+0x00 vtable before
using it. The vtable is learned at paint time from fontstrings the engine
is actively drawing (QueuePlacements), so every fontstring class -- chat's
internal ScrollingMessageFrame lines, tooltip/CreateFontString lines,
addon fontstrings -- is recognized without hardcoding (one hardcoded value
filtered live chat icons out entirely). Maintain now iterates with erase:
a key whose memory no longer carries a learned fontstring vtable has its
regions hidden (our tex pointers stay valid, parented to the chat frame)
and the entry erased, so dead keys can neither accumulate nor be
dereferenced.

* fix(text): guard inline-icon pool hide loops against short region vector

CreateRegion can fail when the region pool is exhausted, breaking the
apply loop with fewer regions than `want`. The code still set
`np.shown = want`, so a later tick's freshness-expiry and fs-hidden hide
loops indexed np.regions[i] past regions.size() -- an out-of-bounds
std::vector access.

Clamp np.shown to min(want, regions.size()) so it never exceeds the
vector, and add the same i < regions.size() bound the eviction loop
already carries to the other two hide loops so all three self-guard.

* refactor(text): centralize inline-texture offsets and pointer probe

Enforce the single-source-of-truth offset rule on the inline-texture
files:

- Read the fontstring text pointer via Offsets::OFF_FONTSTRING_TEXT
  instead of a raw `fs + 0xF0` in FlushLayout's ghost guard; the symbol
  already existed and is used elsewhere in the same file.
- Add OFF_TEXT_NODE_JUSTIFY (0x54) to Offsets.h with a verification note
  and use it for the two node-justify reads (DeriveK and the emitter
  pre-shift) that previously hardcoded 0x54 in two places.
- Move the LAA-aware LooksReadable probe into a shared text/PtrProbe.h
  (namespace Text) so InlineTexture.cpp and InlineTexturePool.cpp share
  one definition instead of two copies plus a third raw-bounds copy in
  LearnFontStringVtable. The 0xFFFF0000 bound now lives in exactly one
  place -- this is the constant whose earlier 0x7FFF0000 form caused the
  missing-chat-icon bug, so keeping the copies from drifting matters.

No behavior change; full build compiles and links.

* fix(currency): clamp GetCoinTextureString to the uint32 copper ceiling

An amount above INT_MAX gold copper (e.g. 1e15) made `gold =
(int)(amount / 10000)` overflow: the long long division was truncated to
its low 32 bits, so GetCoinTextureString(1e15) printed a garbage gold
count (1215752192). silver/copper were already bounded by the % math.

Vanilla money is a uint32 copper field, so clamp amount to 0xFFFFFFFF
copper (~429,496 gold) -- the most the game can represent -- which keeps
gold within int range for the "%d" GlobalString format. Can't widen the
type instead: the count is formatted through the retail-compatible "%d"
coin GlobalString, and passing a long long to %d is undefined.

* fix(text): SEH-guard the inline-icon Maintain tick; document region leak

#6 (SEH backstop): Maintain's liveness probe dereferences a fontstring
pointer that may have been freed (the documented IsLiveFontString
residual). The paint path already latches off on a fault via SafeFlush,
but Maintain ran bare under the render-root tick, so a fault there was an
uncaught client crash. Split the body into MaintainImpl (holds the C++
objects) and a thin Maintain() SEH wrapper that latches g_maintainDisabled
on fault -- mirroring the paint latch. Re-armed on /reload.

#7 (region leak): document why the stale-key eviction intentionally drops
np.regions without reclaiming the pooled CSimpleTextures. Any reclaim (a
free list or explicit destroy) would touch a region whose parent frame may
already be gone -- a use-after-free on the very path this liveness check
was added to stop crashing. The leak is bounded and near-zero in practice
(chat/tooltip fontstrings are reused, never evicted).

* fix(chat): stop raid-marker expansion from dropping the message tail

A token inflates ~28x ({rtN} -> ~85-byte |T markup), so a marker-dense
message could fill the 0x800 buffer and silently truncate everything after
it -- a DLL user would see a shorter chat line than a non-DLL user (a mild
content-hiding vector).

Reserve room for the literal tail before expanding a token: only iconify a
marker when the expansion plus the whole remaining input (worst case copied
1:1) still fits. Past that point later tokens stay literal {rtN}, so the
full message text is always preserved -- just with fewer icons.

* fix(text): gate eviction Hide on region liveness to avoid a UAF

The stale-key eviction Hid its regions unconditionally, assuming they
outlive the fontstring. They usually do (regions are parented to the
fontstring's parent FRAME, which persists as lines churn) -- but if the
fontstring became non-live because that parent frame was destroyed, the
frame freed the fontstring AND its child regions together. Hiding a region
pointer there wrote to freed/recycled memory: a use-after-free that could
crash.

Learn the pooled CSimpleTexture vtable in CreateRegion and gate each
eviction Hide on IsLiveRegion (the same vtable-liveness technique
IsLiveFontString already uses). A recycled region is skipped (it needs no
hiding -- it's already gone); a live one is still hidden so it can't ghost.
Factored the shared WoW-image-range check into InWowImage so the two Learn*
functions don't duplicate the constant.
2026-08-18 04:15:54 -05:00
fuffcandBrues 72c4185026 fix(aura): identify a cached aura by its caster and descriptor slot (#21)
* fix(aura): identify a cached aura by its caster and descriptor slot

Two casters of one spell on one target are two auras in two descriptor
slots, but `Aura::Source` held a single entry per `(target, spellId)`.
The second cast overwrote the first caster's `casterGuid` and timing, and
`OnAuraRemoved` for either copy evicted the entry backing the survivor.

Observable from Lua, with a same-class groupmate debuffing your target:
`sourceUnit` names the wrong caster, so a `PLAYER`-filtered query drops
your own debuff; and the base-duration estimate stored for the other
caster elapses while your talent-extended aura is still up, which
`PushEnriched` reports as `expirationTime = 0` — an aura on the unit with
no timer at all.

Entries are now keyed `(target, spellId, caster)`, the identity the server
uses. Recovering which instance a descriptor slot holds needs the two
halves joined: SpellGo knows the caster but no slot, `OnAuraAdded` knows
the slot but no caster, and they arrive in that order, so the application
hook seats its slot on the newest cast capture still awaiting one.
`Get` takes that slot and resolves by it first, falling back to the unit's
sole entry for the spell — every single-caster case, and the paths with no
descriptor to read a slot from. Several entries and no binding resolves to
a miss: the caller's unknown-caster defaults beat a coin flip between two
casters.

`OnAuraRemoved` and `EvictAbsent` retire the instance in the vacated slot
rather than every entry sharing its spell ID.

* fix(aura): compare unbound-entry freshness wrap-safely

FindFreshestUnbound picked the newest unbound capture with a raw
`stampMs >` on two absolute engine ticks. That compare inverts across the
2^32 ms tick wrap (~49.7 days uptime, or the rdtsc backend already past
2^31 after a warm reboot), so the OLDER capture would win and OnAuraAdded
would seat the descriptor slot onto the wrong cast — mis-attributing that
aura's caster and duration.

Pick by smallest Time::Clock::Elapsed(stamp, now) instead, the wrap-safe
signed difference the rest of the codebase uses for tick math.

* fix(aura): keep the observed caster on the aura fallback paths

The cache-fallback push paths (the descriptor-drop fallback and the
out-of-range group-member fallback) already hold each aura instance's
caster and timing — Enumerate copies them straight out of the cache entry.
But PushEnriched then re-resolved them through Get(guid, spell, slot),
which returns a miss for an unbound entry that shares its spell with
another caster's entry. So an aura Enumerate had fully attributed came
back out with no sourceUnit/sourceGUID and no expirationTime.

Hand the entry's own attribution to PushEnriched as `known` so the
fallback reports what the cache already knew instead of re-deriving it.

* refactor(aura): route Get and Evict through one FindInstance resolver

Get and Evict each hand-rolled the same FindBySlot-then-FindSole ladder —
the read-side rule for which instance a slot-bearing query names. Naming it
once keeps the two from drifting into resolving the same query to different
instances (reporting one caster while evicting another). No behavior change.

* perf(aura): bound cache scans to the active high-water prefix

Every Aura::Source lookup linear-scanned all 2048 cache slots. Get runs
per-aura per-query — hundreds of times a frame when addons poll UnitAura in a
raid — so the full scan dominated the read path.

Track a high-water mark that Claim (the sole allocator) extends and FlushAll
resets, and scan only [0, g_usedHigh). Every used entry lives below the mark,
so no lookup can miss one. Outside a raid the working set is a handful of
auras, cutting a ~2048-entry scan to ~30; in a raid it drops to the real
working set. Claim still scans the full array — as the allocator it must hand
out slots beyond the current prefix.

---------

Co-authored-by: Brues <5278969+brues-code@users.noreply.github.com>
2026-08-16 14:41:49 -05:00
Brues d366fec43e fix(attributes): restore the previous target after a macro click-cast
The `macro` verb selected the clicked unit and left it targeted (Clique's
click-heal minus the restore). Snapshot the current selection GUID, retarget
the clicked unit, run the macro, then restore the prior target via
FUN_TARGET_BY_GUID (which validates the GUID and drops a stale one), or
ClearTarget when there was no prior target. The macro's actions dispatch
synchronously while the clicked unit is selected, so restoring afterward
doesn't affect them.
2026-08-13 00:03:42 -05:00
Brues c6d99cf843 feat(attributes): target the unit for macro click-casts
The `macro` click verb ran the macro text with no unit context, so a
plain `/cast Flash Heal` bound to a raid frame hit the current target
instead of the clicked unit -- a regression from Clique/Healbot-style
click healing. Vanilla macros have no `@unit` conditional, and unlike
the `spell` verb (which feeds a GUID straight to the cast dispatcher)
we can't inject a target into arbitrary macro text.

Emulate pfUIevan's classic click-heal: TargetUnit the clicked unit
before running the macro. Like pfUIevan, the previous target is not
restored -- the click doubles as a target swap. Only the `macro` verb
is affected; `spell`/`item` already act on the unit directly.
2026-08-12 03:48:35 -05:00
Brues 39d22ac124 fix(time): centralize engine ms-tick reads in Time::Clock
The engine's OS millisecond counter (FUN_OS_TICKCOUNT_MS, same epoch
GetTime() scales by 0.001) is unsigned and wraps at 2^32 ms. Nine files
each re-derived the reader; several stored the tick into a signed int,
so past 2^31 ms (~24.9 days uptime) every timestamp went negative and
`startTime + duration` landed in the past -- callers saw every cooldown,
aura, and lockout as already elapsed. The same bug shipped three times
(the cooldown by-ID getters and C_LossOfControl).

Add one source of truth -- Time::Clock (src/time/Clock.h) -- with a
uint32 NowMs() and wrap-safe Reached/Remaining/Elapsed helpers, and route
every tick reader through it. No module re-derives the reader or hand-
rolls a `now < deadline` compare (which inverts across the wrap) anymore.

Also fixes the reported cooldown/LoC getters (unsigned out-params,
wrap-safe compares) and three latent instances of the same `now < end`
inversion found while sweeping: totem/Tracker's two timer getters and
aura/Source's cache-eviction pass.

Named Time::Clock, not Time::Tick, because a Time::Tick inner name
shadows the global Tick namespace (the WorldTick hook) from inside any
Time::* file.

Discovered by fuffc in #17.
2026-08-12 01:58:54 -05:00
Brues b497bb7fb0 fix(attributes): run macrotext as text, not through name-based RunMacro
The secure "macro" action read both `macrotext` (raw text) and the
deprecated `macro` (saved-macro name) into one buffer and ran whichever
through the global RunMacro. RunMacro is name-based -- stock resolves an
index, and SuperCleveRoidMacros' RunMacro calls GetMacroIndexByName --
so a macrotext value like "/cast [hp:<90] Holy Light" resolved to no
macro and silently did nothing. Because the global existed, the native
fallback never ran.

Split the two by their real semantics: macrotext runs through the chat
parser (RunMacroTextC), so each line dispatches via SlashCmdList and
picks up addon slash hooks like SuperCleveRoidMacros' conditional /cast;
the name form keeps preferring RunMacro. Fixes click-cast macros with
conditionals.
2026-08-12 00:32:28 -05:00
Brues 4d5fe8d41b feat(spellbook): add C_SpellBook.GetSpellBookItemInfo
Backport C_SpellBook.GetSpellBookItemInfo(slotIndex, spellBank) -> table,
reusing Spell::Info's DBC reader. slotIndex is 1-based across the book;
spellBank is Enum.SpellBookSpellBank (0 = Player, 1 = Pet), resolved via
Spell::Lookup::SpellbookSlotToID. Returns nil for an empty/out-of-range
slot, matching retail.

Fields map from Spell.dbc: itemType is Spell (player) or PetAction (pet)
- vanilla's book holds only real spells, so None/FutureSpell/Flyout never
occur; actionID == spellID (no override system); name/subName from the
localized Name/Rank; isPassive from Attributes; isOffSpec always false.
iconID is the icon PATH string (vanilla has no fileID), the same
deviation as C_Spell.GetSpellInfo.iconID; skillLineIndex is omitted.

Also register the two Enum tables the return contract references
(non-destructively, like the other Enum.* additions) so
info.itemType == Enum.SpellBookItemType.Spell comparisons work:
Enum.SpellBookSpellBank and Enum.SpellBookItemType.

Document in docs/API.md (SpellBook section + both Enum entries) and list
in README.
2026-08-11 01:28:31 -05:00
Brues 46cae9d465 fix(unitmenu): stop stacking Focus/Cancel when a submenu opens
ClassicAPI_ToggleUnitMenu's initialize closure ran the same level-1
customization at every level. When the mouse crossed a nested entry
(Loot Method / Loot Threshold / Raid Target Icon) the menu builds its
level-2 submenu and re-invokes initialize; our AddFocusButton /
AddCancelButton call UIDropDownMenu_AddButton with no level, which
defaults to level 1 (not the current level), appending onto the still-
open level-1 list. Level 1 is not reset while a submenu rebuilds, so the
list grew every hover until "Too many buttons in UIDropDownMenu:
ClassicAPIUnitMenuDropDown", pushing the real entries out of reach.

Make initialize level-aware: at level >= 2 hand off to UnitPopup_ShowMenu
(it resolves the submenu from UIDROPDOWNMENU_MENU_VALUE and adds its own
Cancel); do the scratch-copy + Focus/Cancel append only at level 1 -
mirroring how Blizzard's own unit dropdowns init.
2026-08-10 13:08:58 -05:00
Brues 93360ce482 fix(cast): don't start target-selection casts at the reticle step
Spell_C_CastSpell (0x006E4B60) calls the cast-start writer
FUN_CAST_START_SET before Spell_C_TargetSpell raises the reticle, so a
target-selection spell (Disenchant, ground-target AoE) stamps g_cast at
the green-cursor step - seconds before the item/ground is clicked and the
cast actually begins. The later click re-enters Spell_C_CastSpell only to
hit its "already this spell" short-circuit, so the writer never re-fires
for the real start. Result: UNIT_SPELLCAST_START (and a UnitCastingInfo
cast bar) fired far too early, and a cancel fired a phantom
START/INTERRUPTED/STOP for a cast that never happened.

Drop the client stamp in OnWorldTick while the reticle is up for that
spell. On selection the server's SMSG_SPELL_START re-stamps g_cast via
the fresh-stamp path (it is 0), so START fires with the correct time and
the SENT castGUID; on cancel it stays cleared. Gated on !g_castFromServer
(never touches the server re-stamp) and on g_cast.spellID ==
VAR_PENDING_CAST_SPELL (only the spell whose reticle is actually up).
Normal casts have no targeting phase and are unaffected.
2026-08-10 00:11:21 -05:00
Brues b879730dfb ci: attach ClassicAPI.map to GitHub releases
Add build/Release/ClassicAPI.map to the release step's asset list so
every vX.Y.Z release ships the linker map beside the DLL. It resolves
the `0001:offset` logical addresses in a shipped build's ERROR #132
crash dump back to function names for that exact build. Dev-build
artifacts stay DLL-only.
2026-08-09 23:27:53 -05:00
Brues 9cbf185b3c fix(frame): make ScriptArgs global save/restore longjmp-safe
RunModern reimplements the frame-script runner tail, saving the
this/arg1..argN globals it clobbers so it can restore them after the
handler pcall. The old save used luaL_ref into the registry, mirroring
the engine's own FUN_00704f10 - but any push before the protected call
can longjmp (out-of-memory being the real case), which unwinds past the
C frame and skips the restore: the refs leak and the globals stay
clobbered for later handlers.

Save the old values on the Lua stack instead. An unwinding error resets
L->top past them for free, so there is nothing to leak and no clobbered
state to strand. This also drops the per-call luaL_ref/luaL_unref churn
and the per-arg re-read from globals on the OnUpdate hot path; the call
args are pushed directly from a pure-C parse of the vararg buffer.

The stack save is deeper than the registry save (~2N slots live at
once), so CheckStack up front; if it cannot grow (or there is no Lua
state) RunModern returns false before any side effect and the thunk
falls back to the original engine runner, never double-running.

Behavior unchanged: default-off passthrough, and identical
(self, [event,] arg1..argN) semantics when enabled.
2026-08-09 23:26:47 -05:00
Brues 68f6a687cc build: emit linker .map for crash-dump triage
Add /MAP to the shared-linker flags so the Release build produces
ClassicAPI.map, which resolves the `0001:offset` logical addresses in
WoW's ERROR #132 crash dumps back to function names. Linker-only output;
no effect on code layout.
2026-08-09 23:26:47 -05:00
Brues 2d5ecdc493 refactor(spell): identify Ferocious Bite structurally, share IsFitToFamily
Carnage's Ferocious Bite gate was a hardcoded list of five rank IDs. Replace
it with the server's own structural test (IsDruidFerociousBite): druid family
+ the Rip/Bite family flag + a direct-damage effect (the damage effect is what
separates Bite from Rip, its DoT sibling that shares the flag). Rank-proof and
covers any Turtle-added rank with no ID list. Verified against the client
Spell.dbc: all five FB ranks are {family 7, flag 0x800000, Effect[0]
SCHOOL_DAMAGE}; Rip shares the flag but is APPLY_AURA, and Rake carries a
different flag.

The family + flag-bit test is the client-side form of the server's
SpellEntry::IsFitToFamily, and Aura::Source::AffectedMatchesRaw read the same
two fields inline, so extract Spell::Lookup::IsFitToFamily and route both
through it. Adds SPELL_EFFECT_SCHOOL_DAMAGE (= 2, verified vs the server's
SpellDefines.h).
2026-08-09 02:52:34 -05:00
Brues 783ffd05bf feat(aura): Carnage Rip/Rake refresh + signal duration-mod changes
Turtle's Carnage refreshes the caster's Rip and Rake off Ferocious Bite,
behind a per-combo-point roll whose outcome the client only sees as the
combo point the proc returns. A src/turtle/Carnage watcher arms on a
Ferocious Bite send and confirms on the first combo-point rise, then
refreshes the cached auras. Verified against tortoise-wow
spell_druid_carnage: icons 108 (Rip) / 494 (Rake), family bits 0x800000 /
0x1000, caster scoping, and RefreshHolder (restore the aura's own applied
duration).

A cache duration edit has no engine packet behind it, so nothing re-fired
UNIT_AURA and event-driven aura bars never saw the change. The trigger mods
(ApplyMod) and the Carnage refresh now enqueue the affected unit, and the
WorldTick flush re-broadcasts UNIT_AURA via the engine's own per-token
signal (FUN_UNIT_EVENT_BROADCAST), deferred off the SMSG_SPELL_GO subscriber.

Also move the two static Turtle duration mods (Conflagrate -> Immolate,
Molten Blast -> Flame Shock) from Lua into src/turtle/DurationMods via a new
C++ entry Aura::Source::AddDurationMod, and drop the now-unused exact-spellID
RegisterAuraDurationModifier Lua export (RegisterAuraDurationModifierByTrigger
stays for Shadow Weaving).

Based on the approach from @fuffc in #15.

Closes #15
2026-08-09 02:40:47 -05:00
Brues f559eb4d07 docs(api): move UNIT_SPELLCAST_* events into the Events section, fix TOC link
The TOC entry pointed at #unit_spellcast_-events-player, but the heading
generates #unit_spellcast_-events (no -player suffix) — broken link. Move
both the TOC entry and the content block out of the Spell section and into
the Events section where the other event docs live, and correct the anchor.
2026-08-08 17:10:11 -05:00
fuffc 2de7176b94 fix(aura): key the combo-point capture by spellID so a proc can't eat it (#14)
The capture was a single slot, and ConsumeCapturedCP cleared it before
testing whether the spellID even matched. Every player-cast aura spell
reaches TryComboScaledMs, so any aura landing between a finisher's
CMSG_CAST_SPELL and its own SMSG_SPELL_GO consumed the snapshot and left the
finisher with no combo points — falling back to the 0-CP base duration.

Not a rare race. Turtle's rogue Taste for Blood casts spell 52529 on the
player off the same Rupture, and its SPELL_GO arrives first, so Rupture
reported a static 12s (its 6s 0-CP base plus the talent) at every combo
count. Untalented, with no proc to clobber the slot, the same cast scaled
correctly — which is what made this look like a modifier bug rather than a
capture one.

Key the captures by spellID in a small ring and consume only the matching
entry. The comment claiming one cast is in flight at a time was reasoning
about finishers alone; the funnel sees every cast.
2026-08-08 16:27:57 -05:00
Brues 13008ab8aa refactor(item): centralize passive item-cache peek in Item::PeekRecord
Add item/Record.{h,cpp} with Item::PeekRecord(itemID) -- the passive
ItemStats_C cache peek (null callback, no network query). Route the three
duplicate implementations through it:
  - the per-module GetItemRecord_t typedef + fn(cache,id,&zero,nullptr,
    nullptr,0) call in ~25 read-only item accessors
  - Item::StatAccum::FetchRecord (deleted; 7 callers repointed)
  - item/Tooltip.cpp's local PeekItemRecord (deleted)

Behavior-identical: every converted call was already a passive peek with
identical args (dedup flag is a no-op when the callback is null).

item/Data.cpp is deliberately untouched -- it owns the ACTIVE fetch
(CacheFetch passes a real callback to fire SMSG_ITEM_QUERY_SINGLE, the
load-bearing cache-race path in CLAUDE.md) and keeps its own typedef.
2026-08-08 15:35:07 -05:00
Brues 0df8885045 refactor(offsets): collapse duplicate object type-mask enum (OBJ_TYPE_* -> TYPEMASK_*)
OBJ_TYPE_* was a partial second naming of the same object-type bits as
the complete TYPEMASK_* set (OBJ_TYPE_ITEM=2=TYPEMASK_ITEM, ... GAMEOBJECT
=0x20 both) -- a single-source-of-truth violation. Repoint all ~18
references to TYPEMASK_* (identical values, behavior-preserving) and
delete the OBJ_TYPE_* definitions, folding their derivation notes
(bitmask semantics, FUN_004F8DB0 for PLAYER, FUN_0052AA20 for GAMEOBJECT,
FUN_00529FE0 SetUnit) into the surviving TYPEMASK_* comment.
2026-08-08 15:12:55 -05:00
Brues 8fa344a084 refactor(item): name CGItem deref idioms via Item::InstanceBlock / ObjectFields
Add item/CGItem.{h,cpp} with two null-safe accessors for a CGItem's two
descriptor-like pointers:
  InstanceBlock(cgItem) -> CGItem + 0x08 (item GUID @ +0, itemID @ +0x0C)
  ObjectFields(cgItem)  -> CGItem + 0x114 (stack/flags/charges/durability/...)

Replace the 30 hand-written `*reinterpret_cast<const uint8_t *const *>(x +
OFF_ITEM_INSTANCE_BLOCK/OFF_ITEM_DESCRIPTOR)` derefs across 24 files with
these calls. Behavior-preserving: same deref, all reads were already const,
and each site keeps its own null-check and field reads. Helpers add a
cgItem null guard (strictly safer).
2026-08-08 15:08:34 -05:00
Brues 2612118ff6 refactor(object): centralize GUID->object resolution in Object::ByGuid
Every caller of the engine object resolver (0x00468460) re-declared the
same __fastcall typedef and split the GUID into lo/hi by hand -- 30 call
sites across 28 files. Add object/Resolve.{h,cpp} with

  void *Object::ByGuid(int typeMask, uint64_t guid, const char *debugName, int priority)

and route every site through it (behavior-identical: same typeMask,
debugName, priority per site; single-uint64 callers pass guid, split-lo/hi
callers reconstruct it).

Also collapse the duplicate offset constant: FUN_CLNT_OBJ_MGR_OBJECT_PTR
was a second name for the same 0x00468460 address as
FUN_OBJECT_RESOLVE_BY_GUID (a single-source-of-truth violation). Remove
it; the ABI-equivalent (u32,void*,u64,int) view it documented is folded
into the surviving constant's comment.
2026-08-08 04:13:30 -05:00
Brues 76e40fec96 refactor: share ASCII case-insensitive compare + DBC reverse token lookup
Add baselib/Ascii.h (header-only Ascii::ToLower / Ascii::EqualCI) and
replace the two hand-rolled case-insensitive compares (frame/Attributes'
EqI, taxi/Map's IEqual + AsciiLower).

Add DBC::ClassIdForToken / RaceIdForToken (token -> ChrClasses/ChrRaces
id, the reverse of ClassToken/RaceToken) backed by a shared
IdForStringField walk using Ascii::EqualCI, and replace player/NameCache's
two near-identical ResolveClassToken / ResolveRaceToken loops.
2026-08-08 02:09:08 -05:00
Brues b72c52d9f7 refactor(identity): share NameForGuid, drop friendlist copies
Add Unit::Identity::NameForGuid(guid) -- a passive NameCache peek that
returns the cached character name -- and replace the two identical local
copies in friendlist/IsFriend and friendlist/IsIgnored. Both files no
longer touch Offsets directly, so drop the now-dead include.
2026-08-08 02:08:59 -05:00
Brues 1447317cd3 refactor(dbc): route class/race/area name lookups through DBC::Names
Add DBC::RaceToken (race client-filename token) and make AreaName skip
the parent Record lookup when resolveToParent is false, then replace the
inline ChrClasses/ChrRaces/AreaTable name+token reads across the codebase
with the shared helpers:

  player/Info, creature/Info, player/LocationInfo, unit/ClassBase,
  unit/RaceBase, map/Areas, taxi/Map, loot/History (drops its verbatim
  ClassTokenForId), classes/Info (drops local Records/LocaleIndex).

All behavior-preserving -- the helpers wrap the same DBC::Record /
LocalizedField / StringField calls with identical id==0 / out-of-range /
empty-string -> nullptr semantics (verified against Lookup.cpp).

Left alone: NameCache's reverse token->id resolvers (no forward helper
fits) and the Record() reads of non-name fields in spell/Mod,
map/Overlays, creature/Info.
2026-08-08 01:53:02 -05:00
Brues f293653837 docs: clarify GetNumWhoResults second return is server-dependent
The second value's meaning varies by server core. Mangos/cmangos cores
send the query match count; Turtle (tortoise-wow) sends the whole
realm's online population whenever more than 49 players are online,
ignoring the filter (verified against tortoise-wow MiscHandler.cpp:
data.put(4, count > 49 ? count : clientcount), count = online players).
Earlier wording claimed it was always the match total, which is wrong
off Turtle -- confirmed by a Twinstar /who priest returning 15/15.
2026-08-08 01:09:27 -05:00
Brues ba1e12fca9 feat(friendlist): C_FriendList.GetWhoInfo / GetNumWhoResults
Add the modern table form of /who results. Vanilla's global
GetWhoInfo returns positional values and no class token; GetWhoInfo
here returns a table with filename (the "MAGE"/"WARRIOR" token, keyed
for RAID_CLASS_COLORS) plus fullName, fullGuildName, level, raceStr,
classStr, and area. GetNumWhoResults returns the shown + total counts.
Reads the engine's /who buffer directly (WHO_RESULT_* globals added to
Offsets.h, verified by decompiling Script_GetWhoInfo / GetNumWhoResults).
No gender field -- vanilla's /who entry has no sex.

Share the class/race/zone display-name resolvers: extract ClassName,
ClassToken, AreaName out of GetFriendInfo into dbc/Names.{h,cpp} (adding
RaceName and an AreaName resolveToParent flag -- friends resolve a
sub-area to its zone, /who uses the area's own name). GetFriendInfo and
GetWhoInfo both use them now.

Document both functions in docs/API.md and README.md.
2026-08-08 01:01:39 -05:00
Brues 867478f410 feat(friendlist): add classFilename to GetFriendInfo
Return the locale-independent class token ("WARRIOR", "MAGE", ...)
alongside the localized className, read from the same ChrClasses.dbc
filename column GetPlayerInfoByGUID's englishClass uses. It is the key
for RAID_CLASS_COLORS and other class tables, so addons can color a
friend's name without matching the localized class name. nil when
unknown, so className and classFilename appear together. Document in
docs/API.md.
2026-08-08 00:40:41 -05:00
Brues caeb598b78 feat(player): resolve UnitNameFromGUID from the friends list
Add a friends-list fallback to UnitNameFromGUID, between the object
manager and the persistent name cache. The friend list keeps name +
GUID for online AND offline friends (SMSG_FRIEND_LIST), so a friend's
GUID now resolves to a name even when the unit is not synced and was
never seen in chat -- the case that previously returned nil.

Only UnitNameFromGUID uses this: it returns name + realm, and the
friend entry has the name. GetPlayerInfoByGUID is left unchanged because
it also returns race and sex, which the friend entry does not carry.

Add FriendList::NameForGuid helper. Document the lookup order in
docs/API.md.
2026-08-08 00:28:34 -05:00
Brues 37ca209210 feat(friendlist): C_FriendList.GetNumOnlineFriends
Add the online-friend count. Vanilla stores no online total, so count
friend entries whose connected byte is set -- the same flag
GetFriendInfo reports. Document in docs/API.md and README.md.
2026-08-08 00:02:15 -05:00
Brues 94c5eaafd2 feat(locale): backport SET_FRIENDNOTE_LABEL / SET_NOTE globals
Add the two friend-note GlobalStrings vanilla 1.12 lacks, per locale
(enUS/deDE/esES/frFR/ruRU/zhCN/zhTW), from Blizzard's Classic
GlobalStrings. Lets note-aware UI (e.g. a pfUI "Set Note" entry driven
by C_FriendList.SetFriendNotes) label itself in the client language.
2026-08-07 23:22:41 -05:00
Brues 3f09b3f883 feat(friendlist): C_FriendList.IsIgnored / IsIgnoredByGuid
Add ignore-list membership checks. Vanilla's ignore list is a flat u64
GUID array in the social singleton (social + 0x650, stride 8, max 25,
terminated by the first zero) -- verified by decompiling GetIgnoreName
(FUN_005AE570 reads social + 0x650 + index*8) and GetNumIgnores
(FUN_005AE550 stops at the first zero, caps at 25).

IsIgnoredByGuid parses the GUID string and walks the array.
IsIgnored accepts a name or GUID string (mirroring IsFriend); for a name
it resolves each ignored GUID to its cached name through the NameCache
and compares -- the same GUID->name path GetIgnoreName uses -- so it
matches any ignored player the client has synced this session.

Share the ignore layout + IgnoreGuidByIndex / IsGuidIgnored helpers in
FriendList.h alongside the friend layout. Document both functions in
docs/API.md and README.md.
2026-08-07 22:50:15 -05:00
Brues 9f640de74b fix(addon): use plain info tables in the unit menu (stock 1.12 has no UIDropDownMenu_CreateInfo)
UIDropDownMenu_CreateInfo does not exist in stock 1.12.1 FrameXML, so
building the Focus and Cancel buttons through it errored with "attempt
to call global UIDropDownMenu_CreateInfo (a nil value)". Build the info
tables directly ({}) -- the vanilla idiom UIDropDownMenu_AddButton
expects.
2026-08-07 22:27:44 -05:00
Brues 67b968c36c fix(addon): NPC unit menu + working Cancel on the Focus dropdown
Unify ClassicAPI_ToggleUnitMenu so every menu (players and NPCs) shows
the base menu minus its trailing Cancel, then appends Focus + Cancel.
An NPC resolves to the RAID_TARGET_ICON menu, whose entries
UnitPopup_HideButtons hides entirely unless you are grouped and can
place markers -- so solo the menu was empty and never opened. The
appended Focus + Cancel now always open it, and the NPC's own name is
used as the title.

Give the Cancel button a no-op func: UIDropDownMenuButton_OnClick
early-returns when a button has no func and never hides the list, so the
funcless Cancel did nothing on click.
2026-08-07 21:12:37 -05:00
Brues f833aad769 feat(addon): Set/Clear Focus on the unit right-click menu
Add a contextual Focus / Clear Focus entry to the ClassicAPI unit
dropdown (ClassicAPI_ToggleUnitMenu), shown for real non-self units
(party / raid / target). pfUI unit frames route their right-click
through this dropdown, so it reaches every frame in use.

Built entirely inside our own dropdown: no hooksecurefunc and no
mutation of Blizzard's shared UnitPopupMenus tables, so default frames
and other addons are unaffected. Cancel stays last by showing the base
menu minus its trailing Cancel, then appending Focus and Cancel with our
own click funcs. "Clear Focus" shows when the unit is the current focus,
"Set Focus" otherwise.

Labels use localized SET_FOCUS / CLEAR_FOCUS globals, added per locale
(enUS/deDE/esES/frFR/ruRU/zhCN/zhTW) from Blizzard's Classic
GlobalStrings.
2026-08-07 21:05:14 -05:00
Brues b38673f51f docs: document the friend-notes API
Update the GetFriendInfo entry so notes is a live field (with the
per-character persistence note), add SetFriendNotes and
SetFriendNotesByIndex sections plus TOC and README-matrix rows. Example
values are from a verified in-game /dump.
2026-08-07 20:14:07 -05:00
Brues f2161265be Add a native friend-notes system (C_FriendList SetFriendNotes / notes)
Vanilla has no friend notes, so persist them client-side like the equipment manager. New friendlist/Notes.{h,cpp}
stores guid -> note in
WTF\Account\<acct>\<realm>\<char>\ClassicAPI_FriendNotes.txt --
per-character (matching the friends list's own scope), GUID-keyed (stable
and realm-unique), atomic tmp+rename write.

Expose C_FriendList.SetFriendNotes(name, notes) and
SetFriendNotesByIndex(index, notes) -- empty/nil clears, fires
FRIENDLIST_UPDATE -- and fill the notes field in GetFriendInfo /
GetFriendInfoByIndex from the store.

Character isolation (the equipment-manager trap): EnsureLoaded re-resolves
the path every call and reloads on change; Load clears the map before the
file-open check, so a note-less character still wipes the previous one's
map; and an empty-globals transition drops the cache so a stale path is
never read or written.

FriendInfo's optional strings (notes, className, area) are left nil when
absent instead of "" -- SetFieldString coerces null to "", which is
truthy in Lua and would fool an `if info.notes then` check.

Verified in-game: set / get / clear by name and by index.
2026-08-07 20:14:04 -05:00
Brues eefcbb17f2 docs: document C_FriendList.GetFriendInfo family
Add API.md sections and the README matrix row for GetFriendInfo,
GetFriendInfoByIndex, and GetNumFriends, with the FriendInfo field list
and example values captured from a live /dump (verified, not guessed).
2026-08-07 19:42:16 -05:00
Brues 599a65d80c Add C_FriendList.GetFriendInfo / GetFriendInfoByIndex / GetNumFriends
Return the modern FriendInfo table (name, connected, level, className,
area, guid, afk, dnd, plus vanilla-truthful mobile / referAFriend /
rafLinkType defaults). Fields are read straight from the friend entry,
mirroring the engine's GetFriendInfo (FUN_005AD060): class name via
ChrClasses.dbc, zone via AreaTable.dbc resolved to the parent area, both
locale-applied. Verified in-game against a live friends list -- online,
offline, level-60 and level-1, with AFK and DND toggled.

Factor the friend-entry layout and list accessors into a shared
friendlist/FriendList.h and move IsFriend onto it, so the one struct has
one definition. Add OFF_AREATABLE_PARENT_ID (0x08) for the zone resolve.
2026-08-07 19:41:11 -05:00
Brues 228c5daa0f docs: document IsFriend, GetSpellDispelType, IsNextMeleeSpell, ResetsMeleeSwing
Add API.md sections and README matrix rows for the four functions, with
example returns verified against Spell.dbc. Also correct two stale docs:
- IsRangedAutoAttackSpell now describes the AttributesEx2 autorepeat flag
  (bit 0x20), matching the fixed behavior -- not the old Attributes
  RANGED-bit test that wrongly matched Aimed Shot / Multi-Shot.
- ResetsMeleeSwing mirrors the server's IsMeleeAttackResetSpell: true for
  cast-time spells whose casting resets the swing (Fireball, Frostbolt),
  false for instant specials (Sinister Strike) and for Slam (NOT_RESET
  flag). The first draft had the examples and framing backwards.
2026-08-07 19:22:09 -05:00
Brues cc6953a530 Add C_FriendList.IsFriend(guid)
Backport the friend-list membership check. Friends live inline in the
social singleton (0x00C28168): up to 50 entries, stride 0x20, each with
a GUID at +0x08 and a name pointer at +0x04 (verified from GetNumFriends
/ GetFriendInfo and the count walker FUN_005AE490). IsFriend matches the
input GUID against +0x08 -- the GUID the server sends for online and
offline friends -- with a name-compare fallback (GUID -> NameCache name),
and also accepts a bare character name.

Renamed VAR_WHO_SYSTEM -> VAR_SOCIAL_SYSTEM: 0x00C28168 is the one social
singleton shared by the friend list, ignore list, and /who system, so it
gets one accurate name instead of a who-specific alias plus a duplicate.
2026-08-07 19:21:59 -05:00
Brues 84da9c23df Consolidate the duplicated Spell.dbc attribute flag bits
The remaining flag-bit duplicates -- the same drift risk that caused the
AttributesEx2/Ex3 mix-up -- now live once in Offsets.h:
- SPELL_ATTR_PASSIVE (0x40): was already in Offsets.h yet copied in
  Info.cpp and Level.cpp; drop both locals.
- SPELL_ATTR_EX_CHANNELED (0x4|0x40): identical local in Cast.cpp and
  CastEvents.cpp; add to Offsets.h and repoint.
- SPELL_ATTR_EX2_AUTOREPEAT_FLAG (0x20): the same bit under two names
  (Cast's _AUTOREPEAT, AutoAttack's _FLAG); unify in Offsets.h.

Single-use flag bits (TRADESPELL, RANGED, HEALTH_FUNNEL,
HIDDEN_CLIENTSIDE, ON_NEXT_SWING, NOT_RESET_AUTO_ACTIONS) and per-module
effect/target enum codes stay local -- they are not duplicated and read
clearer at the use site.
2026-08-07 17:52:55 -05:00
Brues 6e58cb81d1 Consolidate SpellIcon path and remaining Spell.dbc offset stragglers
Fold the last duplicated DBC offsets into Offsets.h:
- SpellIcon.dbc path (+0x04): 4 copies across 3 files -> OFF_SPELLICON_PATH.
  aura/Data and spell/Cast had local consts; spell/Info used two raw
  `iconRec + 4` literals.
- totem/Tracker's OFF_MISC_VALUE (0x1A8) duplicated the existing
  OFF_SPELL_RECORD_EFFECT_MISC_VALUE -- repointed. OFF_TOTEM_TOOL (0xA0) is
  a Spell.dbc field, added as OFF_SPELL_RECORD_TOTEM.

Audit result: unit-descriptor offsets were already fully centralized in
Offsets.h, and item ItemStats_C fields are read via a named struct rather
than offset consts, so neither needed work. Spell.dbc and its sub-DBC
record offsets are now a single source of truth.
2026-08-07 17:49:05 -05:00
Brues 8a065481b4 Consolidate all Spell.dbc record offsets into Offsets.h
Extend the single-source-of-truth cleanup to the whole Spell.dbc record
layout. 40 local constexpr offset copies across 16 files (spell/, totem/,
lossofcontrol/, macro/, aura/) redefined field offsets that belong in
Offsets.h: name (0x1E0), icon (0x1D4), effect (0xF4), rank (0x204),
effect implicit targets (0x148/0x154), powerType (0x7C), manaCost (0x80),
rangeIndex (0x90), castingTimeIndex (0x48), maxLevel (0x6C), spellLevel
(0x74), manaCostPercent (0x270).

Add the ones Offsets.h lacked as OFF_SPELL_RECORD_* and repoint every
local use to the Offsets:: constant, deleting the duplicates. Purely
mechanical and behavior-preserving -- every local value already matched
the canonical (verified before repointing). SpellIcon.dbc / SpellRange.dbc
sub-record offsets (0x04/0x08) stay local; they are different structs.
2026-08-07 17:44:01 -05:00
Brues 2a7cbf75ca Remove the invalid auto-learn hide gate in GetCurrentLevelSpells
SpellHiddenFromAutoLearn tested AttributesEx3 bit 0x02000000, a gate
ported from a MoP function (FUN_00911c60) whose +0x24 field is not
1.12's AttributesEx3. Verified against Spell.dbc: in 1.12 the bit is set
on only 44 of 27925 records -- a grab-bag of passive procs, odd DoT
ranks, the Night Elf priest Starshards line, and Turtle customs -- so it
is not an auto-learn flag and could only wrongly hide legitimate
learnable spells (Starshards carries it).

Drop the AttributesEx3 test and keep the verified HIDDEN_CLIENTSIDE
(Attributes bit 0x80) filter, renamed SpellHiddenFromSpellbook. The
authoritative auto-learn signal is SkillLineAbility.learnOnGetSkill
(col 9), not a Spell.dbc bit; this feature reports the broader
"trainable at level" set and applies no learnOnGetSkill filter.
2026-08-07 16:58:14 -05:00
Brues ff5ce5cdcb Fix IsRangedAutoAttackSpell to test the autorepeat flag
The check tested Attributes bit 1 (RANGED), which every ranged ability
sets -- so Aimed Shot and Multi-Shot wrongly counted as ranged
auto-attacks. The two auto-repeat spells (Auto Shot, Shoot) are the ones
with SPELL_ATTR_EX2_AUTOREPEAT_FLAG (AttributesEx2 bit 5, 0x20). Verified
from Spell.dbc: Auto Shot (75) and Shoot (5019) carry Ex2 0x20; Aimed
Shot (19434) and Multi-Shot (2643) set only RANGED, not the flag.
2026-08-07 16:52:25 -05:00
Brues 47b6a66b96 Fix GetSpellInfo isFunnel to read the health-funnel flag
isFunnel read AttributesEx bit 6, which is CHANNELED_2 -- false for
Health Funnel itself and true for unrelated channels, so it never
actually detected funnel spells. The real flag is
SPELL_ATTR_EX2_HEALTH_FUNNEL (AttributesEx2 bit 11, 0x800). Verified
from Spell.dbc: Health Funnel (755, Ex2=0x808) and Hellfire (1949,
Ex2=0x800) carry it; the channeled non-funnels Drain Life, Mind Flay,
Arcane Missiles, and Rain of Fire do not.
2026-08-07 16:51:38 -05:00
Brues e78c36bb70 Fix the spell-mod gate to read AttributesEx3, not AttributesEx2
The prior consolidation moved the spell-mod disable read from record
+0x24 to +0x20 on the handoff's claim that all three "0x24 readers"
intend AttributesEx2. A tortoise-wow sweep plus client disassembly
disproved that for the mod gate: the client's spell-mod core
(FUN_006e6b30) reads [record + 0x24] & 0x20000000 -- AttributesEx3 bit
29, SPELL_ATTR_EX3_IGNORE_CASTER_MODIFIERS, which is the real "ignore
caster modifiers" flag. AttributesEx2 bit 29 is CANT_CRIT and has
nothing to do with spell mods. So +0x20 was a regression.

Add OFF_SPELL_RECORD_ATTRIBUTES_EX3 (0x24) and the correctly named
SPELL_ATTR_EX3_IGNORE_CASTER_MODIFIERS to Offsets.h, and point Mod.cpp
at them. Cast.cpp's autorepeat read stays at AttributesEx2 (bit 5,
AUTOREPEAT_FLAG) -- that one was a genuine EX2 flag and the move to
+0x20 was correct.

Level.cpp's auto-learn gate was ported from a Cata function
(FUN_00911c60, outside 1.12's .text) and its 1.12 meaning is
unverified, so restore it to the original +0x24 read (no behavior
change from before the consolidation) and mark the constant unverified
pending a real 1.12-client check.
2026-08-07 16:43:35 -05:00
Brues 41fb17502d Add C_Spell spell-record field readers
Add C_Spell.GetSpellDispelType, IsNextMeleeSpell, and ResetsMeleeSwing.
Each reads a Spell.dbc field straight from the record: dispel type
(0x10), the on-next-swing attribute bits (0x18 & 0x404), and the melee
swing-reset rule (InterruptFlags 0x54 has AUTOATTACK and AttributesEx2
0x20 lacks NOT_RESET_AUTO_ACTIONS). All offsets come from the shared
Offsets.h constants. This lets pfUI drop nampower's GetSpellRecField.
2026-08-07 16:35:04 -05:00
Brues a989499cae Consolidate Spell.dbc attribute offsets into Offsets.h
The Attributes (0x18), AttributesEx (0x1C), and AttributesEx2 (0x20)
record offsets were each copied as local constants across several spell
modules. AttributesEx2 was 0x24 in three of those copies, which is
actually AttributesEx3 -- an off-by-one-field bug. Spell.dbc stores each
record as a flat uint32 array by column, so AttributesEx2 (column 8) is
at 0x20. Verified against the 1.12.1 client, the server column order,
and nampower.

Move the record offsets to Offsets.h as the single source of truth (add
AttributesEx at 0x1C and InterruptFlags at 0x54; correct AttributesEx2
to 0x20) and remove the local copies in AutoAttack, Cast, CastEvents,
Info, and Level. This corrects the autorepeat aim-time skip, the
auto-learn hide check, and the spell-mod family gate -- all of which read
AttributesEx2 -- and removes the duplication that let one wrong offset
become three bugs.
2026-08-07 16:34:46 -05:00
Brues 722c257acb fix(aura): size source cache to the raid working set; never evict a present aura
The Aura::Source cache holds one entry per (target, spellId) for every
aura-applying SMSG_SPELL_GO observed — every buff on every unit in view, not
just the player's. At 256 entries the table was permanently full in a group or
raid, so nearly every new cast fell through Store's overflow branch, which
overwrote a blind round-robin slot with no presence or expiry check. That slot
was almost always a live buff, dropping its cached caster — the "buff kept its
sourceGUID for a few minutes then lost it" report (e.g. Blessing of Wisdom).

Size kCacheSize to the realistic worst case (2048 — a fully raid-buffed 40-man
plus debuffs, ~80 KB static) so the table stops living at capacity, and replace
the round-robin overflow with a presence-aware victim: prefer the
least-recently-updated ORPHAN (no live descriptor backing — out of range /
despawned), and only touch a still-present entry under true saturation (every
one of 2048 slots a live aura, practically unreachable). This extends the
descriptor-presence invariant the tick sweep and slot-reuse already honor to
the last unguarded eviction path, so an aura still on a resolvable unit keeps
its source for its whole life. Verified in-game: 30+ minutes in a full
Stormwind with no source loss.
2026-08-07 16:16:57 -05:00
Brues a6c7098106 fix(aura): match self-buffs in the PLAYER aura filter
The self-buff sourceGUID inference from 7caee62 ran only at display, so a
self-buff we never saw cast (e.g. login-persisted Inner Fire) showed
sourceUnit="player" yet was excluded from HELPFUL|PLAYER — IsPlayerCast
still keyed off the Aura::Source cache alone, which has no entry for it.

Centralize the resolution in EffectiveCaster (observed caster, else the
self-buff inference: a self-only-target aura is cast by the unit carrying
it) and route display plus both filter predicates (IsPlayerCast,
GroupIsPlayerCast) through it, so the two paths can't disagree. The
predicate stays unit-scoped: a self-buff on the player matches PLAYER; the
same self-buff on another unit resolves to that unit and correctly does not.
2026-08-07 01:51:28 -05:00
Brues 7caee620e8 fix(aura): make C_UnitAuras sourceGUID persist and infer self-buff casters
Two changes so an aura's source stops vanishing:

Pin observed casters. The WorldTick expiry sweep (and Store's slot
reuse) dropped a cache entry once its computed expirationMs elapsed —
but that time is only a base-duration estimate for non-player casters
(we lack their mod tables), so a talent-extended debuff expired in the
cache while still live on the target. The entry took the caster with it,
and the descriptor path then rendered the aura with no sourceGUID. Now
an entry whose aura the owning unit's live descriptor still lists is
never timer-reclaimed (DescriptorListsAura resolves the GUID through the
object manager); only genuinely orphaned entries — unit out of range /
stealthed / despawned — expire. The fallback path already skips expired
entries, so no phantom can resurface. PushEnriched also reports an
already-elapsed cached expiration as unknown rather than a negative
remaining time.

Infer self-buff casters. On a caster miss (no cache entry, or one with
no caster), a self-only-target aura can only have been self-cast, so the
unit carrying it is its own source. Factor the record scan out of the
C_Spell.IsSelfBuff Lua wrapper into Spell::IsSelfBuff::IsSelfBuff and
call it from PushEnriched to recover sourceUnit/sourceGUID for
pre-existing self-buffs we never saw applied. Caster is exact; timing
stays unknown.
2026-08-07 01:45:09 -05:00
Brues 954533a170 feat(aura): add CROWD_CONTROL / !CROWD_CONTROL aura filter
Reuses the C_LossOfControl classifier so the two never drift. Extract
ClassifyControlLoss out of the LoC module into a shared
Spell::CrowdControl: Classify(rec) returns the hard control-loss type
string (stun/fear/silence/root/charm/confuse/pacify/possess/disarm) and
still backs C_LossOfControl; IsCrowdControl(spellID) backs the aura
filter.

Crowd control is broader than loss of control: IsCrowdControl also
counts movement slows / snares (SPELL_AURA_MOD_DECREASE_SPEED = 33,
added to Offsets.h), which are crowd control but not a loss of control —
so a Frostbolt/Hamstring slow is CROWD_CONTROL while C_LossOfControl
still ignores it. Classify (LoC) is unchanged.

Wire it as a third CcMode dimension on the Aura::Data::Match struct,
checked in MatchesAura; tokenizer honors CROWD_CONTROL / !CROWD_CONTROL.
Docs updated. Verified in-game: Psychic Scream (fear) and a Frostbolt
slow both classify as CROWD_CONTROL; DoTs and buffs do not.
2026-08-07 01:21:17 -05:00
Brues dbe5ab40ee feat(aura): add DISPELLABLE / !DISPELLABLE aura filter
Modern DISPELLABLE means "can be dispelled/purged/stolen by SOME
mechanism, regardless of whether the player can". Confirmed against the
Turtle/Tortoise server: an aura is dispellable iff its Spell.dbc Dispel
type is Magic(1), Curse(2), Disease(3), or Poison(4) — the server's
DISPEL_ALL_MASK — and vanilla applies no per-aura "undispellable"
attribute, so the dispel type is the whole story.

Data::IsDispellable(spellID) reads the Dispel field (OFF_SPELL_DISPEL_TYPE)
via the existing SpellRecord and checks 1..4 (the type ID directly, not
dispelName != nil, in case SpellDispelType.dbc names Stealth/Invisibility).

Fold the caster and dispel predicates into one Aura::Data::Match struct
that replaces the standalone CasterMode parameter across the Find*/Push*/
Append* surface, applied by a shared MatchesAura(match, isPlayerCast,
spellID). Orthogonal filter dimensions now add a struct field instead of
another parameter. Existing caster behavior is unchanged.

Tokenizer honors DISPELLABLE / !DISPELLABLE; docs updated. Verified
in-game: HARMFUL|DISPELLABLE returns Magic debuffs, HARMFUL|!DISPELLABLE
returns physical debuffs (Rend).
2026-08-07 01:06:39 -05:00
Brues f3b328247c ci: run build steps in PowerShell, not bash
shell: bash on the self-hosted Windows runner resolved to the WSL
launcher at C:\Windows\System32\bash.exe (Git Bash isn't on the
NETWORK SERVICE account's PATH), so Resolve version died with 'no
installed distributions'. Default the build job's run steps to Windows
PowerShell 5.1 (always present) and rewrite Resolve version accordingly,
dropping the bash/WSL dependency from the native-Windows build.
2026-08-07 00:44:42 -05:00
Brues 470361fbce ci: fall back to windows-latest when self-hosted runner is offline
Probe repo runners in a pick-runner job and hand the resolved label
(self-hosted if one is online, else windows-latest) down to build via
needs, so an offline self-hosted runner no longer queues the build
indefinitely.
2026-08-07 00:30:57 -05:00
Brues 2d266a9b76 feat(aura): tokenize C_UnitAuras filters; add PLAYER/!PLAYER negation
The aura filter string was matched with raw strstr, which the modern
AuraFilters token set breaks: strstr(f, "PLAYER") also matches
RAID_PLAYER_DISPELLABLE (false PLAYER-only), and "!PLAYER" contains
"PLAYER" so it was read as PLAYER-only — the opposite of intent.

Replace it with a real tokenizer (Aura::Api::ParseFilters): tokens
separated by "|" or whitespace, each optionally negated with a leading
"!", whole-token matching. Honored tokens: HELPFUL / HARMFUL
(descriptor slot ranges) and PLAYER / !PLAYER (caster == / != the local
player). Every other AuraFilters token (RAID, CANCELABLE, DISPELLABLE,
INCLUDE_NAME_PLATE_ONLY, MAW, …) is accepted and ignored — vanilla has
no data for them.

!PLAYER makes the caster restriction ternary, so the Aura::Data layer's
`bool playerOnly` becomes `CasterMode { Any, PlayerOnly, NotPlayer }`
threaded through every Find*/Push*/Append* function (plus the
lossofcontrol call site). Existing Any/PlayerOnly behavior is preserved
exactly; NotPlayer is additive. A cache miss counts as not-player, so
!PLAYER includes auras whose cast we did not observe (matching
IsPlayerCast's miss semantics).

Also fixes: "PLAYER" alone on the by-id / by-name getters now searches
both ranges instead of wrongly restricting to helpful.

Docs: API.md gains an STE "Filter tokens" note under GetAuraDataByIndex.
2026-08-06 23:50:15 -05:00
Brues 8e3e207f83 fix(frame): show mouseover tooltip for offline party/raid members
pfUI-style unit frames have no OnEnter; their tooltip is produced by
Frame::Attributes driving the engine mouseover setter (FUN_00492890).
That setter builds the unit tooltip only when the GUID resolves to a
live object, so an offline / far out-of-range party or raid member
(roster GUID, no object) got no tooltip.

The unit-tooltip builder FUN_00529FE0 itself works offline — with no
object it fills name/level/class + the "Offline" line from the party/
raid roster (same path GameTooltip:SetUnit("party1") uses). So when the
hovered unit-frame's GUID has no live object, build the tooltip
ourselves from the roster.

Fire OnTooltipSetDefaultAnchor before building (via the self-contained
FUN_FRAME_INVOKE_SCRIPT), exactly as the engine setter does — that
FrameXML handler sets the tooltip owner/anchor and is what shows it.
Without it the first hover worked by luck but a re-hover after the
leave-clear had no owner and stayed invisible (only a live-unit hover,
which takes the engine's own anchor path, would recover it).

New offsets: VAR_GAMETOOLTIP_OBJECT_PTR (0x00B4B3C4, the mouseover
tooltip object) and OFF_TOOLTIP_SET_DEFAULT_ANCHOR_HANDLER (0x444).
2026-08-06 23:26:52 -05:00
Brues 1fd1295679 debugtools: use DEBUG_FRAMESTACK from locale if available 2026-08-06 19:27:14 -05:00
Brues e4a75e68ca feat(frame): add GetMouseFoci — mouse-focus stack under the cursor
Modern WoW exposes GetMouseFoci() (the stack of frames under the
cursor) alongside GetMouseFocus(), with GetMouseFocus() ==
GetMouseFoci()[1]. Vanilla stores only the single topmost focus
(Script_GetMouseFocus reads *(ctx + 0x7C)); there is no stored stack.

Reimplement natively (no Lua polyfill, no hooks): walk the engine frame
list that Script_EnumerateFrames iterates (head *(ctx + 0xCC4), next
+0x308, low-bit/null sentinel), keep frames that are visible +
mouse-enabled and whose rect contains the cursor (Region getters +
cursor/effective-scale, mirroring Frame::Modern's IsMouseOver), order
top-first by strata rank then frame level (level read directly from
+0xC4), and force index 1 to the engine's stored focus so the invariant
holds by Lua table identity. Frames are pushed via the shared
UI::FrameObject::Push so == compares the same wrapper GetMouseFocus
returns.

Filters to the mouse-enabled (interactive) stack, matching 1.15.x
(verified: GetMouseFocus skips a higher non-mouse-enabled cooldown to
land on the button, and 1.15.x GetMouseFoci returns the same set).
/framestack lists more because it is a pure-geometry debug view, not the
mouse-focus set.

Docs: API.md entry (Simplified Technical English).
2026-08-06 18:42:35 -05:00
Brues 28bf41c647 locale: Backport debuff symbols and debug label
Add DEBUFF_SYMBOL_{CURSE,DISEASE,MAGIC,POISON} and DEBUG_FRAMESTACK translations to locale files (deDE, enUS, esES, frFR, ruRU, zhCN, zhTW).
2026-08-06 17:59:16 -05:00
Brues ac97f9b960 ci: add workflow_dispatch manual trigger to Build
Push-triggered runs can be silently dropped when GitHub throttles
webhooks during an Actions incident, leaving no way to kick a build.
Add a workflow_dispatch trigger as a manual escape hatch, runnable
from the Actions UI.

A single Resolve step computes is_release/tag from the pushed ref, the
dispatched ref, or an optional `tag` input, and every downstream step
keys off it — so push behavior is unchanged. Dispatch modes: run from a
vX.Y.Z tag (release build of that commit), run from a branch with a
`tag` input (release build attached to that tag), or run from a branch
with a blank input (dev build artifact). The Release step now passes
tag_name explicitly so it also works when the ref is a branch.
2026-08-06 17:17:46 -05:00
Brues 7f6c6e2dd4 consolidate UPDATE_MOUSEOVER_UNIT compat logic 2026-08-06 16:45:19 -05:00
Brues 9d09266fc6 build(embed): flag-driven embedded toc version + marker-gated dev override
Two related fixes to the embedded-addon precedence so users stop
running a stale/mismatched on-disk !!!ClassicAPI without realizing it,
while keeping the developer's disk-wins workflow intact.

Version is now a pure build-flag artifact. The embedded copy's
`## Version:` is stamped from CLASSICAPI_TAG at embed time
(cmake/embed_addon.cmake rewrites the line in-memory before hex
encoding, portable via a temp-file round-trip). The committed source
toc stays `## Version: DEV` and is never edited, so a release build is
`-DCLASSICAPI_TAG=vX.Y.Z` and nothing else. Dropped the CI sed step
that previously mutated the source toc. Moved the version-derivation
block above the embed step so CLASSICAPI_TOC_VERSION is available to it.

Dev override moved from the toc version to an explicit marker. A
`.classicapi-dev` file in the on-disk addon folder now forces the disk
copy to win regardless of version (checked via the original
FUN_FILE_READ, so it reflects a real on-disk file). Consequently `DEV`
no longer sorts as "newer than any release" in CompareVersions — it
sorts oldest — so a stray `DEV` source/clone copy on a user's disk no
longer silently shadows a newer embedded release. The normal local
loop still works without the marker (local DEV DLL + DEV disk = tie =
disk wins); the marker is only needed to prefer disk against a released
DLL. The marker is gitignored and excluded from the embed (both globs),
and the release ships only the DLL, so it can exist only in a
developer working tree.
2026-08-06 16:37:36 -05:00
Brues d972433ab0 compat(puppeteer): guard EnemyTracker against mouseover-loss fire
ClassicAPI 1.8.4 added a UPDATE_MOUSEOVER_UNIT loss-fire polyfill
(matching retail): the event now also fires when the mouseover goes
unit -> nothing, with `mouseover` already cleared. Puppeteer's
EnemyTracker OnEvent reads `unit = UnitGUID("mouseover")` on that
event, which is now nil on the loss fire; it then calls
`UnitCanAttack("player", unit)`, and Puppeteer routes UnitCanAttack
through its DoubleUnitProxy (no nil guard) straight to native
UnitCanAttack -> engine raises `Usage: UnitCanAttack("unit",
"otherUnit")` on the nil arg.

Wrap PTEnemyUpdater's OnEvent from our AddOnCompat shim and skip the
handler when UPDATE_MOUSEOVER_UNIT fires with no live mouseover, so
the nil never reaches the proxy. Gains still pass through, so enemy
tracking is unaffected. Deferred via ContinueOnAddOnLoaded (Puppeteer
loads after us) and guarded on PTEnemyUpdater existing (it is only
created when SuperWoW is present).
2026-08-06 14:23:29 -05:00
Brues b5513c6b22 fix(cbor): emit canonical map key order (RFC 7049 §3.9)
The CBOR encoder walked string-keyed tables with lua_next (pairs()
order), which Lua does not guarantee to be stable. The pfUI export
path rebuilds its config tables on every press, so each rebuild
re-hashed the same keys into a different internal layout and the map
serialized its key/value pairs in a different byte order -> different
compressed bytes -> different Base64. Harmless (every variant decodes
to the same config) but no stable fingerprint.

EncodeTable's map branch now stashes each key, records its encoded
bytes, sorts by encoded-key bytes (shorter first, then bytewise per
RFC 7049 3.9), then re-fetches key/value in sorted order. Nested
maps sort recursively, so the whole byte stream is canonical. Decode
is order-agnostic, so the round trip stays lossless.

Verified in-game: encode/decode/re-encode of a pfUI profile now
produces a byte-identical Base64 string.
2026-08-06 14:02:19 -05:00
Brues 8a434fea0e fix(aura): keep SMSG_SPELL_GO caster through the descriptor-sync race
C_UnitAuras dropped sourceGUID/sourceUnit for buffs cast by other units
(e.g. a druid's Mark of the Wild / Gift of the Wild on the player).

SMSG_SPELL_GO arrives before the SMSG_UPDATE_OBJECT that adds the aura to
the target's descriptor. In that window an addon aura poll runs
ReconcileCache, which calls EvictAbsent. The just-captured cache entry
named an aura the descriptor did not list yet, so EvictAbsent dropped it
and lost the caster. OnAuraAdded then recreated the entry with no caster,
so sourceGUID stayed nil. Verified by trace: every "Store NEW caster=0x8"
was followed at once by "EvictAbsent (had caster=0x8)".

Give each cache entry a write timestamp (stampMs) and exempt entries
younger than kEvictGraceMs (2s) from EvictAbsent. A real removal is far
older and still gets dropped, and OnAuraRemoved evicts genuine removals
directly, so stale-aura cleanup is unaffected.

Verified in-game: a remote druid buff now reports sourceGUID; a self-cast
buff still reports sourceGUID + sourceUnit="player".
2026-08-06 01:26:39 -05:00
Brues dbbba88aad feat(tooltip): show spell rank in the corner of SetSpellByID
`GameTooltip:SetSpellByID` now shows the spell rank in the top-right
corner of the title line. The cross-class `SetTalentByID` fallback shows
it too. Both go through `Spell::Tooltip::ShowByID`.

The engine builder `BuildSpellTooltip` (`FUN_0052E610`) sets the title
line right-text to `Rank[locale]` when `param_5` or `param_2` is not
zero. `param_5` has no other effect in the builder (confirmed by
disassembly). `SetAction` and `SetPetAction` pass `param_5=1` for this.
Native `SetSpell` and the old `SetSpellByID` passed `0`, so they did not
show the rank. `ShowByID` now passes `param_5=1`.

The change is additive. A spell with no rank (passive or racial) shows
nothing there, the same as the engine.

With this change, the macro tooltips of SuperCleveRoidMacros match the
native action-button tooltips.
2026-08-06 00:32:16 -05:00
Brues b8bd0bce4e fix(unit): gate +0xE68 sub-struct reads on OBJECT_TYPE_PLAYER, not PLAYER_CONTROLLED
The CGPlayer sub-struct at [unit+0xE68] (guild key, PLAYER_FLAGS, quest
list, visible items) exists only on real player objects. Reads of it were
gated on UNIT_FLAG_PLAYER_CONTROLLED, but the server sets that flag on
pets, totems, guardians, companions, and MC'd creatures too (Turtle
UnitDefines.h; Pet.cpp/SpellEffects.cpp/SpellAuras.cpp setters) -- all
TYPEID_UNIT creatures with no such sub-struct. On one of them the +0xE68
pointer is garbage-but-non-null, so the null check passes and the deref
AVs (ERROR #132, pfUI issue #34: UnitIsInMyGuild on a nameplate pet/totem,
frequent in crowded dungeons/raids).

Add Unit::Flags::IsPlayerObject (m_objectType == OBJECT_TYPE_PLAYER via
[obj+0x14]) and use it as the gate at every arbitrary-unit +0xE68 reader:

  - UnitIsInMyGuild  (ReadGuildKey)      -- the reported crash
  - UnitIsAFK/UnitIsDND (TestPlayerFlag) -- same latent crash on a pet
  - IsUnitOnQuest    (Quest::Log::UnitHasQuest)
  - GetInventoryItemID (non-local unit visible-items path)

Local-player-only readers are unaffected. IsPlayerControlled stays for
minion/ownership classification (Unit::Pet), which wants the broad flag.
2026-08-05 20:53:30 -05:00
Brues c3a80053e9 equipment: Backported missing localization strings 2026-08-05 15:52:02 -05:00
Brues 5a3badb5bd feat(macro): add C_Macro.CreateMacro / EditMacro with string icons
The vanilla CreateMacro / EditMacro globals take an icon INDEX into the
GetMacroIconInfo list, and that list omits INV_* item icons entirely --
so item icons are unreachable through the stock API even though the
engine stores and renders them fine. C_Macro.CreateMacro / EditMacro
accept the icon as a texture string (a full Interface\Icons\<name> path
or a bare <name> basename) instead, writing the basename directly to the
macro struct; GetMacroInfo re-prefixes it as Interface\Icons\%s on read,
so any Interface\Icons\ texture round-trips.

Both go straight to the engine's own workers (FUN_004f1010 create /
FUN_004f1280 edit), which do the bounded copy, re-run the primary-spell
parser, set the persist-on-logout dirty flag, and refresh the action
bars. EditMacro resolves its index arg as a slot number or a macro name
(via the GetMacroIndexByName resolver), leaves any nil field unchanged,
and reads back the entry's local flag so the worker's unconditional
rewrite of it is a no-op.

The legacy globals stay untouched (index-only); string-icon callers opt
in through the C_Macro namespace. Verified in-game incl. an INV_* item
icon surviving a relog. Unblocks a pfUI macro-UI remodel.
2026-08-05 01:53:08 -05:00
Brues aae4eb8a2b fix(util): preserve nil holes in vararg forwarding; drop no-op unpack ranges
On this Lua 5.0 build, unpack() ignores its explicit i/j arguments entirely
and takes its element count from getn() -- which returns the table's `.n`
field, or border-searches to the first nil when `.n` is absent. Verified in
the binary (luaB_unpack 0x007030a0 -> luaL_getn 0x006f5050) and in-game
(unpack({1, 1, nil, 1}, 1, 4) yields just 1, 1).

- GenerateClosure built its forwarding table `rest` with no `.n`, so
  unpack(rest, 1, restN) border-searched and silently dropped every value
  past the first nil hole in the payload -- despite the comment claiming
  embedded nils survive. It now stamps `all.n` and unpack(all) forwards
  holes intact.

- Every other unpack(x, 1, x.n) / unpack(x, 1, count==x.n) call was a no-op:
  the table already carried `.n`, so unpack(x) is identical. Simplified
  across FunctionUtil, Pools, CallbackRegistry, and TableUtil's SafeUnpack,
  and corrected the header comments that recommended the redundant form.
2026-08-04 18:13:14 -05:00
Brues 0a31ee8a89 fix(events): stop EventRegistry dispatch on PLAYER_LOGOUT to prevent #132 crashes
A callback firing during the engine's logout teardown can touch state
that has already been freed, faulting with ERROR #132 (ACCESS_VIOLATION).
A dedicated frame owns PLAYER_LOGOUT and tears down frameEventFrame's
event delivery (UnregisterAllEvents + clear OnEvent) so nothing dispatches
during teardown. A separate frame keeps this decoupled from the
ref-counted consumer event set, which may no longer hold PLAYER_LOGOUT.
2026-08-04 13:25:02 -05:00
Brues 969273f5f7 tradeskilllink: link reagents in chat 2026-08-04 12:28:43 -05:00
Brues a4760386ed tradeskilllink: Properly format links for SetHyperlink 2026-08-04 11:55:47 -05:00
Brues f9ef12bc9b itemmixin: GetItemLink/GetInventoryTypeName switched to select
These were backported before select was
2026-08-03 22:39:16 -05:00
Brues 89d86bffb7 addon-compat: unregister ShaguTweaks libpredict's backported TBC events
ShaguTweaks' libpredict sender frame (ShaguTweaksPredictionSender) registers
TBC-era events alongside its vanilla ones — COMBAT_LOG_EVENT_UNFILTERED and
UNIT_SPELLCAST_START/STOP/FAILED/INTERRUPTED/SENT (libpredict.lua:342-347). In
stock 1.12.1 those never fire, so registering them was a harmless no-op and only
the vanilla SPELLCAST_* path ran. ClassicAPI now backports those events, so
libpredict's TBC branches fire too and double-process cast/heal predictions.

Unregister the six TBC events on libpredict.sender once ShaguTweaks loads,
restoring vanilla-only behavior. Guarded on the addon existing and the
libpredict table being present.
2026-08-03 17:06:07 -05:00
Brues a0d8d6d723 fix(events): forward leading-nil event payloads to callbacks
EventRegistry callbacks (RegisterOnceFrameEventAndCallback, etc.) dropped any
payload whose first arg was nil — e.g. this client's reload PLAYER_ENTERING_WORLD
(arg1=nil, arg2=1) delivered nil to every callback parameter. Root cause is a
WoW Lua 5.0 quirk: unpacking a table whose hole lands right after a present
element into a `func(first, ...)` collapses the receiving vararg count to 0, so
the payload after `owner` was silently lost.

Fix both build-then-unpack sites in CallbackRegistry to pass the leading arg
explicitly and the payload as the unpacked tail:
- TriggerEvent Function branch: func(owner, unpack(arg, 1, arg.n))
- GenerateClosure: func(bound[1], unpack(rest, 1, restN))

Verified in-game: RegisterOnceFrameEventAndCallback("PLAYER_ENTERING_WORLD", cb)
now delivers arg2=1 to the callback's 2nd parameter on reload.
2026-08-03 14:23:12 -05:00
Brues e0e4fbcf84 docs: list the new frame-attribute + modern-script-arg APIs
The attribute methods and the modern-script-args toggle shipped on this
branch but weren't in the README index, and the toggle wasn't documented
at all.

- README: add frame:SetAttribute / SetAttributeNoHandler / ClearAttribute /
  GetAttribute, the OnAttributeChanged script, and SetModernScriptArgs /
  GetModernScriptArgs to the Frame row.
- docs/API.md: document SetModernScriptArgs(enable) / GetModernScriptArgs()
  (opt-in modern positional handler args) with a Frame TOC entry. The
  attribute methods and OnAttributeChanged were already covered.
2026-08-03 01:57:45 -05:00
brues-code 1da06d4a73 frame: attribute backport, modern script args, and SMSG hook consolidation (#13)
* frame: backport Frame:SetAttribute/GetAttribute + unit-frame mouseover/click

Adds native SetAttribute / SetAttributeNoHandler / GetAttribute on the base
Frame registry: a per-frame, case-insensitive value store with the 3.3.5
prefix/name/suffix getter precedence, stored on the frame's own Lua table.

A `unit` attribute makes the frame a mouseover source. A WorldTick poll of the
engine's mouse-focus frame (GetMouseFocus's global) calls the real mouseover
setter (FUN_00492890) for its unit -- 1:1 with hovering the 3D model: model
highlight, mouseover tooltip, UPDATE_MOUSEOVER_UNIT, and the native GUID slot.
Stomp-proof (the engine's 3D-hover setter is event-driven) and independent of
the frame's scripts, so an addon setting its own OnEnter can't break it.

A `type1`/`type2`/`type` attribute installs a chained OnClick on that frame only
(PCall-guarded, Button-only) that dispatches target / assist / focus on the
unit at click time, then runs any prior handler.

No global hooks: mouseover reads the mouse-focus global; clicks use the frame's
own OnClick. Deliberately does NOT MinHook the button-click dispatcher
(FUN_00779540) -- SuperWoW's click-casting owns that prologue and a second
inline hook corrupts the trampoline (ERROR #132).

* frame: extend attribute backport (one-verb click dispatcher + OnAttributeChanged)

The `type*` click path now mirrors retail's SecureActionButton_OnClick:
resolve ONE verb per click from the modifier/button-qualified `type`
attribute and perform it, instead of a fixed `type1=target`.

- Modifier/button resolution: `[alt-/ctrl-/shift-]type[1..5]` with
  prefix..name..suffix -> name..suffix -> name precedence, read from the
  live key state and the click's button.
- Verbs: target (with the engine's default-interaction precedence -
  cast a pending spell / drop a cursor item on the unit instead of
  switching target), assist, focus, spell, stopcasting, macro, and menu.
- Own-the-click: when a verb resolves we perform it and do NOT chain the
  frame's previous OnClick, so a configured `type1` no longer double-
  dispatches alongside an addon's own conditional click handler.
- Self-healing wire: addons that re-SetScript OnClick (pfUI on every raid
  relayout) clobber our closure; WireOnClick re-wraps a clobbered Lua
  handler but skips its own C closure, so re-setting `type*` recovers
  without double-chaining.

Dispatch goes straight to C++ where we own the code - no Lua round-trip
through the global table: spell -> Spell::AtUnit::CastByName (a native
unit-targeted cast; the unit's GUID is fed to the engine's dispatcher so
there's no target juggling, and ground-target spells land at the unit's
feet), focus -> Unit::Focus::Set, and the target verb's predicates ->
Spell::AtCursor::IsPlacementActive / Cursor::Info::HasItem. Only genuine
engine entries (TargetUnit/AssistUnit/SpellTargetUnit/DropItemOnUnit/
SpellStopCasting) and addon-provided functions still go through Lua
globals. Spell::AtUnit gains a C++ header sharing its CastCore with the
C_Spell.CastAtUnit Lua entry.

macro verb: takes the content from the `macrotext`/`macro` attribute and
prefers an addon-provided RunMacro (SuperCleveRoidMacros etc. - handles
named macros and extended macro text), falling back to running the text
natively when no RunMacro global is present. The native path runs each
line through the stock FrameXML ChatEdit_ParseText via a throwaway
edit-box (GetText closure + no-op __index), so it needs no addon.

menu/togglemenu verb: pops the standard unit dropdown at the cursor via
the new ClassicAPI_ToggleUnitMenu (Util/SecureUnitMenu.lua), resolving
the unit -> menu type with Blizzard's own generic resolver
(self->SELF, pet->PET, grouped player->PARTY, other player->PLAYER,
NPC->RAID_TARGET_ICON). Keeps the FrameXML dropdown logic in Lua with
the C side as a thin call.

OnAttributeChanged is now a real SetScript/GetScript/HookScript-able
frame script on every frame: SetAttribute fires it, SetAttributeNoHandler
suppresses it. Made settable by co-hooking the base-frame script-name
resolver FUN_0076a0d0 (the one every frame type delegates through) and
handing back an external per-frame {handler, context} cell for that name -
frames are immortal in 1.12, so the cell never goes stale. One hook does
it (vs the tooltip OnTooltipSet* work's five) because we already own the
firing side. 1.12 convention: the handler reads this = frame, arg1 = name,
arg2 = value. Recursion-guarded so a handler may itself SetAttribute.

* frame: add Frame:ClearAttribute (retail 11.2.0)

`cleared = frame:ClearAttribute(name)` removes an attribute and returns
whether it was set. Registered on the base Frame method registry next to
SetAttribute/GetAttribute, so every frame has it.

Routes through DoSet's nil-value path (removes the stored key, drops a
`unit` mouseover binding) but does NOT fire OnAttributeChanged — verified
against a live retail 11.2 client: SetAttribute fires the handler,
ClearAttribute fires nothing, and the return is true for a set attribute /
false when there was nothing to clear.

* frame: store attributes in the Lua registry, hidden from Lua

Attributes were kept as a subtable on the frame's own Lua table under a
control-char key ("\1ClassicAPIAttributes"). That key, while collision-
safe, is still enumerable via pairs(frame) and readable/writable from Lua.

Move the store to registry[frame] in the Lua registry (LUA_REGISTRYINDEX),
which has no _G path — so the attribute map is invisible to pairs(frame)
and can't be read or tampered with from script, matching how retail keeps
attributes C-side. Only PushSub changed (create/fetch now key the registry
by the frame table); GetAttribute/DoSet/CopyAttr sit on top unchanged.
1.12 frames are immortal, so the strong registry key never leaks. The dead
kAttrKey constant is removed.

Verified in-game: SetAttribute/GetAttribute still round-trip, and a
pairs(frame) scan no longer finds any ClassicAPI key.

* frame: add the `item` click verb (SecureActionButton item action)

type*="item" uses the modifier-qualified `item` attribute:
- a "bag slot" string (e.g. "0 1") -> UseContainerItem(bag, slot);
- otherwise an item name / itemID / link -> C_Item.UseItemByName(item, unit),
  passing the unit as the use target (self-use items ignore it, targeted
  ones like scrolls/bandages apply to it);
- the deprecated `bag` + `slot` attributes are honored when `item` is unset.

Both bag paths go through lua_call (new CallTableFunc2Str / CallGlobalNum2)
rather than a direct C++ call: the item-use bag walk does SetTop(L, 0), so
it needs its own Lua stack frame — a direct call would wipe the dispatcher's
stack. (spell stays direct because Spell::AtUnit is stack-free; the helper
comment records the distinction.) Retail's "bag slot" string is the
preferred form; the deprecated per-attribute form is supported too.

* docs: format the attribute click verbs as a table

The verbs were one long paragraph of nested parentheticals - hard to scan.
Replace it with a Verb | Extra attributes | Action table so each verb's
inputs and behavior are legible at a glance. Content-equivalent; no API change.

* frame: clear target on the `target` verb when unit is "none"

Retail's SecureActionButton target action treats a "none" unit as "clear
target". Match it: the `target` verb calls ClearTarget() when the resolved
`unit` is "none" (case-insensitive), before the normal cursor/spell
precedence. Mouseover already handles "none" implicitly (it resolves to
GUID 0 = no unit). Docs' target-verb row updated.

* frame: pass modern positional args to script handlers

Vanilla always invokes frame-script handlers with zero Lua args; the
handler reads this/arg1/event as globals. Modern addon ports write
SetScript("OnMouseWheel", function(self, delta) ...) and get nothing.

Co-hook both script runners -- FUN_FRAME_INVOKE_SCRIPT (no-arg scripts)
and FUN_FRAME_RUN_SCRIPT_ARGS (scripts with values) -- and reimplement
their pcall tail: keep the engine's exact this/argN global save-set-
restore and message-handler errfunc, but additionally push self +
arg1..argN as real positional arguments and pcall with nargs = 1+N.
Purely additive: a zero-param vanilla handler ignores the extras and
reads globals; a modern (self, delta) handler binds them.

OnEvent gets (self, event, arg1..argN), detected structurally by
matching the invoked handler ref against the frame OnEvent slot
(frame+0x0C) -- exact, since each SetScript makes a distinct ref.

Runtime switch SetModernScriptArgs()/GetModernScriptArgs(), default on;
when off both detours are a straight passthrough to the original runner,
which matters because FUN_FRAME_RUN_SCRIPT_ARGS is the hottest Lua path
in the engine (every OnUpdate frame). Verified in-game across
OnMouseWheel/OnClick/OnValueChanged/OnUpdate/OnEnter/OnLeave/OnEvent.

* net: consolidate spell SMSG hooks onto one dispatch funnel

The spell subsystem's per-opcode SMSG handlers (SpellGo, SpellStart,
SpellDelayed, ChannelStart/Update, SpellFailure, SpellFailedOther,
SpellCooldown) were each co-hooked directly -- and nampower (hadesmem)
plus SuperWoW detour the same prologues. Two inline hookers on one
prologue is the documented MinHook collision risk, and a whole-protocol
bisect fingered exactly this cluster as the crash-suspect surface.

Add Net::PacketDispatch: a receive-side mirror of Net::SendObserver that
co-hooks the single incoming-SMSG dispatch funnel FUN_NET_MESSAGE_DISPATCH
(0x00537AA0) -- a chokepoint nampower does NOT hook (it detours the leaf
handlers) -- and fans each packet out to opcode subscribers with the
cursor at the body and centralized save/restore.

Migrate all eight handlers to subscribers: aura/Source (SpellGo, which
re-decodes the packed guids + spellId the leaf handler used to hand it
pre-decoded), spell/Cast (Start/Delayed/Channel*/Failure*), and
lossofcontrol (Cooldown). The parse bodies are unchanged; only the hook
site moved. Subscribers run before the engine's leaf handler instead of
after a co-hook's original -- verified order-independent for all eight
(self-contained cache/state updates; SpellGo's aura-application handoff
rides a separate SMSG_UPDATE_OBJECT).

Cuts the ClassicAPI-nampower shared spell prologues from 10 to 3 (the
OnAura* method hooks, which have no packet chokepoint to relocate to).
One hook on an uncontended function replaces eight on contended ones.

Verified in-game: cast bars, channels (incl. Mind Control cast-then-
channel), pushback, remote-cast interrupt eviction, and C_LossOfControl
school lockouts all intact.

* ScriptArgs is back to opt-in

* frame: fix ScriptArgs comments to match opt-in default

* frame/net: dedupe packet observers, reuse Lua/token helpers, fix attr edge cases

Post-review cleanup of the attribute + SMSG-consolidation work.

- net: extract the shared packet-observer plumbing (PacketObserver.h) — the
  intrusive subscriber list, Subscribe(), and the read-opcode / reset-cursor /
  fan-out / restore loop — so Net::PacketDispatch (SMSG, u16) and
  Net::SendObserver (CMSG, u32) each reduce to a one-line hook thunk over
  FanOutByOpcode<OpcodeT>. Drops the dead per-namespace Callback aliases
  rather than keeping them as compat shims.

- Game::Lua: promote PushGlobalFunction / CallGlobal / CallGlobalString into
  the shared Lua helpers (a pattern several modules open-code); Frame
  attributes use them instead of private copies.

- frame/Attributes: resolve unit tokens through Unit::Identity::GuidForToken
  (engine resolver + player fast-path) instead of a duplicate raw-cast wrapper.

- frame/Attributes: wire the chained OnClick for every "type" action attribute
  the click resolver reads (IsTypeAttr: modifier prefixes + type1..type5), not
  just type/type1/type2 — a middle-click or modifier-only binding now installs.

- frame/Attributes: FireAttributeChanged snapshots and restores the caller's
  arg1/arg2 around the fire, so calling SetAttribute from inside a running
  script handler no longer clobbers its globals.
2026-08-03 00:37:36 -05:00
Brues 960b37d7e6 README: trim addon helper list and remove legacy notes
Remove Mixin/CreateFromMixins from the AddOns helper list and streamline the surrounding text. Drop outdated paragraphs describing engine-dependent addon features and the note about the triple-`!!!` folder prefix/load-order. This is a documentation cleanup only; no code or behavior changes.
2026-08-02 01:19:16 -05:00
Brues 0c27d61839 unit: add markN raid-target-marker unit tokens
"mark1".."mark8" (star..skull) now work as unit tokens against the whole
Script_Unit* surface, and fire per-token unit events (UNIT_HEALTH, ...)
with arg1 == "markN" -- the same TokenObserver path focus/nameplateN use.

Resolution: a markN branch in the FUN_TOKEN_TO_GUID hook
(unit/TokenExtensions.cpp) reads the engine's 8-slot marker table
(VAR_RAID_TARGET_GUIDS = 0x00B71368, mark{1..8} = table[N-1]), so every
stock Unit* gains the token for free and "mark1target" composes via the
existing suffix walker.

Events: unit/RaidTarget.cpp runs a WorldTick watcher that diffs the marker
table and attaches/detaches one descriptor observer per marked unit,
deferring registration until the unit is in the object table (a unit can
be marked while out of range and enter later) -- the same range handling
Focus does, x8. One distinct callback per slot fires its fixed "markN"
token. Idle (no markers set) costs 8 compares and no object lookups; a
marker on a non-unit is never observed.

Verified the array shape against the binary (reverse lookup FUN_004bb190
walks 8 uint64 slots) and against nampower's CGRaidInfo_m_raidtargets.
Docs added under Unit tokens (markN); README token table updated.
2026-08-01 23:55:44 -05:00
Brues f02f576e70 addon: hide + force-enable embedded !!!ClassicAPI so it can't be disabled
The bundled library provides FrameXML-compat fixes (e.g. the tooltip
mouseover guard) that the DLL and other addons rely on; letting a user
uncheck it at character-select would silently break them.

FinalizeEmbeddedEntry now sets entry+0x29 (filter-out) to hide it from
the AddOns list -- the flat-display builder FUN_0051da70 copies only
+0x29==0 entries into GetNumAddOns/GetAddOnInfo -- and entry+0x2b
(DefaultState) enabled. A co-hook on the per-character enable resolver
FUN_ADDON_ENABLE_RESOLVE (0x0051e470) force-returns "enabled" for
!!!ClassicAPI, defeating any stale WTF disable-override that hiding
alone would otherwise leave stuck off.

Hiding only affects the index-based display array; the addon hash table
keeps the entry, so ## Dependencies: !!!ClassicAPI, IsAddOnLoaded, and
GetAddOnInfo-by-name all still resolve. README updated to match.
2026-08-01 22:53:26 -05:00
Brues 0bd85dd4f3 tooltip: guard mouseover-clear recolor, fix white name flash (#12)
The DLL now fires UPDATE_MOUSEOVER_UNIT on mouseover loss (retail
parity). The stock FrameXML GameTooltip OnEvent recolors the name
unconditionally via GameTooltip_UnitColor("mouseover"), which returns
white when no mouseover exists -- so the loss fire (and the transient
clear when clicking a unit) flashed NPC and PvP-flagged-player names
white during the tooltip fade.

Wrap the stock OnEvent in Util/GameTooltip.lua: swallow the event when
UnitExists("mouseover") is false, otherwise delegate to the original
untouched. The name keeps its color through the loss window and
recolors normally when a mouseover resolves again.
2026-08-01 22:53:15 -05:00
brues-code 29e3dab24a UNIT_SPELLCAST_* event family + GUID unit tokens (#11)
* spell: backport UNIT_SPELLCAST_* events for the local player

Adds the TBC+ cast/channel events (START, STOP, DELAYED, SUCCEEDED,
INTERRUPTED, FAILED, SENT, CHANNEL_START, CHANNEL_UPDATE, CHANNEL_STOP)
for the player, so cast-bar / rotation addons written against the modern
signature work on 1.12. Each carries (unit, castGUID, spellID, spellName,
rank) -- SENT inserts `target` at arg2 -- with a synthesized modern-shape
castGUID (Cast-3-0-0-0-<spellID>-<castUID>) shared across all of a cast's
events so START pairs with STOP. arg1 is always "player" (player-only phase).

The events are derived, not independently tracked: Spell::Cast already
hooks every cast/channel path for UnitCastingInfo/UnitChannelInfo, so
Spell::CastEvents reuses that state.
  - START/STOP/DELAYED/CHANNEL_START/STOP: polled from Cast's OnWorldTick
    against the previous snapshot.
  - SUCCEEDED: fired from the SMSG_SPELL_GO hook (covers instants too).
    Deferred for channels so it lands after CHANNEL_START (modern order).
  - INTERRUPTED/FAILED: split by result code in a Spell_C_SpellFailed
    co-hook -- a started cast that aborts (kick/move/LoS) fires INTERRUPTED
    (repeated per retry, reusing the cast guid); a pre-cast rejection fires
    FAILED.
  - SENT: minted from the CMSG_CAST_SPELL send, threading its castGUID
    forward so all of a cast's events share one guid.
  - CHANNEL_UPDATE: from a new MSG_CHANNEL_UPDATE co-hook, which also
    re-anchors g_channel.endMs to the server's remaining time so channel
    pushback (which shortens vanilla channels) shows in UnitChannelInfo.

Every fire is gated on Event::Custom::HasListeners (new), so the system
costs one pointer-compare per transition when no addon registers.

Supporting changes:
  - Net::SendObserver: shared co-hook on the NetClient send funnel with an
    AutoSubscribe list, so CastEvents (SENT) and ComboDuration (combo-point
    capture) both watch outgoing packets without owning the hook. Extracted
    from ComboDuration's private hook.
  - Cast.cpp: player channel now self-expires at its computed endMs in the
    poll (was cleared only by the ~1s-lagged +0x228 field, so CHANNEL_STOP
    trailed the real end by ~1s); wrap-safe delta compare so a long-uptime
    ms tick past 2^31 can't misfire it.

Player-only; remote-unit fan-out, FAILED_QUIET, and empowered casts are
not implemented.

* spell: extend UNIT_SPELLCAST_* to non-player units (phase 2)

Fires the six observable cast/channel events -- START, STOP,
CHANNEL_START, CHANNEL_STOP, SUCCEEDED, INTERRUPTED -- for other units,
not just the player. Each is fanned out once per unit token currently
mapping to the caster (target / focus / nameplateN / party / raid / pet /
mouseover), so a target frame, a party frame, and a nameplate cast bar
all get their own event with a shared castGUID -- matching retail.

Token fan-out reuses the engine's own GUID->token reverse map
(FUN_00515c50, nampower's unfilled GetNamesFromGUID) for native tokens,
plus focus/nameplate which the engine can't see, via
Unit::Identity::TokensForGUID. SuperWoW's raw-GUID token ("0x...") is
filtered out so only standard tokens fan out.

Remote events are derived from Spell::Cast's existing packet hooks:
  - START / CHANNEL_START from HandleSpellStart (SMSG_SPELL_START)
  - SUCCEEDED from the SPELL_GO hook (Aura::Source)
  - STOP / CHANNEL_STOP at the computed end, or on abort
  - INTERRUPTED (casts only) from HandleCastAborted (ClearCastingSpell /
    failure packets)
A per-caster state machine (PollRemote, from OnWorldTick) fires them in
modern order; a channel's SPELL_GO cast->channel ClearCastingSpell is
filtered so it doesn't self-interrupt at its own start.

Not fired for remotes (data is caster-only / client-local): SENT,
DELAYED, FAILED, CHANNEL_UPDATE.

Also in this change:
  - castGUID follows type rule from https://warcraft.wiki.gg/wiki/GUID#Cast : real casts are Type 3 with a
    time-based castUID (low 23 bits = UNIX second, high bits = per-second
    counter, matching retail's structure), threaded across a cast's events
    (player and remote converge on the same value); FAILED is Type 2 with
    a flat incrementing integer.
  - Channels never fire INTERRUPTED (player or remote) -- retail emits
    only CHANNEL_STOP whether a channel completes or is cut short.

arg1 is the caster's unit token ("player" or another token); the
spellName / rank tail extensions are unchanged.

* spell: return the castGUID as UnitCastingInfo's castID

UnitCastingInfo / CastingInfo now return the cast's castGUID as castID
(return 7) instead of nil -- the same string the UNIT_SPELLCAST_* events
carry, so an addon can correlate the polled info with the events. It's
pulled from Spell::CastEvents (the single source of the castUID) via a new
CurrentCastGuid accessor, and works for the player and remote units. The
timing stays sourced from Spell::Cast -- only the castGUID crosses over,
so there's no duplication of cast state.

UnitChannelInfo is left retail-exact (no castID; channels don't carry
one), even though our channel events do include the shared castGUID.

Also corrects the spell-cast-GUID spec attribution in comments/docs to
warcraft.wiki.gg/wiki/GUID#Cast (it was wrongly credited to Wowhead).

* spell: add UNIT_SPELLCAST_RETICLE_TARGET / _CLEAR events

Backports the ground-target reticle events for the player:
RETICLE_TARGET when an AoE placement reticle comes up (Blizzard, Flare,
Rain of Fire, ...), RETICLE_CLEAR when it's cancelled. Args are
(unit, "", spellID, spellName, rank); arg1 is always "player".

Driven by polling the engine's targeting-flag global (0x00CECAC0 -- the
predicate behind SpellIsTargeting) from OnWorldTick: 0->nonzero fires
RETICLE_TARGET with the pending spellID (0x00CEAC58, written by
Spell_C_CastSpell); nonzero->0 fires RETICLE_CLEAR. CLEAR is suppressed
on placement (a CMSG_CAST_SPELL for the reticle spell went out, seen via
the shared send observer), so it fires only on a genuine cancel --
matching retail, which emits no CLEAR when the spell is placed/cast.

The castGUID slot (arg2) is "" rather than retail's nil: there's no cast
to identify yet, and the engine's event dispatcher can't emit a nil
mid-argument-list (a NULL %s corrupts the args after it -- the nil trick
only survives as the last arg). unit (arg1) and spellID (arg3) are exact.

* spell: fire UNIT_SPELLCAST_FAILED_QUIET for the quiet result whitelist

Vanilla's Spell_C_SpellFailed dropped SPELL_FAILED_DONT_REPORT silently.
Modern surfaces suppressed (no-error-text) failures as
UNIT_SPELLCAST_FAILED_QUIET rather than FAILED.

Verified against the 3.3.5 client's unit-spellcast dispatch (FUN_007fecc0),
which selects the QUIET event for a fixed 3-code whitelist, mapped to 1.12's
SpellCastResult enum (FUN_006e23e0):
  CHARMED (0x14) . DONT_REPORT (0x17) . SPELL_IN_PROGRESS (0x61)

SPELL_IN_PROGRESS (casting while already casting / a nampower spell-queue
rejection) is the common case that previously mis-fired as a loud FAILED.

* unit: accept raw GUID literals as unit tokens

Fold a "0x<hex>" branch into the existing FUN_TOKEN_TO_GUID hook so every
Unit* function (UnitName, UnitHealth, UnitClass, UnitExists, ...) accepts a
64-bit GUID literal in place of a token. The parsed GUID goes straight to
the engine's own object-manager lookup (the path "player" takes), so an
unloaded/out-of-range GUID resolves to nil like any absent unit, no error.
Reuses the existing suffix walker, so "0x...target" composes.

Gated on SuperWoW's absence (GetModuleHandleA("SuperWoWhook.dll"), cached):
SuperWoW already provides GUID input via its own resolver hook, so when it
is loaded we defer to avoid two layers parsing the same string. Behaves
identically either way. Input direction only.
2026-07-31 21:38:44 -05:00
Brues 555ea02447 loot: add C_Loot.LootAllCorpses to auto-loot nearby corpses
C_Loot.LootAllCorpses([max]) loots every nearby lootable corpse in
sequence -- coin (CMSG_LOOT_MONEY) plus every item slot (CMSG_LOOT_ITEM)
from each window before releasing and advancing. Optional max caps the
corpse count.

Shares Loot::Scan's existing corpse-walk state machine and its single
FUN_LOOT_CONTROLLER hook -- MinHook allows one hook per target, so this
can't be a separate module. ScanNearbyLoot scrapes each window and
releases; LootAllCorpses does the same walk but actually loots it first.
The walk stays silent (LOOT_OPENED/LOOT_CLOSED suppressed, so LootFrame
never flickers) while the item-received / money chat + inventory events
fire normally.

Packet-based and target-clean, matching the rest of the C_Loot suite:
no right-click, no target change, no auto-walk toward out-of-range
corpses. Money goes through FUN_005ea8c0 (CMSG_LOOT_MONEY) with the SAME
player pointer passed to FUN_CMSG_LOOT_UNIT -- whose send wrote this
window's target GUID to the player's +0x1D28 guard slot, so the money
send's internal guard passes. Item sends bypass the client BoP/unique
confirm dialog (the server still enforces real loot permissions).

Reimplemented in spirit from WeirdUtils's LootAllCorpses (public domain)
on our own packet loot primitives + object-scan helpers, rather than its
right-click-autoloot approach. Wires the existing AOELOOT keybinding to
it (was ScanNearbyLoot).
2026-07-31 14:51:24 -05:00
Brues e3f5318747 bag: gate BAG_UPDATE_DELAYED on VAR_IN_WORLD, drop the PEW latch
f91ffd3 gated the drain on a one-way PLAYER_ENTERING_WORLD latch
(Event::EnteringWorld::HasEnteredWorld), added on the belief that no
pollable in-world flag existed. cd674aa found the real one:
VAR_IN_WORLD (0x00B4B424), 1 while in world and 0 during any loading
screen.

The one-way latch stays true forever after the first login, so if the
object burst re-populates bag descriptors during a LATER zone/instance
loading screen it would fire BAG_UPDATE_DELAYED mid-load again -- the
very thing the gate was meant to prevent, recurring on every zone.
VAR_IN_WORLD clears on every transition, so polling it re-suppresses
during later loads and emits one DELAYED once actually in-world
(matching retail's one-per-load).

Switch the gate to VAR_IN_WORLD and remove the now-dead HasEnteredWorld
latch/accessor and its header; EnteringWorld keeps only its PEW-payload
role.
2026-07-31 13:04:15 -05:00
Brues cd674aa115 hearth: gate HEARTHSTONE_BOUND on in-world flag, not location diff
Turtle's server re-sends SMSG_BINDPOINTUPDATE on every map/zone
transition with the unchanged bind location, behind a loading screen.
The valid-flag gate only suppresses the initial post-login sync, so
every map change fired HEARTHSTONE_BOUND.

A player can't bind mid-load, so gate on the engine's "world is live"
flag instead: VAR_IN_WORLD (0x00B4B424), set to 1 by the enter-world
init FUN_004908C0 and back to 0 by the world-teardown FUN_00490A80 that
runs at the start of every transition (verified via the enter/leave
pair in Ghidra). The resync arrives with the flag 0 (suppressed); a
real innkeeper bind always arrives with it 1 (fires) -- including a
rebind at the same inn, unlike a location diff would.

Add VAR_IN_WORLD to Offsets.h (the real pollable in-world boolean;
0x00B4E37C, once wrongly labeled this, is only instance grace-period
state). Update the bind-handler offset comment and docs/API.md.
2026-07-31 12:58:32 -05:00
Brues f91ffd3189 bag: gate BAG_UPDATE_DELAYED on PLAYER_ENTERING_WORLD, not VAR_IN_WORLD
The in-world gate added in 5d785ea polled 0x00B4E37C, believed to be an
"in world" flag. It isn't: verified in the binary it's instance
grace-period state, written from a packet handler (FUN_0049e6c0) and
read only by the "recently left an instance" 90-second window check
(FUN_00495c90). It never reliably goes non-zero from being in the world,
so OnWorldTick's early-return held g_pending forever and
BAG_UPDATE_DELAYED stopped firing entirely. There is no clean pollable
in-world boolean at these offsets (0x00B4E378 is the map ID; map 0 is
valid).

Gate on the correct signal instead: PLAYER_ENTERING_WORLD, already owned
by Event::EnteringWorld. Expose a one-way HasEnteredWorld() latch flipped
the first time PEW fires (loading screen done, world live) and stays true
across /reload; UpdateDelayed holds g_pending until then, then emits one
DELAYED covering the settled login inventory. Correct the mislabeled
0x00B4E37C note in Offsets.h so the trap isn't repeated.
2026-07-30 20:13:05 -05:00
Brues 8361ae01eb equipment: unregister equip observers before re-registering on reload
PLAYER_EQUIPMENT_CHANGED fired an extra time per /reload. The event's
descriptor-field observers are registered in ObserverSetup_h, a co-hook
of the engine's per-enter-world inventory-observer setup. /reload
re-runs that setup but does NOT destroy the CGPlayer object, so the
prior session's observer nodes are still attached; the engine registrar
always appends (no dedup by callback), stacking a second observer per
equipment field each reload. Logout/login recreates the player object,
old nodes die with it, so the count resets to one -- matching the
observed "doubles only on /reload" symptom.

Unregister each equipment-field observer before re-registering it. On
/reload this drops the stale node (same object/guid/callback key) so we
keep exactly one per slot; on logout/login the object is already gone so
the unregister no-ops. Mirrors the objects-survive-/reload guard
Unit::TokenObserver uses for nameplates.
2026-07-30 20:02:59 -05:00
Brues 5d785ea0d3 bag: hold BAG_UPDATE_DELAYED until in-world
The per-frame world tick (FUN_0066FD50) runs behind the initial-login
loading screen, and the engine populates every bag slot during the
initial object burst -- setting g_pending while still loading. That made
OnWorldTick fire BAG_UPDATE_DELAYED repeatedly mid-load, so addons
rescanned bags for inventory that wasn't a real change yet.

Gate the drain on the engine's in-world flag (new VAR_IN_WORLD =
0x00B4E37C): hold g_pending -- without clearing -- until the flag is set.
The first in-world frame then emits a single DELAYED covering the settled
login inventory (matching retail's one BAG_UPDATE_DELAYED at login), and
a pending update suppressed during a later zone transition fires on
return. The three bag hooks are unchanged (still just set the flag).
2026-07-30 11:33:55 -05:00
Brues e84673dde5 item: clamp bank-bag slot count in NewItems baseline scan
AppendNonBagOwned read each bank-bag container's slot count straight
from the invMgr's first dword with no upper bound. A container resolved
while only partially initialized (plausible right at login) can yield a
garbage value there, driving AppendGuidArray into a multi-billion-
iteration loop -- a multi-second freeze. Clamp to kMaxContainerSlots
(64), far above any real vanilla/Turtle bag, so it's invisible to real
inventories and only trips on a bogus count.
2026-07-30 11:33:45 -05:00
Brues a2c5db7b76 time: add GetTimeCached() frame-stable timestamp
Backports retail 4.x's frame-cached GetTime() behavior under a distinct
name, leaving vanilla GetTime() live/per-call. 1.12's Script_GetTime
recomputes the OS tick on every call, so same-frame calls can differ;
GetTimeCached() samples once per frame (via the shared Tick::WorldTick
hook) and returns that until the next frame, on the same epoch as
GetTime() so the two are directly comparable. Falls back to a live
sample before the first world tick so it never returns 0.

Deliberately NOT a perf feature and documented as such: the 1.12 tick
source is cheap (GetTickCount shared-page read or rdtsc) and both
functions pay the same dominant Lua->C dispatch, so caching saves
nothing measurable. The only benefit is frame-stable semantics; the
real hot-loop fix is caching GetTime() in a Lua local, which no C
function can do for the caller. New global chosen over modifying
GetTime() to avoid changing a core vanilla function's behavior.
2026-07-30 03:12:07 -05:00
Brues 46597f6587 unit: fire UPDATE_MOUSEOVER_UNIT on mouseover loss
Vanilla fires UPDATE_MOUSEOVER_UNIT only when a mouseover unit is gained;
moving the cursor off a unit clears the mouseover and signals nothing.
Retail fires for both gain and loss, so addons watching
UnitExists("mouseover") can react when it goes false. This restores the
loss fire.

Co-hooks the engine's mouseover set/clear chokepoint (FUN_00492890) --
the ONLY writer of the mouseover GUID globals, so every gain/loss/change
flows through it. Resolves whether the mouseover is a unit before and
after the original and fires the event on the unit->non-unit transition.

Gating on unit TYPE (not just "GUID present -> absent") is load-bearing:
the same GUID slot also holds gameobjects and items, which never fire a
gain, so a naive present->absent test spuriously fired when moving off a
herb node or chest (reported in testing). The unit|player object-mask
resolve fixes that; the !hasUnit half prevents a double-fire on any
->unit transition the engine already covered inline.

Change-gated target (per-frame would spam the gain event while
hovering), so it's a cool hook. Documented in API.md (loss-fire fix
subsection + TOC) and Events.md notes.
2026-07-30 00:45:00 -05:00
Brues 4e1c1863e9 debugtools: add Refresh button to TableInspector
Re-reads the current level's live table in place. The nav stack holds
the real table reference (never a copy), so refresh reflects mutations
made since the view was built -- keys added/removed, values changed --
without leaving the current view. Scroll position is preserved (Back and
drill reset to top; refresh deliberately doesn't) and Update re-clamps
the offset if the entry count shrank. No-op if the held reference is no
longer a table.

Adds TableInspector_Refresh() and a Refresh button in the header between
Back and the breadcrumb (breadcrumb shifted right and narrowed to fit).
2026-07-29 23:58:01 -05:00
Brues a4c57614bc debugtool: Use MouseIsOver global for fallback
WIthout ClassicAPI this will fallback to the 1.12.1 implementention of MouseIsOver
2026-07-29 13:14:13 -05:00
Brues e1a9d9b5c4 docs: document IsIndoors / IsOutdoors
Add the two globals to the State section of docs/API.md (with TOC
entries) and the README State row. Notes the 1/nil return contract
(retail + SuperWoW 2.2 parity) and that the state is a live WMO
geometry query, not zone/area based.
2026-07-29 11:04:45 -05:00
Brues cd280ac307 state: add IsIndoors / IsOutdoors globals
Backport the modern `IsIndoors()` / `IsOutdoors()` no-arg globals to 1.12.
Both return 1 when the condition holds, nil otherwise (the historical
retail contract, also what SuperWoW 2.2 uses), so `if IsOutdoors()` and
`IsOutdoors() == 1` both work. Recomputed live from the engine's WMO
geometry query, so they flip as the player crosses an interior threshold
rather than tracking zone/area; nil pre-world.

The signal is a live WMO query, not a cached flag. Vanilla ships no Lua
binding for it, and the static anchors all dead-ended (the WMO runtime
flag bits differ from 3.3.5; ZONE_CHANGED_INDOORS is never fired with a
literal event ID; WMOAreaTable is only the area-naming path). SuperWoW
2.2 exposes `IsIndoors`, so decoding its handler gave the exact recipe:
resolve the local player object, then call FUN_00612cc0(unit) -- a thunk
that reads the unit world/collision context at +0xE0 and tail-jumps to
the WMO query FUN_006706f0 (nonzero = outdoors, fully null-safe). Same
shape as the 3.3.5 client's IsIndoors (unit+0xB8), so cross-confirmed.

Added Offsets::FUN_UNIT_IS_OUTDOORS with the full trail; the two
functions live in Unit::State next to IsMounted / IsSwimming and share
Unit::Identity::PlayerObject().
2026-07-29 11:01:59 -05:00
Brues 564495248c item: apply random suffix in by-string GetItemNameByID / GetItemInfo
C_Item.GetItemNameByID and C_Item.GetItemInfo resolved an item link down
to just the itemID and dropped the random suffix (3rd `item:` field), so
"item:12022:0:769:0" returned "Iridium Chain" instead of "Iridium Chain of
the Owl" (and GetItemInfo's rebuilt link lost the 769). The global
GetItemInfo applies it; now these match.

Item::Arg::Resolve parses the suffix alongside the itemID. New
Item::Link::NameFromIDSuffix builds the suffix-decorated name from
(itemID, suffixID) without a live CGItem, via the engine's inner name
builder (FUN_005d8b00 = the formatter behind FUN_ITEM_BUILD_INSTANCE_NAME,
which reads the localized "of the X" suffix from ItemRandomProperties).
Item::Link::BasicFromIDSuffix preserves the suffix in the rebuilt link
(payload + bracketed name); BasicFromItemID is now a suffix=0 wrapper.

GetItemNameByID and GetItemInfo route through these; numeric/suffixless
input still yields the base name. Numeric item stats are unaffected (the
suffix only decorates the name/link). Enchant/unique fields are normalized
to 0 in the rebuilt link (suffix is what affects the name).

Verified in-game: item:12022:0:769:0 -> "Iridium Chain of the Owl" (name +
link); bare 12022 / item:12022:0:0:0 -> "Iridium Chain".
2026-07-28 16:33:50 -05:00
Brues 1f3f3cb9f6 aura: infer server-side DoT-duration changes from the triggering cast
C_UnitAuras expirationTime for a debuff on another unit is derived from
SMSG_SPELL_GO at cast time; the vanilla server never retransmits a LATER
server-side duration change on a non-self unit (verified in the server
source: SetAuraDuration/RefreshHolder, and UpdateAuraDuration is self-
scoped -- on a mob no packet is built at all). So a refresh/consume goes
stale in our cache. We can't hear the change, but we DO see the triggering
cast, so mirror the server's edit off that.

Aura::Source gains a rule engine applied in SpellGo_h (before the aura
gate -- triggers apply no aura themselves): a trigger matched by exact
spellID OR by SpellFamilyName + school index, an affected aura matched by
family + family-flag overlap (+ optional icon, rank-proof like the server
scripts), and an op (refresh/reduce/set/remove). Proc-applied affected
auras enter the cache unattributed (casterGuid 0); the rule accepts those
and attributes them to the trigger caster (also gives them a sourceUnit).

Lua: C_UnitAuras.RegisterAuraDurationModifier (exact-ID trigger) and
RegisterAuraDurationModifierByTrigger (family+school trigger), so the
server-specific ruleset lives in the addon, not the DLL.

Default Turtle ruleset (AuraDurationModifiers.lua, gated on
TURTLE_WOW_VERSION; IDs/flags DBC-verified):
  Conflagrate  -> reduce Immolate 3s
  Molten Blast -> refresh Flame Shock
  Shadow Weaving (5/5 talent 15334) -> priest shadow-school casts refresh
    Shadow Vulnerability 15258 (covers the max-stack refresh blind spot;
    Turtle reworked it, so stock DBC proc masks don't apply -- match by
    school). Best-effort: DoT-tick procs emit no cast packet.
Carnage's roll-gated Rip/Rake refresh is deliberately excluded (the client
can't know the server roll).

Verified in-game (debug trace): Conflagrate/Molten Blast, and Mind Blast /
SW:P / Mind Flay all refresh 15258 with advancing expiration + sourceUnit.
2026-07-28 16:14:45 -05:00
Brues 7ae9b83ad7 spell: CastAtUnit casts unit-target spells directly at the unit
Previously CastAtUnit only handled ground-target spells (placement at the
unit's feet); a non-ground spell fired with no implicit target (fell to
current selection). Now it resolves the unit once to its object, reads
position AND GUID, and dispatches the cast WITH that GUID -- the engine's
FUN_SPELL_CAST_DISPATCH substitutes it exactly where it would the current
selection (verified: passing 0 substitutes VAR_CURRENT_SELECTION_GUID), so
a unit-target/normal spell fires straight at that unit regardless of
current target.

Branch on placement state after dispatch: no placement -> cast went out
(unit-target); ground placement -> commit at the unit's feet (existing);
other placement -> unit not accepted as target, cancel + false.

AtCursor gains an optional targetGuid on DispatchSpellCast[ByName] (0 =
prior behavior, so CastAtCursor is unchanged) and IsPlacementActive().

Verified in-game: ground spells still land at the unit's feet; Frostbolt/
Renew/PW:Fortitude cast on the named unit while another unit stays targeted.
2026-07-27 23:36:03 -05:00
Brues 26e5fdc052 readme: place C_Glue helpers in the right sections
IsFirstLoadThisSession is glue-only -> GlueXML-calls section only.
IsOnGlueScreen is registered on both states -> main in-game table AND the
GlueXML-calls section.
2026-07-27 22:18:52 -05:00
Brues 4281cd8253 glue: add C_Glue.IsFirstLoadThisSession and C_Glue.IsOnGlueScreen
IsFirstLoadThisSession() - glue-only; true only during the first glue
screen since process launch, false after a world->glue logout (login <->
character-select stays within the first session). Backed by a
process-static glue-boot counter incremented in the GlueModuleAutoRegister
callback (fires once per glue boot).

IsOnGlueScreen() - true on a GlueXML screen, false in the world.
Registered on both Lua states; since glue and in-game states are mutually
exclusive the answer is a constant per state (true from glue, false
in-game), so it's callable from either environment with no runtime flag.

Verified in-game: first login true/true, post-world-logout false; in-game
C_Glue.IsOnGlueScreen() false.
2026-07-27 22:12:28 -05:00
Brues 9239756153 frame: add frame:GetEffectiveAlpha()
Own alpha times every ancestor's alpha -- the product WoW composites at
render time. Vanilla has only GetAlpha (a frame's own alpha); this walks
self -> parent -> ... via the engine's own GetAlpha/GetParent, so it
reflects the engine exactly, including 8-bit alpha quantization
(SetAlpha(0.5) -> 127/255). Frame-scoped, matching GetAlpha's registry.

Verified in-game: matches an equivalent Lua GetAlpha/GetParent walk, and
a two-level 0.5/0.5 chain returns (127/255)^2 = 0.248043 exactly.
2026-07-27 21:40:16 -05:00
Brues f13aa1943d unit: add UnitPosition(unit)
Backport the modern UnitPosition -> posY, posX, posZ, instanceID. Reads
any visible unit's world position through the shared Unit::Position helper
(CGObject::GetPosition vtable slot 5 -- same path UnitDistanceSquared
uses), so no group/taint restriction like retail: works for target,
mouseover, nameplates, in-range party/raid. nil when the unit has no
known position.

Retail return order (posY=world Y/west, posX=world X/north, posZ=height);
instanceID is the current Map.dbc id. Verified in-game: squared delta of
two UnitPosition reads matches UnitDistanceSquared exactly.

Note: SuperWoW also defines a global UnitPosition with a different shape;
last registrant wins if both load. Documented in docs/API.md.
2026-07-27 21:19:58 -05:00
Brues 438ad97f8f readme: list IsMouseOver/GetRect/IsDragging in the Frame row 2026-07-27 20:59:20 -05:00
Brues 7f4b20c6ec frame: add region:GetRect and region:IsDragging
Two more Region-base methods backported from 3.3.5, both on the Region
registry so they resolve on every region type.

GetRect() -> left, bottom, width, height, composed from the engine's own
GetLeft/GetBottom/GetWidth/GetHeight (all UI-scale conversion is engine
code). Returns nothing for an unpositioned region, matching retail.

IsDragging() -> true while the region is the frame currently being
moved/sized. Reads the engine's single global drag target
(*(VAR_UI_CONTEXT_PTR) + 0xCFC); StopMovingOrSizing (0x00776990) gates its
own clear on the identical `context+0xCFC == self` predicate. Non-frame
regions never match the stored frame, so they report false.

Verified in-game: GetRect on UIParent/Minimap; IsDragging toggles with a
live frame drag.
2026-07-27 20:56:04 -05:00
Brues 3f11f942bd addon: use native region:IsMouseOver
Add a MouseIsOver(region, top, bottom, left, right) global that forwards
to the native Region:IsMouseOver method (mirrors modern FrameXML's
forwarding; nil offsets default to 0 in the C method).

Drop DebugTools' hand-rolled DebugTools_IsMouseOver helper in favor of
the native method. This also fixes _CollectFramesUnderMouse's showHidden
path: the old helper baked a visibility check into the geometric test, so
a hidden-but-hovered frame could never surface; the native method is
purely geometric and visibility is already gated separately at the call
site.
2026-07-27 20:38:10 -05:00
Brues 9622ea7742 frame: add region:IsMouseOver([top, bottom, left, right])
Native Region method (all region types) for cursor-in-rect testing with
optional per-edge offsets. Mirrors the engine's own math: delegates to
the Region-registry rect getters (GetLeft/Right/Top/Bottom) and
GetCursorPosition, dividing the cursor by the region's effective scale
read from obj+0x7C -- the same field GetLeft/GetEffectiveScale read
internally, so it works on textures/fontstrings where GetEffectiveScale
(Frame-only) would typecheck-fail. Returns false for an unpositioned
region. Offset semantics match modern FrameXML's MouseIsOver forwarding.
2026-07-27 20:30:37 -05:00
Brues 659dd7e159 newitems: fix false "new" flags from transient bag-scan drops
A bag update in progress transiently drops items from the pure-C++ bag
read -- sometimes the entire backpack (all 16 slots) for a frame or two.
The old logic rebuilt the seen-set from each scan, so a momentarily-
missing item fell out of the set and was re-flagged "new" the instant it
reappeared (e.g. dragging/swapping an item into the backpack lit it up).

Replace the rebuilt-each-scan set with a persistent seen-set whose entries
carry a consecutive-absent-scan counter (SeenReconcile): present items
reset it, absent ones age by one, and only items absent kMaxMissStreak
scans running are evicted. Counting scans rather than wall-clock means a
pause with no bag activity never ages an owned item, and any reappearance
resets the streak -- so transient drops are absorbed while the set stays
bounded to ~currently-owned items (genuinely-removed items age out).
Verified in-game: backpack repeatedly vanishing from the scan, seen-set
holds steady, zero false flags.
2026-07-27 20:13:49 -05:00
Brues 1ae102b554 add string.split to workaround certain addons replacing strsplit 2026-07-27 15:41:23 -05:00
Brues a5b6cf367d aura: cache fallback for out-of-range group auras (server delta gap)
The server resends out-of-range party/raid stats as deltas only, so a
member seen in range and then moved away again leaves an empty party-
stats aura array (it's cleared when they become visible and never re-
sent), and C_UnitAuras showed nothing until a full roster resync (relog).
Their auras still sit in the Aura::Source cache from when we observed them
in range, so the four group enumerate paths now fall back to the cache
when the group array is empty -- gated by GroupArrayHasVisibleAura, the
same "container non-empty => authoritative" rule the descriptor path uses
(DescriptorHasVisibleAura). A populated array is trusted as-is (no
phantoms); only the empty-array gap consults the cache, deduped and
visibility/playerOnly-filtered.
2026-07-26 18:19:47 -05:00
Brues b496568670 Add C_Spell.GetSpellEffectMechanics(spellID)
Returns the spell's three per-effect SpellMechanic ids (Spell.dbc
EffectMechanic[3], +0x13C) as a 1-based array, or nil for an invalid spell.
Complements GetSpellMechanicByID, which reads only the spell-level Mechanic
field (+0x14): vanilla stores some mechanics on an effect instead -- e.g.
Rake's bleed is effect-level (spell-level 0, EffectMechanic[2]=15), so
GetSpellMechanicByID misses it while this returns {0,15,0}.

Add OFF_SPELL_RECORD_EFFECT_MECHANIC offset, API.md section + TOC entry, and
README index entry.
2026-07-26 15:42:25 -05:00
Brues a37c590a72 aura: clamp elapsed player-buff expiration to 0 (permanent auras)
Permanent auras (paladin auras, passives, racials) carry an infinite
SpellDuration (base -1); the server stores their fixed cast-time in the
player buff-expiration table, so it reads as already-elapsed and drifts
into the past. We were reporting that stale timestamp, giving a permanent
aura like Devotion Aura a negative time-left. Mirror the engine's own
GetPlayerBuffTimeLeft (Script at 0x004e4930 -> FUN_004e4450), which reads
the same table and returns 0 once now >= expiration. Signed compare
absorbs the GetTickCount wrap, matching the engine.
2026-07-26 12:16:48 -05:00
Brues 60479677c1 aura: best-effort duration guess for out-of-range group/raid auras
An out-of-range party/raid member has no CGUnit and never yields
SMSG_SPELL_GO, so the caster/duration cache never learned their auras'
timing and expirationTime stayed 0. But SMSG_PARTY_MEMBER_STATS carries
their aura spell IDs and the server sends it on change
(SendUpdateToOutOfRangeGroupMembers flushes the moment an aura add/remove
dirties the group mask), so a spell ID that newly appears in the group
array did so ~one tick + latency after the real application.

Aura::Source::ObserveGroupAuras (called from the group enumerate paths in
Aura::Data) keeps a per-member snapshot of the last-seen spell-ID set and,
on a genuine absent->present transition, stamps now + base duration into
the same cache PushEnriched already reads. Covers party and raid alike
(AuraArray reads the raid slot too; snapshot table sized for a 40-man).
Base duration only (no remote caster mods) and no caster recorded
(sourceUnit/GUID stay nil). Auras already present at first sight have
unknown age and are not stamped; snapshots reset on map change and after
30s unpolled. The Store guard keeps any real SpellGo timing, so this
never downgrades better data.
2026-07-26 03:05:54 -05:00
Brues b5038dc3fd util: add VectorLib (Vector2D / Vector3D / Vector4D)
Verbatim backport of retail's Blizzard_SharedXML vector mixins
(CreateVector2D/3D/4D + Vector*DMixin + the free Vector*_ helpers).
Pure math on CreateFromMixins and Lua 5.0 math.*, so no adaptation was
needed. Registered the three files in the TOC (we list .lua directly
rather than via retail's VectorLib.xml include).
2026-07-26 03:00:03 -05:00
Brues 0bbf802316 Use BASE_MOVEMENT_SPEED for speed calculation
Replace the magic divisor 7 with the BASE_MOVEMENT_SPEED constant
2026-07-26 02:53:34 -05:00
Brues 0fcaa2e064 util: add RectangleMixin / CreateRectangle
Backport of retail's Rectangle helper (sides, stretch/move/adjust,
contains/intersects, center, width/height accessors), built on
CreateFromMixins. Registered in the TOC.
2026-07-26 02:49:02 -05:00
Brues 6724ddd2bd mathutil: CreateCounter takes an optional step
Retail added a second `step` parameter (default 1); mirror it. Backward
compatible -- existing no-step callers are unchanged.
2026-07-26 02:46:58 -05:00
Brues 50d001a71f mathutil: add CreateAccumulator / AccumulatorMixin
Backport of retail's AccumulatorMixin (Init/Add/Subtract/Count/Reset)
and the CreateAccumulator factory, built on CreateAndInitFromMixin.
2026-07-26 02:42:40 -05:00
Brues 3aad341a91 table: add table.count(tbl)
Backport of retail's table.count (added 11.2.5): returns
(numTableNodes, numArrayNodes, maxArrayIndex) -- total entries, entries
with an integer key in [1..numTableNodes], and the largest positive
integral key (0 if none). Pure lua_next walk, no Lua-internal layout
dependency; keys read via ToNumber only (ToString on a numeric key
would corrupt traversal). All five cases verified to match retail,
including negative-key handling ({[-3]=x} -> 1, 0, 0).
2026-07-26 02:24:19 -05:00
Brues 3141acf547 baselib: provide Mixin and CreateFromMixins as C natives
Modern WoW implements these FrameXML table primitives as engine C
functions (TableUtil); do the same so they exist whenever the DLL is
injected -- even if the !!!ClassicAPI addon is disabled. Behaviour
matches the Lua form exactly: shallow key/value copy from each table
arg, non-table args skipped, returns the object / new table. Registered
on both the in-game and glue states.

Slimmed the addon Mixin.lua to just CreateAndInitFromMixin (calls a Lua
:Init, so it stays Lua), mirroring retail's Mixin.lua. The taint-based
SecureMixin family is omitted -- vanilla 1.12 has no execution taint.
2026-07-26 02:12:22 -05:00
Brues 05e7bda5da color: add C_ColorUtil and wire the addon Color files to it
New C_ColorUtil native module (src/color/Util.cpp) with the modern color
helpers, all pure math/string: ConvertRGBToHSV, ConvertHSVToRGB,
ConvertHSVToHSL, ConvertHSLToHSV, ConvertHSLToRGB, GenerateTextColorCode,
WrapTextInColor, WrapTextInColorCode. Conventions verified in-game against
a retail-family client: hue in degrees [0,360), -1 achromatic sentinel,
bare AARRGGBB from GenerateTextColorCode, |c..|r wrapping.

Ported the addon Color.lua / ColorUtil.lua to match retail now that the
natives exist: ColorMixin:GetHSL/GenerateHexColor/WrapText* delegate to
C_ColorUtil (GetHSL now returns degrees), SetRGBA defaults alpha to 1,
byte getters use Round; added COLOR_FORMAT_* constants and
CreateColorFromBestRGBHexString. Kept 1.12-Lua-5.0-safe syntax and the
ClassicAPI-only CAPI_ApplyStandardColorGlobals / ITEM_QUALITY_COLORS bits.
2026-07-26 01:57:56 -05:00
Brues c4b48f7f42 spell: add CanDualWield()
New global returning whether the player can equip an off-hand weapon.
The server tracks this as Player::m_canDualWield, flipped on only by
SPELL_EFFECT_DUAL_WIELD (effect 40); exactly one client Spell.dbc row
carries that effect -- 674 "Dual Wield" -- so CanDualWield() is exactly
IsPlayerSpell(674). Factored the known-spell bitmap read into a shared
PlayerKnowsSpell() helper used by both.
2026-07-26 01:30:11 -05:00
Brues 4d97b1c449 clipboard: add CopyToClipboard(text [, removeMarkup])
New Win32-backed global that copies text to the Windows clipboard and
returns the byte length copied. Optional removeMarkup strips WoW UI
escape sequences (color codes, hyperlinks keeping visible text,
textures, |n, || -> |) so the clipboard gets plain text. UTF-8 in,
CF_UNICODETEXT out. Registered on both the in-game and glue states.

Docs: folded the lone Screen section and this into a single System
section rather than adding a one-function Clipboard section.
2026-07-26 01:18:42 -05:00
Brues e447c70ca3 aura: recover player-talented DoT duration in the application hooks
A player DoT with a duration talent (e.g. Improved Shadow Word: Pain,
2/2 -> 24s vs 18s base) intermittently showed the base duration. The
displayed value is the Aura::Source cache entry's durationMs, which is
computed two ways: SpellGo knows caster == player so it applies the
player's duration mods (skipMod 0 -> 24s), while the OnAuraAdded /
OnAuraStacksChanged application hooks have no caster and take the
unmodified base (skipMod 1 -> 18s).

Normally SpellGo owns the entry and the application hooks can't clobber
it, but the base value wins whenever SpellGo can't land its talented
value on THIS target's entry: an empty SMSG_SPELL_GO hit list files it
under the caster instead (numTargets == 0), or a slot reshuffle
evicts + refills the entry after SpellGo ran. Both are packet-order
dependent, hence the flicker.

Fix: SpellGo (which knows caster == player) records recent player aura
casts by spellId; the application hooks recompute with skipMod 0 and
attribute the caster when the spellId matches a recent player cast.
Robust against both the attribution miss and the refill race, and
leaves other units' auras on the base path (we lack their mod tables).
2026-07-26 00:00:42 -05:00
Brues 72fa36956e tooltip: add OnTooltipSetSpell/Unit/GameObject scripts
Generalize the item-only Tooltip::SetItemEvent into Tooltip::SetEvents,
backing all four object tooltip scripts through one shared fire path
(stack save/restore + recursion guard + Suppressor). One resolver
co-hook recognizes all four OnTooltipSet* names (the per-tooltip cell
now holds a slot per kind), plus one builder co-hook per kind firing its
script after the original build:

- Spell  -> FUN_0052E610 (SetSpell/SetSpellByID/SetTalent/SetShapeshift;
  7 stack args, RET 0x1c)
- Unit   -> FUN_00529fe0 (SetUnit + mouseover; 1 arg, returns an int the
  caller tests -> co-hook forwards it)
- GameObject -> FUN_0052aa20 (GO hover populator; 1 arg)

Each hook's declared stack-arg count matches its callee RET N (verified
from disassembly) so the caller's stack isn't corrupted.

Auras deliberately do NOT fire OnTooltipSetSpell: SetUnitBuff/Debuff/
PlayerBuff funnel through a separate aura-tooltip builder (FUN_0052f880)
that bypasses the spell builder -- matching retail, where unit auras are
a distinct tooltip data type.

Verified in-game: all three new scripts fire (spell hover, unit
mouseover, gameobject mouseover), item still fires, no crash.
2026-07-25 22:57:32 -05:00
Brues 40813a715c talent: GetTalentSpellID takes an optional classID too
Mirror the classID extension just added to GetTalentIDByIndex. classID
is the 4th arg (GetTalentSpellID(tab, idx[, rank[, classID]])); pass rank
as nil to keep its default. A numeric classID resolves the talent
against the Talent.dbc / TalentTab.dbc flat arrays via the shared
ResolveTalentRecordForClass, then reads SpellRank[rank-1] off the record.

One semantic difference from the same-class path: there's no player
currentRank for a class you aren't, so a cross-class query with no
explicit rank defaults to rank 1 (the canonical spellID) rather than
delegating to the engine's GetTalentInfo.

Verified in-game: own-class parity at rank 1 (14524 == 14524), Mage (8)
tab1 talent1 -> Arcane Subtlety (11210 r1, 12592 r2, r9 nil),
default-rank cross-class == rank 1, and bad tab/index/class all nil.
2026-07-25 15:05:34 -05:00
Brues a14ccfacbb talent: GetTalentIDByIndex takes an optional classID
Previously it only read the local player's talent tree (the engine's
runtime per-tab arrays at VAR_TALENT_TAB_INFO_ARRAY, built only for the
player's class). Addons that want another class's talent IDs -- build
tooling, spec previews -- had no way to get them.

Add an optional 3rd arg: nil/omitted keeps the runtime path (player's
class, unchanged); a numeric classID resolves against the Talent.dbc /
TalentTab.dbc flat arrays instead, so any class works.

Ordering matches the player-class path exactly because it replicates the
engine's tree builder FUN_004f2c00: tabs taken from TalentTab.dbc in row
order filtered by classMask (+0x30; mask 0 = all, race not a factor --
FUN_004f2e50 is a plain bitmask test), then talents from Talent.dbc in
row order within each TabID. The runtime arrays are built from that same
walk, so GetTalentIDByIndex(t,i) == GetTalentIDByIndex(t,i,<player class>).

New Offsets: the flat (row-order) DBC array globals the builder uses
(VAR_TALENTTAB_DBC_FLAT_* / VAR_TALENT_DBC_FLAT_*), distinct from the
sparse by-ID index SetTalentByID uses.

Verified in-game: own-class parity (166 == 166), Mage (8) tabs 1/2/3
first talents = 37/1/18, and out-of-range tab/index/class all return nil
with no fault.
2026-07-25 14:58:49 -05:00
Brues 4afe0b9eae aura: read out-of-range groupmate auras from the roster
C_UnitAuras.* returned nothing for a party/raid member with no live
CGUnit (different map / far out of range): every path bailed on the
null unit, and the only fallback was the Aura::Source SMSG_SPELL_GO
cache, which needs the object to exist.

The server keeps transmitting each group member's current aura spell
IDs via SMSG_PARTY_MEMBER_STATS (GROUP_UPDATE_FLAG_AURAS / _NEGATIVE)
and the client stashes them in the group-member roster structs -- the
same source the built-in UnitBuff/UnitDebuff read out of range. Surface
them.

- Group::MemberStats::AuraArray(guid) mirrors the engine's own
  out-of-range fallback in Script_UnitBuff/Script_UnitDebuff exactly
  (party stats block +0x1a gated on the online flag, else raid slot
  +0x64; both 48x u16).
- Factor aura-table enrichment (caster/expiration/duration) into a
  single descriptor-independent PushEnriched core; Push and
  PushFromCache now delegate to it.
- New group-array enumerate branch (PushNthGroupAura /
  PushGroupAuraBySpellID / ...BySpellName / AppendGroupAuras), applying
  the engine's per-slot visibility predicate and merging any
  caster/timing the SpellGo cache observed.
- Api.cpp routes unit==null to the group array for every C_UnitAuras
  entry point. Safe: the token resolver never raises (returns 0), and
  the GUID lookup only runs after ResolveUnit already accepted the
  token.

Spell IDs only (no stacks; IDs are u16-truncated) -- same limitations
as UnitBuff. Verified in-game: GetUnitAuras("raid1") cross-map returns
Power Word: Fortitude (10938), matching UnitBuff.
2026-07-25 14:33:58 -05:00
Brues c01dceabb8 unit: class/race fall back to the player-info cache out of range
UnitClassBase / UnitRaceBase resolved via FUN_RESOLVE_UNIT_TOKEN and returned
(nil,nil) for a groupmate on another map -- but the engine's own UnitClass /
UnitRace fall back to the cached player-info record there (verified in-game:
UnitClass("raid1")="Priest", UnitRace("raid1")="Human" while our descriptor
path yielded nil). Give ours the same fallback: on a descriptor miss, read
class (+0x140) / race (+0x138) from the NameCache record by GUID. Verified
fixed: UnitClassBase("raid1")=("PRIEST",5), UnitRaceBase("raid1")=("Human",1).

That engine-NameCache peek existed in four places (the two above plus
loot/History and player/Info). Collapsed them into one primitive,
Unit::Identity::PlayerInfoRecord(guid) -> record* (null callback = peek only),
and pointed all four at it. FUN_PLAYER_INFO_LOOKUP is now called in exactly
one spot.
2026-07-25 13:19:04 -05:00
Brues 365df6b882 group: add Group::MemberStats, generalize the out-of-range roster reader
Extract the roster fallback (added for UnitPower) into a shared
Group::MemberStats reader and give it the full picture. Lookup(guid) tries
the party stats block (FUN_GROUP_MEMBER_STATS_LOOKUP) then the raid slot
(FUN_GROUP_MEMBER_SLOT_LOOKUP) -- the object-independent group roster fed by
SMSG_PARTY_MEMBER_STATS -- and returns health, maxHealth, power, maxPower,
powerType, level, areaId, online (both paths) plus dead, subgroup, rank (raid
path). Raid-struct layout mapped from Script_GetRaidRosterInfo (0x004bb560):
subgroup@+8, rank@+0xc, flags@+0x18 (bit0 online, bit2 dead), level@+0x22,
areaId@+0x24, plus the health/power fields already used.

UnitPower/Max/Missing now go through it (no behavior change -- verified target
still reads UnitPower == UnitMana == 2896 on a different map), and
UnitHealthMissing gains the same fallback so it no longer returns 0 for an
out-of-range groupmate. UnitPowerType already had the engine's own roster
fallback (0x00517940) and needs nothing.

The extra fields (level/area/online/dead/subgroup/rank) are populated but not
yet consumed -- groundwork for fixing UnitLevel / UnitIsConnected / UnitIsDead
and a full GetRaidRosterInfo for out-of-range members.
2026-07-25 12:59:55 -05:00
Brues 72de6c0960 unit: fall back to the group roster for out-of-range power reads
UnitPower / UnitPowerMax / UnitPowerMissing read the CGUnit descriptor
directly, so they returned 0 for a party/raid member on a different map
(no live object). The engine's UnitMana/UnitManaMax don't -- they fall back
to the cached member stats from SMSG_PARTY_MEMBER_STATS.

Mirror that fallback: when ResolveArgs finds no live object, resolve
token -> GUID and read the member's primary power from the party stats block
(FUN_GROUP_MEMBER_STATS_LOOKUP: type@+9, cur@+0xe, max@+0x10) then the raid
slot (FUN_GROUP_MEMBER_SLOT_LOOKUP: type@+0x58, cur@+0x60, max@+0x62), all
u16 -- exactly Script_UnitMana (0x00517670) / Script_UnitManaMax (0x005177e0).
Verified in-game: a different-map target now reports UnitPower == UnitMana
(2896) instead of 0.

Limitation (inherent): the roster caches only the member's primary power, so
an explicit non-primary powerType returns 0 out of range. Reached only after
ResolveArgs fails on an already-valid token, so TokenToGUID can't raise.
2026-07-25 12:42:06 -05:00
Brues eeba4ada9d focus: keep focus on party/raid members that leave range
3.3.5 does not drop focus the instant a unit leaves the object table -- its
object-teardown purge (FUN_00524350) is gated by FUN_00512a30, which is
"party-member (FUN_0052d310) OR raid-member (FUN_00573200)". So a groupmate
whose CGUnit is destroyed by going out of range/LoS keeps focus and reattaches
when they return; only non-group units clear on despawn. (Verified in 3.3.5
via Ghidra: focus GUID at DAT_00bd07d0/d4, sole writer FUN_0051ff20, purge
gate decoded to the party/raid roster checks.)

OnWorldTick now mirrors that gate: on an ObjectByGUID miss it keeps focus when
IsGroupMemberGuid(g_focusGUID) -- reading the object-independent roster GUIDs
(VAR_PARTY_GUIDS 4-slot array + VAR_RAID_MEMBER_PTRS 40-slot member-ptr array,
GUID at *member+0) -- otherwise clears as before. A new g_focusObserved flag
tracks whether the "focus" unit-event observers are attached to a live object;
they die with the object on despawn, so OnWorldTick re-registers them when a
groupmate returns to range, and Set() registers only against a resolvable
object (deferring to OnWorldTick when focusing an out-of-range member).

Corrects the earlier note claiming vanilla/modern drop focus on mere range
loss -- that was wrong; the drop is object-teardown gated by group membership.
While a groupmate is out of range UnitExists("focus") is still false (no client
object to read), but the focus survives and snaps back live on their return.
2026-07-25 12:19:51 -05:00
Brues 5f13c63c99 unit: add UnitSpellHaste(unit) -- backport of the TBC+ haste getter
Vanilla 1.12 has no spell-haste API. UnitSpellHaste reads UNIT_MOD_CAST_SPEED
(the cast-time multiplier at descriptor +0x22c that the server folds into
SpellEntry::GetCastTime) and converts it to the modern haste percentage:

    haste% = (1 / modCastSpeed - 1) * 100

so 1.0 -> 0, 0.5 (half cast time) -> 100, and a slow like Curse of Tongues
(>1.0) -> negative. This is the Blizzard-shaped surface over the same field
nampower exposes raw as GetUnitField(unit, "modCastSpeed"), letting addons
drop that dependency (raw multiplier recoverable as 1/(1 + haste/100)).

Formula verified byte-exact against 4.3.4's Script_UnitSpellHaste
(FUN_004555b0): `(C1 / mult) * C2 - C2` with C1=1.0, C2=100.0 and a
div-by-zero guard -- the constants are forced by "unhasted must read 0" and
"return a percentage". The 4.3.4 field lives at desc+0x10c; +0x22c is the
verified 1.12 offset. Our div-guard uses `> 0` vs retail's `!= 0` (identical
for the always-positive cast-speed field, marginally more defensive).

New src/unit/SpellHaste.cpp + OFF_UNIT_MOD_CAST_SPEED; docs + README updated.
2026-07-25 00:27:17 -05:00
Brues afa1f62720 unit: add the unmodified arg to UnitPower / UnitPowerMax
Completes the retail signature UnitPower(unit [, powerType [, unmodified]])
(and UnitPowerMax). A truthy third arg skips the per-type display divisor and
returns the raw internal value, via the same ToBoolean(L, 3) path already used
by UnitPowerMissing.

Verified in-game on a warrior (rage, divisor 10):
  UnitPower(1)=96  UnitPower(1,true)=961   (floor(961/10)=96)
  UnitPowerMax(1)=100  UnitPowerMax(1,true)=1000
  UnitPowerMissing(1)=4  UnitPowerMissing(1,true)=39
The missing=4 (not 3) confirms the display-value subtraction: 100-96, not
(1000-961)/10 floored to 3.

Docs updated (signature, TOC anchor, unmodified note).
2026-07-25 00:10:09 -05:00
Brues c369373efe unit: add UnitPowerMissing(unit [, powerType [, unmodified]])
The power analogue of UnitHealthMissing: returns UnitPowerMax - UnitPower for
the given type in one native call. Reuses the Power module's ResolveArgs /
PowerDivisor, so it inherits the primary-power fallback (powerType omitted)
and per-type display divisor. The unmodified third arg (truthy) skips the
divisor for the raw internal deficit, matching retail's UnitPower.

Subtracts the two display values (each integer-divided) rather than dividing
the raw difference, so it equals UnitPowerMax(...) - UnitPower(...) exactly --
the rage case would otherwise be off by one (100/5 -> 95, not (1000-55)/10 =
94). Returns 0 for invalid units and for types the unit has no pool for
(e.g. energy on a mana user). Verified in-game: mana 6685-5929 = 756.

Docs + README updated.
2026-07-25 00:04:16 -05:00
Brues 1c86d0dead unit: add UnitHealthMissing(unit)
Returns the health deficit -- the equivalent of
UnitHealthMax(unit) - UnitHealth(unit) -- in one native call, so healing
addons don't call both engine getters and subtract in Lua every frame.
One token resolve + two descriptor field reads (HEALTH +0x40, MAXHEALTH
+0x58); no display divisor (health is stored at face value), clamped at 0.

Tracks the engine's own UnitHealth/UnitHealthMax exactly in both forms:
real values (player 3600-1 = 3599) and vanilla's percentage form for
non-grouped units (target 100-85 = 15). Returns 0 for a valid-but-absent
unit, matching UnitHealth's convention.
2026-07-24 23:58:46 -05:00
Brues cedbd04553 cast: mirror the server's +500ms ranged aim time in the cast-time prediction
FUN_006e3340 (the spell tooltip's cast-time helper, which our zero-latency
CastStartSet_h stamp reuses) omits the flat +500ms "aim time" the server adds
to every ranged, non-autorepeat spell -- SpellEntry::GetCastTime does
`castTime += 500` for SPELL_ATTR_RANGED. So the client prediction ran ~500ms
short of the server on Volley / Aimed Shot / Multi-Shot (Volley's real cast is
3000ms base + 500 = 3500ms), and the confirming SMSG_SPELL_START then snapped
the bar out ~1 RTT later. This was the dominant cause of the Volley overhang,
present with or without Quick Shots.

CastTimeMs now adds the +500 for SPELL_ATTR_RANGED spells (excluding Auto Shot
/ Shoot via the AttributesEx2 autorepeat bit, matching the server), so the
prediction is right from frame 1. Only applied when the spell already has a
cast time; instant ranged abilities the server gives a 500ms aim time still
surface through the packet path. The HandleSpellStart reconcile stays as the
backstop for any residual client/server divergence.
2026-07-24 23:21:26 -05:00
Brues 3b1bba2131 cast: reconcile local-player cast time to the server on the confirming packet
The client-side FUN_CAST_START_SET hook stamps g_cast with a zero-latency
prediction from FUN_006e3340, which folds in the caster's cast-speed /
ranged-haste multiplier (descriptor +0x22c). That is correct for spells the
server also hastes (Aimed Shot / Multi-Shot), but wrong for ones it does
not. Volley (1510 / 14294 / 14295) is the case: it is NOT channeled in the
client DBC (AttrEx has no 0x4/0x40) so it takes the regular-cast path, and
its Attributes & 0x30 == 0 so FUN_006e3340 applies the +0x22c multiplier --
yet Volley gains no benefit from Quick Shots server-side. The predicted bar
therefore ended ~before the real cast finished ("still casting after the bar
ends").

SMSG_SPELL_START carries the server's authoritative cast time, but for a
cast the client already stamped we were deduping the packet away entirely to
avoid restarting the bar. Instead, keep startMs (no visual restart) and snap
endMs to the server's castTime (preserving any accumulated pushback). Aimed
Shot / Multi-Shot are unaffected -- the server hastes them too, so client and
server agree and the reconcile is a no-op.

Closes https://github.com/brues-code/pfUI/issues/28
2026-07-24 22:40:27 -05:00
Brues 786428c9fb focus/who: reset per-character state on logout
Both modules held per-character state in process globals that the DLL
never cleared on a logout -> character-select -> login (the DLL is not
reloaded across that transition), the same bug class as the equipment-set
leak.

Focus: g_focusGUID / g_focusTargetGUID carried a dead GUID from the prior
character into the next. The WorldTick despawn probe self-healed it within
a tick, but fired a spurious PLAYER_FOCUS_CHANGED and could not cover a
GUID collision. Clear it from a GlueModuleAutoRegister, which fires on the
world->glue return a logout triggers but NOT on /reload -- so focus still
survives /reload (retail behavior) and drops only on logout.

Who: a /who whose SMSG_WHO response never crossed a logout left g_inFlight
stuck (IsWhoQueryPending wrongly true for the next character) and the
VAR_WHO_TO_UI_FLAG override forced on (routing the next character's /who to
the WhoList). Reset in-flight state and restore the flag on every in-game
Lua (re)build via ModuleAutoRegister, which fires per login and per /reload
before any addon runs -- previously only ResetIfStuck's lazy 10s-on-next-
send backstop covered this.
2026-07-24 22:29:05 -05:00
Brues f5ecdc69c5 equipmentset: reload sets per character, not once per process
EnsureLoaded latched on a process-global g_loaded flag that was never
reset. The injected DLL survives a logout -> character-select -> login
(no process restart), so opening the Equipment Manager on character A
cached A's file path and sets permanently; character B then read, and
saved into, A's data. Only a full game restart cleared the globals, and
never opening the manager on A left B correct -- matching the report.

Re-resolve the per-character path on every EnsureLoaded call and reload
when it changes, so the cache self-heals across any character/account
switch. Also clear the per-session ignored-slot state on switch. Every
mutation Persist()s immediately, so dropping the old in-memory sets
never loses unsaved work.

Fixes https://github.com/brues-code/pfUI/issues/29
2026-07-24 22:13:55 -05:00
Brues 7531223b9a nameplate: assign stable slots instead of a compacting list
Switch nameplateN indexing from a compacting vector (append on ADDED,
erase + shift-down on REMOVED) to retail-exact slot assignment: a plate
keeps its slot for its whole lifetime, a removal frees the slot, and the
next new plate reuses the lowest free one. Survivors are never renumbered
when another plate is removed - matching modern WoW, where a middle plate
vanishing leaves the others' tokens unchanged and its slot goes vacant
until reused.

g_orderedGUIDs -> g_slots (sparse; free slots hold GUID 0, trailing
empties trimmed). GetGUIDByIndex returns 0 for a free or out-of-range
slot; new GetSlotCount exposes the high-water mark. The reverse token walk
in Unit::Identity now scans 1..GetSlotCount() and skips gaps instead of
stopping at the first 0. The per-plate observer lifecycle is unchanged
(keyed on GUID: register on ADD, unregister on REMOVE).

Verified in-game: 3 plates in slots 1/2/3, removing the middle one leaves
slots 1 and 3 occupied and 2 vacant - no renumber.
2026-07-24 18:45:42 -05:00
Brues cb4e428592 unit: fire per-token unit events for focustarget
Extend the focus observer to the focus unit's current target, so
UNIT_HEALTH / UNIT_AURA / ... fire with arg1 == "focustarget" like a
native token. Unlike focus (a sticky GUID), the focustarget GUID is
volatile - it changes whenever the focus re-targets, and vanilla fires no
event for a unit changing its target (UNIT_FIELD_TARGET, field 10, has no
event-table slot). So the WorldTick watcher re-reads the focus's target
each tick and re-points a second TokenObserver at it only when that
identity changes; the focustarget events themselves still fire
event-driven through the observer (only the re-pointing is tick-gated,
<=1 tick lag). Set() drops the stale focustarget observer immediately on
a focus change/clear.

Verified in-game: focustarget events fire and re-point when the focus
switches targets.
2026-07-24 18:13:08 -05:00
Brues e7e2fe05dc unit: guard TokenObserver against a null observer-registry root
Register/Unregister funnel through FUN_00464890, which dereferences the
client/player-rooted observer registry at [VAR_LOCAL_PLAYER_PTR] (+0x24).
That root is null out of world (login, loading screens, logout teardown),
where the helper null-derefs -> ERROR #132 (ACCESS_VIOLATION reading 0x24).

The nameplate teardown on world-exit fires NAME_PLATE_UNIT_REMOVED for
every plate, each calling Unregister while the root was already null ->
crash. Player::Equipment never hit this because it only registers from the
enter-world hook; focus/nameplate register from Lua / WorldTick, which can
run mid-transition.

Gate both Register and Unregister on RegistryReady() ([VAR_LOCAL_PLAYER_PTR]
!= null). Out of world there are no live objects or observer nodes to touch
anyway - nodes die with their objects on teardown, and in-world callers
re-register / clean up on the next tick.
2026-07-24 18:10:42 -05:00
Brues d7078827fd unit: fire per-token unit events for focus and nameplateN
Make the synthetic focus / nameplateN unit tokens first-class sources of
the standard per-token unit events (UNIT_HEALTH, UNIT_MANA, UNIT_AURA,
UNIT_LEVEL, ...): arg1 == "focus" / "nameplateN" now fires just like
"party1", so focus and nameplate frames can update event-driven instead
of polling.

Vanilla fires these events only for units it "watches"
(target/party/raid/pet/mouseover) - FUN_0060c520 recomputes a unit's
token-category mask and, on 0->nonzero, FUN_0051bbb0 registers bank-UNIT
descriptor-field observers whose callback broadcasts the field's event to
the guid's tokens (field index == event id; health +0x40 = event 16 =
UNIT_HEALTH). Focus and nameplates are not watch categories, so they
never fired.

New Unit::TokenObserver replicates that watch registration (FUN_0051bbb0's
field set + per-index sizes) with a caller-supplied callback, via the
engine's own observer registrar - the same API Player::Equipment uses. No
hooks: zero MinHook trampolines, hence no collision risk (the reason this
beats co-hooking the broadcast). The registrar appends a fresh node per
(guid, field), so our observers coexist with the engine's - a unit that is
target AND focus AND a nameplate fires all three tokens. Node lifetime is
engine-managed (nodes die with the object; unregister no-ops post-despawn).

- Focus: register/unregister in Unit::Focus::Set.
- Nameplates: register on NAME_PLATE_UNIT_ADDED, unregister on _REMOVED
  and (all) in PrepareForReload, since objects survive /reload; the
  callback resolves the changed guid to its current plate index at fire
  time.

Offsets cross-confirmed against nampower's offsets.hpp (SendUnitSignal
0x515e50, StringParamFormat "%s" 0x82e280, SignalEventParam 0x703f50,
UNIT_HEALTH 16); the GUID->token reverse map nampower left as a TODO is
FUN_00515c50.
2026-07-24 17:26:23 -05:00
Brues c571c1a852 equipmentset: build the tooltip natively, not via Lua method dispatch
SetEquipmentSet built its lines by calling back through self:SetText /
self:AddLine / self:Show - a PushValue/GetTable/Insert/Call dance per
line. Replace that with the engine's own per-tooltip clear plus raw
add-line (with a small r,g,b to packed-color helper) - the same native
path SetTotem and SetHyperlinkCompareItem use. Localization is unchanged:
PushLocalizedFormatInt for the count lines, Lua string.format for the
ITEM_MISSING %s template.

Shows itself via Script_Show at the end, matching retail (the inner
builder tail-calls the show) and PaperDollFrame.lua, which sets the
anchor then calls SetEquipmentSet with no trailing :Show().
2026-07-23 22:38:12 -05:00
Brues a7b205cd56 totem: add GameTooltip:SetTotem(slot)
Backport of the TBC (2.4.0) tooltip method. Fills the tooltip with the
slot's active totem as two native lines - name (NORMAL_FONT_COLOR) and
time remaining (white) - mirroring retail's Script_GameTooltip_SetTotem
(verified against the 3.3.5 binary; the two line colors are read verbatim
from its color data). Built with the engine's own per-tooltip clear plus
raw add-line - no Lua method dispatch - and shows itself via Script_Show,
matching retail's TotemFrame.xml OnEnter which calls SetTotem with no
trailing :Show().

The time line mirrors SecondsToTimeAbbrev (raw seconds under a minute,
minutes rounded up above) and localizes through the FrameXML GlobalStrings
SPELL_TIME_REMAINING_SEC/_MIN with English fallbacks; slot data is the
existing GetTotemInfo tracker.
2026-07-23 22:38:00 -05:00
Brues a3f224876f event: add a correctly-timed on-demand table-grow valve
Re-introduces the event-table grow valve (removed in 538beda as
mis-timed) at the correct point. Event::Custom::Grow runs from
RetryClaims -- the frame:RegisterEvent hook -- on the first in-game
registration, which is AFTER RebuildEventTable (and SuperWoW/nampower's
clamp-to-700 that co-hooks it) but BEFORE any chain is populated. So
every chain is still an empty self-sentinel and the buffer can be moved
safely. A one-shot latch (reset per reload) runs it at most once per
build, and a hard "abort if any chain is live" scan backs the timing.

Same realloc logic the old EnsureCapacity used -- SMemAlloc a new
buffer, copy name pointers, re-init empty-sentinel anchors, swap the
{cap,count,base} globals, SMemFree the old -- bypassing SetEventCount's
destructive =700 clamp. Consumers read base fresh; the engine's reload
teardown frees our buffer + names as its own.

Dormant in practice (~200 low gaps vs ~46 reservations). Validated via a
new _classicapi_ForceEventGrow() diagnostic that forces a grow on the
next /reload: table grew 700->716, all events (ours, engine,
SuperWoW/nampower, VMT) survived with names intact, dispatch worked on
the grown table, and a following /reload cleanly freed the buffer.
2026-07-23 21:27:29 -05:00
Brues a40236eb84 spell: add GameTooltip:AddSpellByID(spellID)
Append counterpart to SetSpellByID -- adds a spell's tooltip (name, cast
time, cost, range, description) to the current tooltip WITHOUT clearing
existing lines, so callers can compose tooltips like
AddLine(header) + AddSpellByID(id).

BuildSpellTooltip's last arg gates the clear: SetSpellByID passes 0
(clears via FUN_00530050 first); AddSpellByID passes 1 (skips the clear
and appends). That append path is the engine's talent "next rank"
preview, so it emits a "Next rank:" header instead of the spell name and
doesn't stash the displayed spellID -- we overwrite that header line (at
the pre-build numLines index) with the real name from Spell.dbc and let
GetSpell keep reflecting the base tooltip. Verified in-game.
2026-07-23 21:12:06 -05:00
Brues 538beda499 event: remove the mis-timed EnsureCapacity table-grow valve
EnsureCapacity was meant to grow the event table when the engine's ~200
low NULL gaps ran short of our ~46 reservations, by reallocating the
entry buffer via Storm and swapping the base/count globals. But it was
called from LoadScriptFunctions_h, which runs BEFORE RebuildEventTable
inside FUN_0048FBF0 -- so it always operated on the previous cycle's
still-populated table, tripped its own "abort if any chain is live"
guard, and never actually grew anything. Mis-timed dead code doing risky
buffer surgery on the shared event table.

Claim-NULL into the engine's low gaps is the sole mechanism now; it
always suffices, and TryClaim logs once if it somehow doesn't. Drop the
function, its Storm alloc/free helpers, and the now-inaccurate offset
comments.
2026-07-23 21:06:36 -05:00
Brues af01a4b408 event: claim NULL slots low-first + on-demand table expansion
Reworks custom-event slot reservation to be coordination-free and
durable without depending on DLL load/hook order.

- Claim NULL-name slots walking LOW->high instead of from the tail.
  SuperWoW/nampower own the high range (fixed IDs 549..655) and
  destructively clamp the table to 700, and VanillaMinimapTracking also
  walks the tail, so the top is contested; the engine's low gaps (~200,
  incl. a ~64-slot hole at 42..106) are stable and uncontested. Verified
  in-game: our events now land at 1..64, VMT alone at 699 -- clean
  separation, independent of the clamp.

- Add Event::Custom::EnsureCapacity: on-demand grow run once from
  LoadScriptFunctions_h (after module registration so all reservations
  incl. lazy TTS are counted, before any frame registers). If NULL slots
  < reserved, it reallocates the entry buffer via Storm and swaps the
  {cap,count,base} globals directly, bypassing SetEventCount's clamp --
  so it's load/hook-order independent. Defensive: reads fresh, verifies
  all chains empty before moving the buffer (aborts otherwise), frees
  only the old buffer (names are shared), publishes base before count.
  Dormant in the common case (low gaps dwarf our count).

- Drops the SetEventCount co-hook (Capacity.cpp) entirely -- nothing new
  on a SuperWoW/nampower-contended function. Keeps the one-shot
  table-full log as the backstop.

Adds Storm SMemAlloc/SMemFree + VAR_EVENT_TABLE_CAP offsets.
2026-07-23 18:13:41 -05:00
Brues 33c8c3e37c Add C_TaxiMap.GetTaxiRoute(slotIndex)
Exposes the client's computed flight route to a taxi-map slot as an array
of TaxiNodes.dbc IDs in flight order { currentNodeID, ..., destNodeID } --
the exact chain TakeTaxiNode sends the server.

Mirrors the TakeTaxiNode worker (FUN_004dc8d0): a single direct hop when a
TaxiPath edge exists (via the FUN_004dbad0 adjacency matrix), otherwise the
client's precomputed multi-hop route array (slot +0x14, length +0x18). This
lets addons identify every hop of a per-character route without matching
flight-map coordinates back to nodes.

Offsets added: per-slot route array/count/flag, the current-node record
pointer, and the node adjacency matrix. Documented in docs/API.md + README.
2026-07-23 06:00:55 -05:00
Brues c5d5415afe taxi: add C_TaxiMap.GetTaxiPaths + GetTaxiPathWaypoints
Expose the taxi routing graph and per-path geometry that vanilla keeps in
TaxiPath.dbc / TaxiPathNode.dbc but never surfaces to Lua (and addons can't
read DBCs at all).

- GetTaxiPaths() -> array of { pathID, fromNodeID, toNodeID, cost } (every
  directed flight-path edge; cost is the routing weight in copper).
- GetTaxiPathWaypoints(pathID) -> array of { x, y, z, mapID } world
  coordinates ordered by node index; sum the 3D chords for path length
  (/ 32 yd/s ~= single-hop flight seconds).

Lets addons build the flight graph, run travel-time / routing math, or drive
a map overlay without baking the geometry in. Pure DBC readers, no flight
master needed. Offsets for TaxiPathNode.dbc + TaxiPath cost added to
Offsets.h.
2026-07-23 03:59:04 -05:00
Brues 39dcfc73de event: add GetFramesRegisteredForEvent(event)
Returns the frames currently subscribed to an event as multiple return
values (retail's vararg signature). Reads the engine's own subscriber
chain off the event-table entry (entry+0xC head; node next @+0x04,
frame @+0x08, low-bit/null end sentinel) — the exact list
frame:RegisterEvent appends to, so it stays in sync with real
registrations, including AutoReserve custom events. Each frame is
pushed via the shared UI::FrameObject wrapper so frame methods work.
A counting pass drives lua_checkstack up front against heavily
subscribed events.
2026-07-21 14:41:10 -05:00
Brues 6e5f7c3e43 tradeskilllink: gate detail wheel on overflow
The detail ScrollFrame had mouse wheel enabled unconditionally, so even
when the content fit (bar hidden, 0 range) it still consumed wheel events
— clamping to a no-op but swallowing the scroll instead of letting it pass
through. Enable the wheel from SetDetailBarShown alongside the bar, so it's
on only when there's something to scroll.
2026-07-21 14:25:43 -05:00
Brues 2e05e86362 tradeskilllink: fix detail-pane scroll range + auto-hide
The trade-skill-link viewer's reagent pane couldn't scroll to the last
row for some recipes (issue #10). Root cause, found by comparing against
Blizzard's Blizzard_TradeSkillUI: resizing a ScrollFrame's child does NOT
recompute its scroll range in 1.12 — you must call UpdateScrollChildRect()
(TradeSkillFrame_SetSelection does exactly this). We resized the child but
never refreshed the range, so the bar's travel was capped at a stale max.

- Call detailScroll:UpdateScrollChildRect() after (re)sizing the child in
  RenderDetail and ClearDetail.
- Size the child from actual laid-out geometry (bottom of the last reagent
  button relative to the child top + name-plate overhang) instead of a
  hand-tallied constant that undercounted.
- Drive scrollbar visibility from the computed overflow (SetDetailBarShown)
  rather than the engine's range-changed event: scrollBarHideable only
  auto-hides on a range CHANGE, so content that fits from the start (e.g.
  Turtle's roomy pane) never hid, and GetVerticalScrollRange isn't reliably
  readable the same tick as UpdateScrollChildRect.

Net removes the old detailNeedScroll bool-tracking, per-need mouse-wheel
toggling, and the OnShow re-assert workaround — all of which were
compensating for the missing range recompute.

Fixes #10
2026-07-21 14:21:25 -05:00
Brues bcc631c4ed tradeskilllink: fix ColorMixin clobber from Fonts.xml re-includers
Addons that re-include ..\..\FrameXML\Fonts.xml in their TOC (notably
SpecialTalentUI, LoadOnDemand — pulled in when the talent frame is first
opened) re-run its inline script, which resets NORMAL_FONT_COLOR /
HIGHLIGHT_FONT_COLOR / GRAY_FONT_COLOR to plain {r,g,b} tables and strips
the ColorMixin methods our UI relies on. That crashed the trade-skill-link
viewer's NORMAL_FONT_COLOR:GetRGB() (issue #10).

Factor the standard color-global setup into CAPI_ApplyStandardColorGlobals
(idempotent — only (re)creates a tag that's missing :GetRGB) and re-run it
after SpecialTalentUI loads via EventUtil.ContinueOnAddOnLoaded, next to the
existing pfUI compat in AddOnCompat.lua.

Also simplify the viewer frame anchor to SetPoint("CENTER").
2026-07-21 12:54:39 -05:00
Brues f9fb32186d TradeSkillLink: Play Open/Close Sound 2026-07-21 11:11:41 -05:00
Brues 60adbba7c3 pointless fallback 2026-07-21 11:11:09 -05:00
Brues c35d883af0 targeting: backport TargetDirection*/TargetNearest* + GetPlayerFacing
Adds the post-vanilla TargetScript selection functions 1.12.1 lacks:

  TargetDirectionEnemy(facing[,cone]) / TargetDirectionFriend
  TargetNearest([reverse])
  TargetNearestEnemyPlayer([reverse]) / TargetNearestFriendPlayer
  GetPlayerFacing()

All five targeting functions reuse the engine's own tab-target core: the
visible-unit enumeration, the per-mode validity predicate FUN_00493e40
(reaction/attackability/alive, modes 1=enemy/2=friend), and the selection
commit. The only new logic is a player-GUID filter for the *Player variants
and the cone geometry for the direction variants. Cycle functions keep a
frozen per-filter snapshot advanced within a ~1s window (no ping-pong).

Target-setting routes through FUN_TARGET_BY_GUID (0x00489A40), which
rejects a GUID that no longer resolves to a live unit rather than
committing it — a stale snapshot GUID would otherwise leave "target"
pointing at freed unit data and crash the next handler that reads it.

GetPlayerFacing reads the CGUnit movement-block orientation at +0x9C4
(located by probing the player object across a known 180-degree turn); it's
the facing source the direction-target functions need.

Not backported (no vanilla equivalent): TargetPriorityHighlightStart/End,
IsTargetLoose, TargetToggle.

New offsets: FUN_TARGET_CANDIDATE_VALID (0x00493E40),
FUN_SET_SELECTION_BY_GUID (0x00493540), VAR_CURRENT_SELECTION_GUID_LO/HI,
OFF_UNIT_FACING (0x9C4).
2026-07-21 00:49:05 -05:00
Brues c202c1000f chatbubbles: add C_ChatBubbles.GetAllChatBubbles
Returns the active chat-bubble Frame objects, matching modern WoW's
7.2.5 signature. Vanilla's CGChatBubbleFrames are full CSimpleFrames
the engine creates in C++ without CreateFrame (same as default
nameplates), kept on an intrusive Storm TSList at 0x00B6F038 (next
link +0x318, low-bit sentinel). Mirror the engine's own walk
(FUN_004b1060) and push each as its canonical engine wrapper, so the
returned frames are real and method-capable and their text FontString
(+0x31c) surfaces via :GetRegions().

includeForbidden is accepted and ignored (vanilla has no forbidden
frames).

Factor the ScriptRegister->rawgeti wrapper push out of nameplate/Info
into a shared UI::FrameObject::Push; PushNamePlateFrame now forwards to
it (no behavior change).
2026-07-20 23:00:03 -05:00
Brues 98b4ae14e7 totem: add GetTotemDuration(slot)
Returns the slot's active totem total duration in seconds (0 when none) —
the totem's full lifetime from cast, same value as GetTotemInfo's 4th
return, companion to GetTotemTimeLeft. Reads the tracker's durationMs.
Verified in-game (constant 45 while time-left counts down).
2026-07-20 21:27:58 -05:00
Brues 8d957eb424 totem: add TargetTotem(slot)
Target the player's totem in a slot (1-4). 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 via FUN_00489a40 — the
set-target-by-GUID path Script_TargetUnit uses after its token→GUID
resolve. No-op when the slot is empty or the totem isn't visible. Added
Offsets::FUN_TARGET_BY_GUID.
2026-07-20 21:25:34 -05:00
Brues 78618ea2cc totem: add GetTotemTimeLeft(slot)
Returns seconds remaining before the slot's totem auto-destroys (0 when
no totem is active), computed from the existing Totem::Tracker's
startMs + durationMs. Slots 1-4 = Fire/Earth/Water/Air. Verified in-game
counting down.
2026-07-20 21:11:01 -05:00
Brues 1a4583e16e totem: fire PLAYER_TOTEM_UPDATE on slot changes
Backport the TBC PLAYER_TOTEM_UPDATE(totemSlot) event (absent from
vanilla's table, so reserved as a custom event) on top of the existing
Totem::Tracker. Every slot state change marks a dirty bit — the cast
path (SpellGo), duration expiry, and the WorldTick death-scan removal —
and OnTick flushes the dirty slots with Fire(id, "%d", slot). Flushing
from the tick keeps Lua handlers out of mid-packet context. Drops fire
next frame; removals within the ~250ms scan interval. Verified in-game.
2026-07-20 21:04:15 -05:00
Brues a20e1206fb totem: add GetTotemInfo(slot) with a self-tracking totem subsystem
Vanilla 1.12 tracks nothing about totems client-side (the totem bar,
PLAYER_TOTEM_UPDATE, and GetTotemInfo are all TBC additions), so
Totem::Tracker tracks the four element slots itself — data-driven:

- Slot from the summon spell's Spell.dbc effect (87-90 =
  SUMMON_TOTEM_SLOT1..4 = Fire/Earth/Water/Air; slot = effect - 86).
- Creature entry from the effect's EffectMiscValue (for death detection).
- Duration from SpellDuration.dbc via the engine duration helper.
- haveTotem tool item from the spell's Totem[0] field (0xA0) — the totem
  the spell requires (a tool, not a consumed reagent) — resolved from the
  player's spellbook on SPELLS_CHANGED, not hardcoded.

Casts are observed through Aura::Source's existing SMSG_SPELL_GO hook (a
one-line notify before its aura gate, since a summon applies no aura) —
no new hook, respects one-hook-per-target. Tool items resolve on
SPELLS_CHANGED (a no-arg event via the shared Event::SignalHook), when
the spellbook is populated. A slot clears when its duration elapses OR
when the totem creature disappears early (killed / Totemic Recall /
destroyed), detected by a throttled WorldTick object-manager scan for the
player-owned creature of that entry (seen-then-gone latch; CreatedBy ==
player so another shaman's same-entry totem can't mask yours).

GetTotemInfo returns haveTotem, totemName, startTime, duration, icon,
modRate=1, spellID. Turtle-custom totems are tracked automatically.
Also exposes Item::Count::InInventory (equipped + bags) as a shared
helper for the tool-presence check. Verified in-game: Earthbind lands in
slot 2, haveTotem reflects the Earth Totem tool, and Totemic Recall
clears the slot early.
2026-07-20 20:53:01 -05:00
Brues 9f67cade87 unit: add UnitOwnerGUID(unit)
Returns the GUID string of a unit's owner — the summoner of a
pet/guardian/totem or the charmer of a charmed unit — or nil for
players, world creatures, and unresolved units. Reuses Unit::Pet's
existing OwnerGuid helper (CharmedBy, else CreatedBy in m_objectFields),
the same field the pet predicates share. Verified in-game:
UnitOwnerGUID('target') == UnitGUID('targetowner').
2026-07-20 18:35:47 -05:00
Brues 8629e13e1f gameobject: add ClosestGameObjectPosition(gameObjectID)
Returns xPos, yPos, distance for the nearest visible game object of a
given GO-template ID, or nothing when none is in range — the game-object
counterpart of ClosestUnitPosition.

Extract the shared visible-object-manager scan into
Object::ClosestByEntry (object/ClosestByEntry.{h,cpp}): enumerate visible
objects, match GUID type + template entry (bits 24-47), return the
closest one's world position + center distance. Both ClosestUnitPosition
(TYPEMASK_UNIT / Creature) and ClosestGameObjectPosition
(TYPEMASK_GAMEOBJECT / GameObject) are now thin wrappers over it;
ClosestUnitPosition behavior is unchanged.

Same retail-vs-vanilla caveat as the unit version: returns the nearest
CURRENTLY-VISIBLE object rather than reading retail's static starting-
zone database (which vanilla lacks). Documented in docs/API.md.
2026-07-20 18:26:46 -05:00
Brues ca9bfbab5e unit: add ClosestUnitPosition(creatureID)
Returns xPos, yPos, distance for the nearest creature of a given NPC
entry ID, or nothing when none is in range. Walks the visible-object
manager (Loot::Nearby pattern), matches creatures whose GUID encodes
the entry (bits 24-47, per guid/CreatureInfo), and returns the closest
one's world position + center distance in yards.

Semantic note: retail's ClosestUnitPosition reads a static client spawn
database (starting-zone mobs only); vanilla 1.12 has none, so this
returns the nearest CURRENTLY-VISIBLE creature of that entry (anywhere)
— more general than retail, but can't point at un-synced spawns.
Documented in docs/API.md.
2026-07-20 18:18:52 -05:00
Brues 8fdc767cc7 item: add Enum.ItemQuality
Poor=0 through Artifact=6, matching the numeric quality GetItemInfo /
C_Item.GetItemQuality report. Heirloom (7) and WoWToken (8) are omitted
— no such items exist on 1.12. Registered in src/item/TypeInfo.cpp
alongside Enum.ItemClass / Enum.InventoryType. Docs + README updated.
2026-07-20 17:36:47 -05:00
Brues aa31c25be5 item: add GetItemClassInfo, GetItemSubClassInfo global, Enum.ItemClass
- GetItemClassInfo(classID) -> localized ItemClass.dbc name, registered
  as both a global and C_Item.GetItemClassInfo. Obsolete class slots
  return the client's literal "...(OBSOLETE)" string.
- GetItemSubClassInfo(classID, subClassID) exposed as a global (the
  C_Item form already existed); returns name + the armor-material bool.
- Enum.ItemClass: 0..15 with modern key names on the obsolete slots
  (Gem/ItemEnhancement/CurrencyTokenObsolete/PermanentObsolete), plus
  post-vanilla 16..19 for parity, matching the Enum.InventoryType
  precedent in the same module.

All added to src/item/TypeInfo.cpp alongside the existing subclass /
inventory-type surface. Docs + README updated.
2026-07-20 17:27:28 -05:00
Brues 29aafe88f8 turtle: move combo-finisher & armor-healing custom data out of stock
Two pieces of hardcoded Turtle-specific data were embedded in stock
modules; relocate them to src/turtle/ behind extension points so the
stock code carries only generic mechanism.

- aura/ComboDuration: add an AutoDanglingResolver extension point; the
  stock module keeps the dangling-row detection + scaling formula, and
  Turtle's reworked-Rip base/max values move to
  src/turtle/ComboDuration.cpp. Not gated on Turtle::Detected() — the
  dangling-row condition stays the gate (gate on the bug, not the
  realm), preserving prior behavior exactly.

- spell/BonusDamage: add a Spell::HealingAura resolver extension point;
  the stock GetSpellBonusHealing decoder keeps auras 135 (flat) and 175
  (xSpirit), and Turtle's Ironclad aura 199 (xArmor) moves to
  src/turtle/HealingAura.cpp, gated on Turtle::Detected() (an aura index
  is a generic slot that could collide on another server).

Behavior is unchanged on Turtle; both extractions are pure relocation.
2026-07-20 16:49:45 -05:00
Brues 461f15a4a6 item: derive bag family from (class, subclass) for bags with empty field
Turtle's item data leaves m_bagFamily at 0 on the bags/quivers
themselves — the four profession bags (Soul/Herb/Enchanting/
Engineering, Container class) and quivers/ammo pouches (Quiver
class) all read 0, so C_Item.GetItemFamily and
C_Container.GetContainerNumFreeSlots reported 0 for them even
though the tooltip clearly shows "Soul Bag" etc. Recover the family
from the item's class + subclass instead (keyed on class because
subclass numbers repeat: Container sub 2 = Herb Bag, Quiver sub 2 =
Quiver). Loot items keep carrying the field directly.

Factored the derivation into a shared Item::BagFamily helper
(BitmaskForRecord) used by both GetItemFamily and the free-slot
functions, so a bag and the items it holds always agree on the
family bit. Side effect: CalculateTotalNumberOfFreeBagSlots now
correctly excludes specialty bags from the general free-slot total.

Non-stock data lives in its own module: src/turtle/ with a
TURTLE_WOW_VERSION-based Turtle::Detected() gate (no realm sniffing)
and the custom Meat/Fish/Leather/Mining families (ItemBagFamily.dbc
rows 10-13) plugged into Item::BagFamily via an AutoResolver
extension point, so the stock table stays pure vanilla.
2026-07-20 16:38:42 -05:00
Brues 6245d72694 unit: make UnitInRange reach-aware
Compare center distance against `40 + playerReach + targetReach`
instead of a flat 40, reading each unit's bounding radius from
`[m_objectFields + 0x1F0]` — the same per-unit size factor the
engine's spell-range helper (FUN_006e3480) and the interact/loot
range checks add. A 40-yard heal reaches a target whose center is
slightly past 40 yards but whose body is within reach; the old flat
cap reported those out-of-range. UnitDistanceSquared stays raw
center-to-center, matching retail.
2026-07-20 14:52:35 -05:00
Brues bd14228ad7 event: add PLAYER_ENTERING_WORLD payload (isInitialLogin, isReloadingUi)
Backport the 8.0.1 PEW payload onto vanilla's arg-less PLAYER_ENTERING_WORLD.

PEW is a no-arg event, so it broadcasts through FUN_FIRE_EVENT_NO_ARGS
(__fastcall(int), the no-arg dispatcher) — NOT the variadic FUN_FIRE_EVENT.
So we intercept that dispatcher and, for the PEW event id, suppress the
no-arg fire and re-broadcast through the variadic dispatcher with the two
booleans (true->1 / false->nil, the %d/%s+nullptr trick). Both fire paths
walk the same frame chain, so PEW-registered frames get the args once.

Flags need no PEW-specific engine hook — they fall out of signals we already
produce: GlueModuleAutoRegister (glue-screen boot) latches "next enter-world
is a fresh login"; ModuleAutoRegister (in-game Lua re-init) marks
login-or-reload; a zone/instance transition rebuilds neither, so both false.

New shared Event::SignalHook: FUN_FIRE_EVENT_NO_ARGS was already hooked by
loot/Scan (silent-scan suppression), and MinHook allows one hook per target,
so — like Tick::WorldTick for the per-frame tick — this module now owns the
single hook and fans out to interceptors. loot/Scan refactored from owning
the hook to being a subscriber (behavior identical). Event::EnteringWorld is
a second subscriber.

Verified in-game: fresh login, /reload, and instance transition each report
the correct (isInitialLogin, isReloadingUi).
2026-07-20 03:22:07 -05:00
Brues 5b15172894 coroutine: guard AuxResume xmoves with lua_checkstack
lua_xmove moves values via api_incr_top, which asserts room on the
destination rather than growing it. AuxResume xmoved an unbounded count both
ways without a guard: nres (a coroutine body can yield/return arbitrarily
many values) onto L, and nargs (a caller can resume(co, unpack(bigTable)))
onto co. Moving more than the ~20-slot C-call guarantee corrupted the stack
-- the same latent bug strsplit had, now fixable thanks to the bound
Game::Lua::CheckStack.

Guard both xmoves; on overflow (>2048) push an error and return the error
path (false,msg for resume; re-raise for wrap). Verified in-game: a coroutine
yielding 100 values via unpack now returns all 100 cleanly (previously stack
corruption), and normal small returns still work.
2026-07-20 00:48:28 -05:00
Brues b5470e8d3d lua: add string.reverse/strrev, math.modf, math.huge
Close the remaining 5.0->5.1 string/math stdlib gaps:

- string.reverse(s) / strrev(s) — byte-wise reverse; 5.1 added it, 5.0's
  strlib lacks it. Registered on the string table and as the strrev global.
- math.modf(x) -> (integral, fractional) — integral truncated toward zero,
  fractional keeps x's sign (via C modf). Genuinely new in 5.1 (unlike fmod,
  which 1.12 has as math.mod).
- math.huge — positive-infinity constant (HUGE_VAL) set directly on the math
  table (it's a value, not a function).

All on both Lua states. Verified in-game: reverse, modf on +/- inputs, and
math.huge as a true infinity sentinel.
2026-07-20 00:31:20 -05:00
Brues c601967fdb lua: add strjoin / strtrim / strreplace
Round out the WoW string globals alongside strsplit. These are FrameXML Lua
in 3.3.5 (no C original — no name strings in the binary), so they're
implemented from standard semantics rather than disassembled:

- strjoin(delimiter, ...) — inverse of strsplit; concatenate varargs with the
  delimiter. nil/non-coercible pieces become "" so delimiters stay aligned.
- strtrim(str [, chars]) — trim a literal character set (default whitespace)
  from both ends via a two-ended scan; no allocation, embedded NULs preserved.
- strreplace(str, find, replace) -> (result, count) — plain-text (non-pattern)
  substring replace; empty find returns str unchanged. Not a stock WoW global
  (that build's compat script added it); documented as a ClassicAPI
  convenience complementing gsub.

Registered as globals on both Lua states. Verified in-game: join, empty
delimiter, trim (default + custom set), plain replace with count, and a
strsplit->strjoin round-trip.
2026-07-20 00:21:59 -05:00
Brues 5c063ade73 lua: add strsplit; bind lua_checkstack
Backport the WoW global strsplit(sep, str [, pieces]) to 1.12, ported from
3.3.5's strsplit (FUN_00816a60): split str on any character in sep, returning
the pieces as multiple values; pieces>0 caps the count with the unsplit
remainder as the final piece (0/omitted = unlimited, 1 = whole string).
Consecutive/trailing delimiters yield empty pieces, matching retail.

Two deliberate changes from the 3.3.5 source:
- Skip its lua_settop(L, 0). Popping the args un-roots the source string, so a
  GC step during a pushlstring could free the buffer we're still scanning.
  Leaving the args on the stack keeps the source GC-rooted; Lua returns the
  top N (the pieces) regardless of the args below.
- Bind lua_checkstack (0x006F2F30, __fastcall(L, size) -> int, found via its
  cmp ...,0x800 LUA_MAXCSTACK test) as Game::Lua::CheckStack and guard every
  push with it, erroring "strsplit(): Stack overflow" like 3.3.5 on genuine
  exhaustion (strsplit pushes an unbounded number of results). Reusable for
  any future multi-return C function.

Registered on both Lua states. Verified in-game across basic split, pieces
cap, multi-char separator set, empty middle piece, and empty-separator cases.
2026-07-20 00:05:24 -05:00
Brues 2bd33288c9 event: raise custom-event reservation cap (32 -> 64)
AutoReserve silently drops any reservation past MAX_RESERVED, and the
codebase crossed 32 file-scope reservations, so a shifting subset of custom
events never claimed a table slot -> Lookup returned -1 and Fire no-op'd.
Adding the three AUCTION_MULTISELL_* events moved the overflow onto
ITEM_DATA_LOAD_RESULT / GET_ITEM_INFO_RECEIVED, which stopped firing.

Raise the cap to 64 (well above the ~45 total incl. the lazy TTS events) and
add a comment warning to keep it above the AutoReserve count. Verified via
_classicapi_DumpAllEvents: all custom events now claim slots, item events
included.
2026-07-19 18:29:20 -05:00
Brues bf7e476c10 quest: add C_QuestLog.GetHeaderIndexForQuest
Returns the 1-based log index of the collapsible header (zone / category)
a questID sits under, or nil if the quest isn't in the log. The log is laid
out header-then-its-quests, so it locates the quest's entry and walks back to
the nearest preceding header row (+8 non-NULL). Pairs with GetQuestLogTitle
to fetch the category name.

Verified in-game: quest 60142 -> header index 1 -> GetQuestLogTitle "Dun
Morogh" with isHeader true.
2026-07-19 17:34:52 -05:00
Brues 8f3ed96d51 quest: add C_QuestLog.GetLogIndexForQuestID
The inverse of GetQuestIDForLogIndex: returns the 1-based quest-log index of
a questID, or nil if the quest isn't in the log. Walks VAR_QUEST_LOG_ENTRIES,
skips header rows via the +8 header-pointer gate, and returns the first
matching entry's index. The index spans the full entry list (headers
included), so it feeds straight into GetQuestLogTitle / the other index-based
quest-log accessors.

Verified in-game: index->ID->index and ID->index->ID both round-trip.
2026-07-19 17:30:46 -05:00
Brues e1ffaab6b4 item: add native C_Item.GetItemInfo (full modern tuple)
Implement C_Item.GetItemInfo(itemInfo) in C, returning the full modern
tuple instead of the Lua alias to the vanilla global (which only returned
1.12's short set). Sourced entirely from the cached ItemStats_C record plus
the class/subclass/inventory-type DBC name lookups item/Info.cpp already
does for GetItemInfoInstant — no new duplication.

Returns 18 values: itemName, itemLink, itemQuality, itemLevel, itemMinLevel,
itemType, itemSubType, itemStackCount, itemEquipLoc, itemTexture, sellPrice,
classID, subclassID, bindType, expansionID (0), setID (nil if none),
isCraftingReagent (false; no such flag in 1.12), itemDescription. itemTexture
is the icon path (no fileID system in 1.12). On a cache miss it warms the
cache and returns nil, landing on the GET_ITEM_INFO_RECEIVED retry — same
async contract as the stock global.

Drops the `C_Item.GetItemInfo = GetItemInfo` shim from ItemUtil.lua so the
native implementation isn't clobbered at addon load.

Verified in-game against Rancher's Trousers (nil setID) and Blackened Defias
Boots (setID 161) — all 18 fields correct.
2026-07-19 16:52:53 -05:00
Brues c13b1c8eb7 item: fix C_NewItems flagging unequipped / bank-pulled items as new
The new-item diff only tracked bag contents, so an item moving INTO a bag
from anywhere out of scope looked identical to a fresh loot. Unequipping a
piece of gear (equipment -> bag) flagged it new; same for pulling an item
out of the bank.

Widen the "already owned" baseline to the player's whole inventory — bags,
worn equipment (paperdoll + equipped bags), and the bank (main + bank bags)
— while still only flagging bag items. An item whose GUID was already owned
somewhere is a move, not an acquisition, so it isn't flagged. Bank GUIDs are
read straight from the invMgr array (the gate-bypass C_Item.GetItemCount
already uses; the array is server-populated at login), so no bank window is
needed. Cap raised 256 -> 512 to hold bags + equipment + a full bank.
2026-07-19 01:43:09 -05:00
Brues bedc5d6740 Fix OnEvent handler example to use vanilla globals 2026-07-18 15:44:40 -05:00
Brues bdef428ff7 Update README.md 2026-07-18 15:42:32 -05:00
Brues 25b1a1a95c auctionhouse: add C_AuctionHouse.PostItem (multi-stack auto-split)
Post numStacks auctions of `quantity` each from one source stack in a
single call (retail multi-sell style). Vanilla's CMSG_AUCTION_SELL_ITEM
(opcode 0x256, verified from Script_StartAuction 0x004CE770) has no count
field like WotLK's, so the server posts the whole item object a GUID points
at; posting a partial quantity requires the client to split it into a real
bag item first. Both the split and the post are server-authoritative and
async, so this runs a WorldTick state machine:

  Idle -> (source > quantity) split `quantity` into a reused free general
          bag slot via Item::Swap::MoveCount (CMSG_SPLIT_ITEM)
       -> SplitWait until the stack materializes
       -> point the sell-slot globals at it and call the engine's own
          Script_StartAuction (reusing all its per-stack validation)
       -> PostWait until the server pulls it from the slot -> next stack.
  The final exact stack posts the source object directly, no split.

At most one reused free slot is needed (each post frees it for the next
split); a whole-stack post needs none. Per-step ~10s timeout aborts
gracefully. Progress via retail event names AUCTION_MULTISELL_START /
_UPDATE(done,total) / _FAILURE. Immediate rejections return (false, reason).

New offsets: FUN_SCRIPT_START_AUCTION, VAR_AUCTION_AUCTIONEER_GUID_LO/HI,
VAR_AUCTION_DURATION_TABLE ({120,480,1440} minutes = 2h/8h/24h).

v1 limits: single source stack (no cross-bag aggregation), general-purpose
bags only for the temp split, one job at a time.
2026-07-18 14:05:31 -05:00
Brues 5e23332880 lua: add math.fmod
Backport math.fmod to 1.12's Lua 5.0. Pure 5.0->5.1 rename: 5.0 ships the
identical C function as math.mod (mathlib entry, FUN 0x007FAFD0 —
checknumber(1/2) -> fmod -> pushnumber); 5.1 renamed the Lua-facing entry
to math.fmod. Registered as a direct alias of that function pointer on both
the in-game and glue states (BaseLib::MathLib), no wrapper. math.mod stays
available, so code written for either name works.
2026-07-18 05:05:39 -05:00
Brues eb36b3e09e lua: add string.match / string.gmatch
Backport the Lua 5.1 pattern helpers to 1.12's Lua 5.0 (BaseLib::StringLib),
both reusing pattern machinery 5.0 already ships:

- string.match(s, pattern [, init]) calls the engine's str_find
  (0x007FC3B0) and reshapes the result — captures, or the whole match when
  the pattern has none, or nil. match and find are the same operation in
  lstrlib.c; find returns start/end, match returns the captures.
- string.gmatch is 5.0's string.gfind verbatim (renamed in 5.1), registered
  as a direct alias of the engine gfind (0x007FCFA0) — no wrapper.

Registered on both the in-game and glue Lua states. Only the
string.foo(s, ...) form works, not ("x"):foo(...): WoW's VM strips
type-metatables for non-table/userdata values (both lua_setmetatable and
luaT_gettmbyobj hard-return no-metamethod for strings), so string method
sugar can't be enabled client-side without hooking a hot VM core function.
Documented as a known limitation.

Drops the Util/String.lua polyfill (was just string.gmatch = string.gfind),
now redundant, and its .toc entry.
2026-07-18 04:47:45 -05:00
Brues 16452519a6 lua: add select(index, ...); consolidate Lua backports under one section
Backport Lua 5.1's select() to 1.12's Lua 5.0 (BaseLib::Select). Two
forms: select('#', ...) returns the vararg count; select(n, ...) returns
the args from position n on (negative n counts from the end). Ported from
luaB_select (lbaselib.c) — the numeric form pushes nothing and just
returns top-n, handing back the slice already on the stack. Registered on
both the in-game and glue Lua states (both are 5.0 and equally missing it).

Docs: gather the scattered Lua base-library restorations (select,
table.wipe, coroutine.*) into a single "Lua" section in API.md, and
collapse the separate Coroutine/Table rows in the README table into one
Lua row. No prose lost — the coroutine and table.wipe entries moved
verbatim under the new section (coroutine.* as level-4 subsections).
2026-07-18 04:21:40 -05:00
Brues 33c5f3041d container: add C_Container.GetContainerItemInfo
Backport the modern structured-table accessor. Vanilla's global
GetContainerItemInfo (Script_GetContainerItemInfo, 0x004F9670) returns
only a flat texture/itemCount/locked/quality/readable tuple; assemble the
full ContainerItemInfo table from the same descriptor + item-cache sources
plus the fields 1.12 never surfaced (hyperlink, hasNoValue, itemID,
isBound, itemName).

Live per-instance fields (stackCount, isLocked, isBound, itemID, hyperlink)
are always present; cache-derived fields (iconFileID, quality, hasLoot,
hasNoValue, itemName) are omitted/nil until the item's static data lands.
Reuses Item::StatAccum::FetchRecord and Item::Link for the cache peek and
link/name build (no new duplication); gathers all data into locals before
building the table so the engine link/name builders never interleave with
the half-built table on the Lua stack.

readable mirrors the engine branch at 0x004F97BD (static page text OR the
per-instance readable-text id at descriptor +0x9C, added as
OFF_DESCRIPTOR_READABLE_TEXT_ID). hasLoot is a best-effort static LOOTABLE
approximation (vanilla can't track post-loot emptiness client-side).
2026-07-18 04:06:11 -05:00
Brues e8a03d584b spell: add GetSpellBonusDamage / GetSpellBonusHealing
GetSpellBonusDamage(school) reads the player's per-school spell damage
directly from the CGPlayer sub-struct at [player+0xE68]+0xFD4 (POS) / +0xFF0
(NEG), net = POS-NEG. That field isn't in the broadcast descriptor (+0x110
reads zero — the vanilla server never sends it there), but the client keeps a
fully-computed copy at +0xE68 with gear/enchants/buffs/talents/sets baked in.
Same source nampower's GetSpellPower reads; verified 613 generic / 647 Fire on
a geared mage. 1-based school, matching 3.3.5's Script_GetSpellBonusDamage.

GetSpellBonusHealing() has no such field (vanilla lacks a healing-done field
entirely), so it's derived to mirror the server's SpellBaseHealingBonusDone:
  - flat healing: SPELL_AURA_MOD_HEALING_DONE (135) off gear equip-effects,
    item enchants, random suffixes, and active buffs
  - Spirit conversion: SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT (175) x
    total Spirit / 100  (Priest Spiritual Guidance)
  - Armor conversion: SPELL_AURA_MOD_SPELL_HEALING_OF_ARMOR_PERCENT (199) x
    armor / 100  (Turtle Ironclad)
Percents are read straight from Spell.dbc, so it's generic across any
aura-175/199 talent/buff including Turtle customs, and gated on SPELL_ATTR_
PASSIVE for the known-spell-bitmap walk. Spirit/Armor come from UNIT_FIELD_
STAT4 (+0x250) / UNIT_FIELD_RESISTANCES[0] (+0x254).

Item flat healing routes through the shared Item::StatAccum engine rather than
re-implementing the item spell/suffix/enchant walk: extract a reusable
ApplyEnchant() (from ApplyRandomSuffix) plus a Value() reader, and read
ITEM_MOD_SPELL_HEALING_DONE_SHORT.

The healing sum is expensive (StatAccum over 19 items + buff table + the 27k
known-spell bitmap), so it's cached and recomputed only when a player stat
input changes. New Player::StatSignal (a pull-based epoch) is bumped from the
aura hooks (player-guarded), the equipment observer, and the spell learn/
unlearn writers (0x4B25B0 / 0x4B2C50) -- so buffs, gear, and talent respecs
all invalidate instantly. A coarse world-tick recompute remains only as a
backstop against a missed signal.
2026-07-18 03:51:20 -05:00
Brues adba73a6d8 build: stamp PE version resource on the DLL
Wire a Windows VERSIONINFO resource to the existing CLASSICAPI_TAG so the
DLL's file/product version (Explorer -> Properties -> Details, and
GetFileVersionInfo) matches the CLASSIC_API_VERSION Lua global. Both derive
from the vMAJOR.MINOR.PATCH tag; an untagged dev build gets the 9999.99.99
"newer than everything" sentinel.

Enables the RC language, keeps the tag's major/minor/patch components that
were previously discarded after the integer math, and configure_file's a
version.rc into the build. The resource lands in .rsrc, untouched by the
.rdata/.pdata section merges.
2026-07-17 15:39:04 -05:00
Brues d09137cae0 player: add C_PlayerInfo Get{Name,Class,Race,Sex} / IsConnected(playerLocation)
The PlayerLocation-taking C_PlayerInfo accessors. Resolve the location to a
unit token - unit locations use their token, GUID locations via
Unit::Identity::TokenFromGUID (while the GUID has a live token) - then:

- GetName / GetSex / IsConnected tail-call the engine's Script_UnitName /
  Script_UnitSex / Script_UnitIsConnected (the GetFactionInfoByID
  forward-the-return pattern), reusing all vanilla unit logic. GetSex must go
  through the engine because the raw UNIT_FIELD_BYTES_0 gender byte is 0/1
  while the API reports 2/3. IsConnected defaults to the local player when
  called with no location.
- GetRace / GetClass read UNIT_FIELD_BYTES_0 for the numeric ids vanilla's
  UnitRace / UnitClass don't return (login-time mirror globals for "player",
  else the descriptor bytes); GetClass resolves className / classFile from
  ChrClasses.dbc like C_CreatureInfo.GetClassInfo. classID/raceID round-trip
  with C_CreatureInfo.

Only the unit and guid location kinds resolve on 1.12; the chat/who/BG/
community/voice kinds return nil. New file - player/Info.cpp is the separate
NameCache/GetPlayerInfoByGUID module. Adds the three Script_Unit* offsets
from raw_globals.txt.
2026-07-17 01:20:01 -05:00
Brues 5721fb65a7 addon: add PlayerLocation / PlayerLocationMixin
Backport the modern PlayerLocation parameter object (Blizzard_ObjectAPI) - a
lightweight descriptor wrapping one way to identify a player (GUID, unit
token, chat line, /who index, battlefield-score index, ...). Pure table
bookkeeping like the existing ItemLocation mixin, so ported addon code can
construct and inspect it unchanged.

The GUID / unit / chatLine / whoIndex / battlefieldScore kinds map to real
1.12 concepts; community / voice / Battle.net are kept as harmless data
holders so the mixin matches retail exactly. The only two methods that reach
into systems 1.12 lacks - IsValid (Club) and IsBattleNetGUID (account info) -
are guarded so they degrade gracefully instead of erroring on the missing
namespaces.
2026-07-17 01:08:43 -05:00
Brues 3afd403eae container: add C_Container.HasContainerItem
Classic Era addition (present in the 1.15.x client, absent in 5.4.8) — a
plain occupancy check for a bag slot. Occupancy sibling of
GetContainerItemID: resolves (bagIndex, slotIndex) the same way and returns
whether the CGItem is non-null. Presence only, so it reports true for a
just-looted item even before its static data caches. Returns false for
empty slots and out-of-range indices.
2026-07-17 00:37:23 -05:00
Brues e1030213d3 container: add C_Container.CalculateTotalNumberOfFreeBagSlots
Sum of free slots across the player's general-purpose bags (backpack +
equipped bags 0..4 with BagFamily 0), matching FrameXML's implementation.
Reuses the module's existing ResolveBagInfo (slot count + family) and
CountFreeSlotsInBag, so it's just their sum with the family == 0 filter.

Same sparse-BagFamily caveat as GetContainerNumFreeSlots: vanilla server
data leaves most bags' family field at 0, so specialty bags retail would
exclude get counted here - consistent with the per-bag values it sums.
2026-07-16 23:30:02 -05:00
Brues c1cf437bf8 item: route all local player resolvers through Unit::Identity
Nine modules each rolled their own ResolvePlayer / PlayerInvMgr helper on the
throwing FUN_RESOLVE_UNIT_TOKEN("player"). Delete them all and route through
the canonical non-throwing Unit::Identity::PlayerObject(), plus a new
Unit::Identity::PlayerInventoryManager() (PlayerObject + inventory-manager
offset, mirroring the existing PlayerDescriptor accessor).

Verified equivalent by disassembly: FUN_RESOLVE_UNIT_TOKEN is TokenToGUID ->
FUN_OBJECT_RESOLVE_BY_GUID, the same object-manager lookup PlayerObject()
performs, differing only in a type-mask the player object passes either way.
Callers therefore get the identical CGPlayer (and inventory manager) but
non-throwing - null pre-world instead of a raised Lua error. That also makes
item/Location's equipment resolver safe to call outside a Lua callback (e.g.
the C_NewItems WorldTick bag scan), where the token resolver could have
raised.

Migrated: item/Count, item/AverageLevel, item/Swap, item/Location,
player/CanUseItem, spell/Cancel, equipmentset/Data, equipmentset/Locations,
merchant/Frame. debug/Probe keeps its own (deliberately standalone).
2026-07-16 23:17:24 -05:00
Brues 07a91feff0 item: add C_NewItems (new-item glow tracking)
Backport the modern C_NewItems system - IsNewItem / RemoveNewItem /
ClearAll - flagging items freshly added to bags as "new", cleared once
acknowledged. Vanilla has none of the machinery (no DBC, no server data),
so it is pure client-side bookkeeping, done entirely in C++ like retail.

Newness is keyed on each item's instance GUID (read off the CGItem), so a
flag survives the item being moved between slots - impossible for a Lua
addon, which can only track by (bag, slot). Bags 0..4 only; equipment and
bank are out of scope, matching retail.

The feed is event-driven, not polled: it subscribes to Bag::UpdateDelayed
(which co-hooks the engine's three BAG_UPDATE fire sites), so a bag rescan
runs only on frames where a bag actually changed. A one-time baseline taken
~1.5s after login (re-armed on character switch) keeps items owned at login
from being flagged. BAG_NEW_ITEMS_UPDATED fires when the set changes.

Consolidations along the way:
- New Bag::UpdateDelayed::AutoSubscribe exposes the authoritative
  "a bag changed this frame" signal as a C++ subscription.
- New Item::Location::ContainerInventory factors the CGContainer -> its
  inventory (vtable +0x10) dispatch hand-rolled in item/Count,
  item/AverageLevel, and equipmentset/Locations; all now share it.
- New Item::Location::EquippedBagInventory (equipped bag -> inventory) plus
  the FUN_GET_EQUIPPED_BAG_GUID / OFF_CONTAINER_GET_INVENTORY offsets.
- NewItems resolves the player via the shared Unit::Identity::PlayerObject.
2026-07-16 22:54:45 -05:00
Brues 88ea4356a0 creature: add UnitCreatureTypeID + C_CreatureInfo type lookups
Raw CreatureType id (CreatureType.dbc row: 1=Beast … 11=Totem), the
counterpart to the family additions:

  UnitCreatureTypeID(unit)              -> id, nil if none
  C_CreatureInfo.GetCreatureTypeInfo(id) -> { id, name }
  C_CreatureInfo.GetCreatureTypeIDs()    -> ascending id array (1..11)

UnitCreatureTypeID calls the engine's own type resolver at 0x00605570
(Script_UnitCreatureType's inner helper) directly — it handles all three
engine paths (display-override, creature-cache +0x18, player-race
ChrRaces+0x24), so it matches UnitCreatureType for every unit kind
(players resolve to Humanoid). The C_ lookups read CreatureType.dbc
(records 0x00C0DE2C, count 0x00C0DE30, name +0x04).

Also documented that 0x00605570 is really the creature-type resolver
(new canonical alias FUN_UNIT_CREATURE_TYPE); the existing
FUN_UNIT_PET_MINION_CLASS name is a historical label — Pet.cpp's
"!= 1" test works because it is effectively "is this a Beast (type 1)":
hunter pets are Beasts, warlock minions are Demons (3). Verified
in-game: target -> 7 Humanoid, IDs[8] -> 8 Critter, round-trips.
2026-07-16 21:20:47 -05:00
Brues 50909ce440 creature: add C_CreatureInfo.GetFactionInfo(raceID)
The by-raceID form of vanilla's UnitFactionGroup, returning
{ name (localized), groupTag (english "Alliance"/"Horde") } for a race
with no unit required. Mirrors the player branch of Script_UnitFactionGroup
(0x00516630) exactly: ChrRaces[race]+0x08 -> FactionTemplate id ->
FactionTemplate[id]+0x0C group mask -> scan FactionGroup.dbc for the row
whose bit the mask sets and whose localized name is non-empty (the
non-empty test is how the engine skips the always-set "Player" bit and
the nameless "Monster" row to land on Alliance/Horde). nil for
non-numeric / non-positive / unknown race or a race with no named group.

Every field offset ground-truthed against ChrRaces/FactionTemplate/
FactionGroup .dbc files. FactionGroup is stored contiguously (base +
i*0x30, direct field reads), so it's iterated by hand rather than via
DBC::Record. Its records-base/count globals (0x00C0DD5C / 0x00C0DD60)
are taken from the disassembly, which is authoritative over DBCs.md's
standard-shape tabulation for this table (0x00C0DD64 / 0x00C0DD68) --
verified in-game: race 1 -> Alliance, race 2 -> Horde.
2026-07-16 21:11:04 -05:00
Brues d48d003828 creature: add C_CreatureInfo.GetCreatureFamilyInfo / GetCreatureFamilyIDs
Retail backports over CreatureFamily.dbc (records 0x00C0DE7C, count
0x00C0DE80 — the globals Script_UnitCreatureFamily already indexes), on
the existing C_CreatureInfo table:

  GetCreatureFamilyInfo(id) -> { id, name, iconFile }
  GetCreatureFamilyIDs()    -> ascending array of populated family ids

Localized name at record +0x20 (via LocalizedField), icon at +0x44 (via
StringField). GetCreatureFamilyIDs skips the sparse unused rows
(10/13/14/22/...); each element round-trips with GetCreatureFamilyInfo.

Faithful deviation: retail's iconFile is a numeric fileID, but vanilla's
DBC stores the icon as a texture-path string, so iconFile is a string
(usable directly with SetTexture) and "" for families with no icon
(warlock pets). Verified in-game: 27 -> Wind Serpent + icon path, 15 ->
Felhunter + "", IDs array sparse, unused id 10 -> nil.
2026-07-16 21:02:01 -05:00
Brues d51f5f72a9 unit: add UnitCreatureFamilyID(unit)
Extension exposing the numeric CreatureFamily id (CreatureFamily.dbc
row) for a unit, the value addons want for stable checks — stock
UnitCreatureFamily only returns the locale-dependent display name.

It's the same id the engine's Script_UnitCreatureFamily (0x0051A310)
resolves internally: its family helper FUN_006055e0 returns
[unit+0xB30] ? [row+0x1C] : 0, then maps it through CreatureFamily.dbc
for the name. We stop at the id. Resolves the token via the same
FUN_RESOLVE_UNIT_TOKEN, returns nil for family 0 (players, non-beast
NPCs) and unsynced/unresolvable units — matching UnitCreatureFamily.
Shares UnitSubName's +0xB30 creature-cache read path. Verified in-game:
target (cat) -> 2, targetpet -> 2.
2026-07-16 20:52:31 -05:00
Brues 04efd4caf1 input: reconcile modifier state on focus regain
MODIFIER_STATE_CHANGED never fired for a modifier released while WoW was
in the background: WM_KEY* messages are only delivered to the focused
window, so the WH_GETMESSAGE hook never saw the release and the cached
bit stayed stuck down (also leaving IsLeft/RightShiftKeyDown etc. wrong).

Add a WH_CALLWNDPROC thread hook to catch WM_ACTIVATEAPP (sent, not
posted, so invisible to WH_GETMESSAGE). On app activation, resync the
cached 6-bit mask from GetAsyncKeyState (global physical key state,
unaffected by focus), firing MODIFIER_STATE_CHANGED for any bit that
drifted while WoW was away. Both the keyboard path and the resync now
funnel through a shared SetBit helper so the "only transitions fire"
invariant holds regardless of source.

Caveat (documented): the engine's native IsShiftKeyDown/IsControlKeyDown/
IsAltKeyDown bottom out at synchronous GetKeyState and share the blind
spot; they are not reconciled here — only ClassicAPI's L/R functions and
the event reflect the corrected state.
2026-07-16 20:18:43 -05:00
Brues 329d6b75ba creature: add C_CreatureInfo.GetRaceInfo / GetClassInfo
Retail backports over ChrRaces.dbc / ChrClasses.dbc, on the existing
C_CreatureInfo table. By-id lookups (no unit token needed, unlike
UnitRace/UnitClass) returning the localized name plus the non-localized
file token that round-trips with the unit APIs:

  GetRaceInfo(raceID)   -> { raceName, clientFileString, raceID }
  GetClassInfo(classID) -> { className, classFile, classID }

Reuses the already-verified DBC offsets (OFF_CHRRACES_* / OFF_CHRCLASSES_*),
StringField for the token and LocalizedField for the name. nil for
non-numeric / non-positive / unknown ids. Verified in-game: race 4 ->
Night Elf/NightElf, class 1 -> Warrior/WARRIOR, unknown id -> nil.
2026-07-16 18:32:35 -05:00
Brues 6a677ce447 taxi/map: capital city areaIDs + C_Map.GetMapAreaIDs
Taxi areaID resolution now tries the node's LOCATION part first
("Orgrimmar" in "Orgrimmar, Durotar") -- accepted only when it's a
mapped area whose WorldMapArea rect contains the node -- then the zone
suffix, then the geometric resolver. Capitals thus pin on their own city
map (Orgrimmar 1637, Undercity 1497) instead of the surrounding region,
while normal nodes (location is an unmapped subzone) still resolve to the
outdoor zone. Map::Area::PercentInZone is now containment-checked so a
candidate zone is taken only if it actually holds the point.

Add C_Map.GetMapAreaIDs() -> { [mapName] = areaID } from WorldMapArea:
the missing bridge (vanilla has no GetCurrentMapAreaID) for resolving a
browsed city/instance map -- which GetMapZones() doesn't enumerate -- to
its zone id. Keys on the WorldMapArea name (matches GetMapInfo()'s dir
for nearly all maps; a few misspelled Blizzard folders like "Ogrimmar"
differ, documented).

Verified in-game: Orgrimmar/Undercity flight masters pin on their city
maps; GetMapAreaIDs()["Orgrimmar"] = 1637.
2026-07-16 18:06:55 -05:00
Brues f6f88ab4ee taxi/map: accurate zone resolution + reachable flag
Zone assignment (Map::Area::ZonePercent, shared by GetTaxiNodesForMap
and GetAreaTriggerInfo) chose among overlapping WorldMapArea bounding
boxes by smallest rect, mis-assigning border points. Now resolve by the
zone whose DRAWN LANDMASS the point sits on -- WorldMapOverlay hit rects,
the runtime analog of an ADT area-grid lookup -- tie-broken by how deep
inside an overlay the point is (a node deep in its own zone's overlay
beats one clipping a neighbor's edge). Falls back to most-interior
bounding box when on no overlay. Fixes Ratchet, Un'Goro, Nijel's Point.

For taxi specifically, resolve areaID from the node's own name suffix
("..., Western Plaguelands" -> AreaTable, exact then word-prefix) --
authoritative, and right at borders geometry can't separate (Chillwind
Camp -> WPL, not the Alterac box it sits in). New Map::Area::PercentInZone
projects the position into the named zone; geometric resolver remains the
fallback and the area-trigger path.

Add a `reachable` field: a flight path leads to the node (in-degree > 0).
false marks departure-only nodes reachable only by other means -- druid
Teleport (Nighthaven, Moonglade) or a boat dock (Stormwind Harbor) -- so
a consumer can hide them from a "where can I fly" map without a hardcoded
druid guess. BuildTaxiGraph tracks endpoint + destination sets in one pass.

Verified in-game: Nijel's->Desolace(405), Marshal's->Un'Goro(490),
Ratchet->Barrens(17), Chillwind->WPL(28).
2026-07-16 16:44:58 -05:00
Brues 17c928028e taxi: GetTaxiNodesForMap() with no arg returns all continents
Previously no-arg meant the currently-viewed continent; make it return
every flight master on every continent instead -- a one-call flight DB.
A numeric mapID still filters to that continent. Each entry already
carries its own mapID, and the mount + TaxiPath-endpoint filters apply
uniformly. Verified: no-arg 97, GetTaxiNodesForMap(0) 48.
2026-07-16 14:20:41 -05:00
Brues a47f38417f taxi: add C_TaxiMap.GetTaxiNodesForMap / GetAllTaxiNodes
GetTaxiNodesForMap(mapID) reads TaxiNodes.dbc: real flight masters on a
continent, faction-tagged, discovered or not -- the static DB pfQuest's
pfDB.meta.flight wants. Non-flight rows are filtered out: a node must
have a flight mount (horde @+0x38 / alliance @+0x3C -- drops transports/
boats/zeppelins) AND be a TaxiPath.dbc endpoint (drops Northshire Abbey,
spurious duplicate hub rows, standalone markers with no connecting
path), plus a guard for Blizzard's lone "Generic, World target"
placeholder. Returns retail nodeID/name/faction/position (continent
0-1) + ext mapID/x/y/z and derived areaID/mapX/mapY (zone-relative).

GetAllTaxiNodes([uiMapID]) wraps the open flight master's live node
list (VAR_TAXI_NODE_ARRAY stride 0x20: slot+0 = TaxiNodes record ptr,
+0x04/+0x08 = flight-map x/y; count VAR_TAXI_NODE_COUNT; type via
FUN_004dc4e0): slotIndex (TakeTaxiNode), name, nodeID, state
(Enum.FlightPathState). Empty when no taxi map is open.

Registers Enum.FlightPathFaction / Enum.FlightPathState (retail values).
Extracts the zone-percent projection into shared Map::Area::ZonePercent
+ adds ContinentPercent; refactors AreaTriggers onto ZonePercent.
Verified: EK 48 real masters (Northshire/EPL/transports gone), Stormwind
Alliance / Undercity Horde, continent position matches projection; live
24 nodes with Stormwind state=Current.
2026-07-16 14:00:18 -05:00
Brues 1282e3f6db map: add C_MapExplorationInfo explored/unexplored map textures
GetExploredMapTextures(areaID) backports the retail (9.0-era) call:
only overlays the local player has discovered. GetUnexploredMapTextures
is the ClassicAPI-extension complement (the reveal-over-fog pieces); its
inverse, C_Map.GetMapOverlays, still returns all overlays.

Refactor the overlay walk into a shared Map::Overlays::PushZoneOverlays
with a Filter {All, Explored, Unexplored}; GetMapOverlays is now the
All wrapper. "Explored" is computed per-areaID from the player's
explored-areas bitfield ([player+0xE68]+0xE6C, indexed by AreaTable
AreaBit +0x0C, gated by +0x28) -- mirrors the engine's discovered-
overlay rebuild FUN_004a67a0 -- so the areaID arg works for any zone,
not just the current view. Also add a fileDataIDs field (ordered tile
paths, retail's field name) to every overlay entry.

New offsets: OFF_AREATABLE_AREA_BIT, OFF_AREATABLE_EXPLORE_GATE,
OFF_PLAYER_EXPLORED_BITS. Verified: Elwynn explored(10) + unexplored(2)
== all(12).
2026-07-16 02:25:10 -05:00
Brues 4e4fad9196 map: add C_Map.GetAreaInfo / GetAreas
Surface AreaTable.dbc's localized name column. GetAreaInfo(areaID) is
the retail backport -- localized name for one zone/subzone id, nil for
bad input / no row. GetAreas() is an extension: the full { [areaID] =
name } map (empty-name rows omitted, round-trips with GetAreaInfo), the
piece name databases need for name->id / reverse search. Same "surface
the hidden DBC" pattern as GetAreaTriggers / GetMapOverlays.

AreaTable.dbc is a client DBC (always loaded, synchronous, localized),
so no WDB cold-cache concerns. Uses existing VAR_AREATABLE_* /
OFF_AREATABLE_NAMES wiring; no new offsets. Verified: (12) Elwynn
Forest, (9) Northshire Valley, GetAreas()[12] Elwynn Forest.
2026-07-15 23:48:15 -05:00
Brues 67063876da spell: add C_SpellBook.GetSkillLineRank / GetSkillLineName
GetSkillLineRank(skillLineID) returns the local player's curRank,
maxRank, modifier for a SkillLine.dbc id, or nil if unlearned -- keyed
by id directly instead of forcing addons to map id -> localized name and
string-match GetSkillLineInfo's by-name, by-position walk. Resolves the
id to the player's skill slot via FUN_SKILL_LINE_TO_SLOT, then reads the
CGPlayer +0xE68 skill table (the storage Player::CanUseItem's
require-skill gate already uses). GetSkillLineName(skillLineID) is the
id -> localized name half (pure SkillLine.dbc read, learned or not).

Both live in the existing Spell::SkillLine module; no new offsets.
Verified: Enchanting(333) 171/225/15, Tailoring(197) 261/300/0,
name(182)=Herbalism, unlearned line -> nil.
2026-07-15 23:02:42 -05:00
Brues b34368ef14 map: expose overlay hit rect in C_Map.GetMapOverlays
Each overlay now carries hitRectTop/Left/Bottom/Right (WorldMapOverlay.dbc
+0x34..+0x40) -- the tight clickable landmass bounds in world-map canvas
px (~1002x668), the subzone-center source map addons scrape into their
zone tables. Verified: areaID 12 overlay 8 (NorthshireValley, areaID 9)
-> hitRect 164/400/388/617.

Also stop dropping texture-less rows: a row with an areaID + hit rect but
no texture now appears with textureName == "", zero size, and an empty
tiles table (ipairs-safe), instead of being skipped. No-op on stock/Octo
data (every overlay has a texture) but matches the schema and the "every
overlay of a zone" contract.
2026-07-15 22:07:35 -05:00
Brues 4983c9fd83 map: expose overlay areaIDs in C_Map.GetMapOverlays
Each overlay table now carries areaID (primary AreaTable id revealed,
first nonzero) and areaIDs (the full nonzero list -- WorldMapOverlay.dbc
areaID[4]; 52 of 707 overlays span 2-3 subzones). Lets consumers map an
overlay to its subzone(s) / exploration state. Verified: overlay 1 of
areaID 85 -> areaID 157.
2026-07-15 21:30:19 -05:00
Brues 9e5114141e map: add C_Map.GetMapWorldSize; extract shared Map::Area resolver
Backport the retail C_Map.GetMapWorldSize (9.0): return a zone's world
size in yards as width, height, read from the WorldMapArea.dbc loc rect
(width = locLeft - locRight east-west, height = locTop - locBottom
north-south). Takes an AreaTable areaID, or defaults to the world map's
current view like GetMapOverlays. Verified: (85) -> 4518.75, 3012.5.

Extract the two WorldMapArea row resolvers (areaID -> row, current view
-> row) out of map/Overlays.cpp into a shared Map::Area helper; both
GetMapOverlays and GetMapWorldSize key off the same rows, so the two
ways of naming a zone now live in one place.
2026-07-15 21:14:03 -05:00
Brues 6be25d78e0 map: add C_Map.GetAreaTriggerInfo / GetAreaTriggers
Expose AreaTrigger.dbc (517 static trigger volumes: subzone-entry /
exploration / teleport), which the client loads but never surfaces to
Lua -- the reason map addons ship hand-scraped trigger tables. Same
"read the hidden DBC" pattern as C_Map.GetMapOverlays.

Each trigger returns both the authoritative raw geometry (mapID, world
x/y/z, radius, isBox + box length/width/height/yaw) and a derived
consumable form (areaID + mapX/mapY as a 0..100 zone-relative percent)
via the WorldMapArea rect, picking the smallest zone whose rect
contains the point. GetAreaTriggerInfo(id) returns one trigger;
GetAreaTriggers([mapID]) enumerates all, optionally filtered to a map.

Adds the AreaTrigger.dbc record offsets and the WorldMapArea mapID /
loc-rect offsets to Offsets.h.
2026-07-15 20:04:08 -05:00
Brues 06e68d04a8 docs: document C_Item.PickupItem
Add the API.md entry (input shapes, equipment-then-bags search, no-op
conditions, direct-cursor-primitive note) plus its TOC link, and the
README Item-row index entry.
2026-07-15 19:56:25 -05:00
Brues 8bfe0b008c item: EquipItemByName auto-slot uses Item::Cursor::PickupBagItem
Replace the auto-slot path's Script_PickupContainerItem stack-fake
(SetTop + PushNumber x2 + call) with the shared
Item::Cursor::PickupBagItem, which drives the engine's cursor primitive
directly -- the same one C_Item.PickupItem uses. The ClearCursor at the
top still runs first, so PickupBagItem's empty-cursor guard is satisfied;
bail if the pickup didn't take (locked item / busy cursor) rather than
auto-equipping nothing. Drops the now-unused ScriptFn_t typedef.

FUN_SCRIPT_PICKUP_CONTAINER_ITEM now has no callers -- the Script-pickup
stack-fake is gone from the codebase. Explicit-dstSlot path (atomic
FUN_INVENTORY_SWAP) is unchanged. Verified in-game (auto-slot equip by
name and by id).
2026-07-15 17:35:42 -05:00
Brues e9c2e7416a item: add C_Item.PickupItem, via direct engine cursor primitives
C_Item.PickupItem(itemInfo) picks the matching item up onto the cursor.
itemInfo is an itemID / "item:NNN" / link / name (same input family as
UseItemByName / EquipItemByName): resolved via Item::Arg::Resolve and
found by Item::Location::FindByArg across equipment (1..19, checked first)
and bags (0..4) using the shared MatchesArg predicate (itemID, or the
decorated name for a name arg). An equipped match is lifted off the
paperdoll; a bag match off the container. Verified in-game (bag + equipped,
by id and by name).

Drives the engine's cursor-pickup primitives DIRECTLY rather than the Lua
Script_Pickup* state-machine wrappers (no faking the Lua stack), via a new
shared Item::Cursor:
  - PickupEquipmentSlot -> FUN_004C7300 (self-contained; own guards)
  - PickupBagItem       -> FUN_00494B60, replicating the two guards the
    Script wrapper applies (empty cursor + unlocked item) and the
    post-pickup source lock. The empty-cursor check reuses a new shared
    Cursor::Info::HasItem() (the same cursor-GUID globals GetCursorInfo
    reads), rather than duplicating it.

Supporting consolidation in Item::Location:
  - ResolveBagSlotDetail exposes the container object + linear slot the
    cursor primitive needs; ResolveBagSlot now delegates to it.
  - FindByArg (equipment-then-bags, MatchesArg) reuses FindByArgInBags for
    the bag half; FindByItemID is now its itemID-only specialization.

C_EquipmentSet.UseEquipmentSet was considered but already uses the atomic
FUN_INVENTORY_SWAP (no cursor). EquipItemByName's auto-slot path still uses
the Script wrapper; migrating it to Item::Cursor::PickupBagItem is a
follow-up.
2026-07-15 17:27:36 -05:00
Brues 6641e5ac13 item: add C_Item.IsConsumableItem (+ global IsConsumableItem)
Returns true if an item is a consumable: item class Consumable (0), or
inventory type INVTYPE_AMMO (24) / INVTYPE_THROWN (25). Registered as both
the namespaced C_Item form and the bare global, like IsUsableItem.

Definition established by decoding 3.3.5's Script_IsConsumableItem
(0x005173E0) then verifying the surviving contract on a modern client:
3.3.5 walked the item's on-use spells and returned true for any with a
real effect (which would include on-use trinkets), but that heuristic did
NOT survive -- an on-use trinket with a numeric Use: effect (Talisman of
Ephemeral Power) returns false on modern. It's a plain class/ammo check.
Verified in-game on our client, matching modern exactly: potion / bandage
/ Faintly Glowing Skull (all class 0) and Rough Arrow (Ammo) -> true;
Hearthstone, Talisman, plain armor -> false.

itemID / "item:NNN" / link input (names -> false, no vanilla name->ID
map); uncached -> false with no async load, same contract as
C_Item.IsEquippableItem. Documented in API.md (+ TOC) and the README
Item-row index.
2026-07-15 16:35:43 -05:00
Brues db1f00e0a3 item: add C_Item.IsItemInRange, via a shared Spell::Range core
C_Item.IsItemInRange(item, targetUnit) resolves the item to its on-use
spell (Item::Spell::OnUseSpellIDForItemID) and runs the same geometric
range test as C_Spell.IsSpellInRange: true / false in-or-out of range,
nil when the check doesn't apply (no on-use spell, a rangeless one, or an
unresolvable item/unit). Matches retail, which also returns nil for items
with no range restriction. item accepts itemID / "item:NNN" / link (names
aren't resolvable in vanilla -> nil). Range-only, ignoring LoS/faction,
like IsSpellInRange.

The range predicate SpellIDHasRange was about to become its fourth copy,
so extract the shared core into Spell::Range (SpellIDHasRange +
PlayerVsUnit, returning 1/0/-1). C_Spell.IsSpellInRange and
C_Item.IsItemInRange are now thin Lua wrappers over PlayerVsUnit, and
C_Spell.SpellHasRange / SpellHasRange call the shared SpellIDHasRange --
range logic single-sourced.
2026-07-15 15:59:41 -05:00
Brues 82062309a9 docs: item name/GetItem/by-name APIs return the decorated (suffixed) name
Follow-up to the random-suffix work (aa0279a, e8a9003, 2a218a0). API.md
still described the old base-name behavior in five places; update them:

- GameTooltip:GetItem() example: name is now the decorated name that
  agrees with the returned link ("Superior Cloak of the Eagle").
- C_Item.GetItemName: split the two forms -- location returns the
  decorated name (live instance, via the engine name builder), ByID
  returns the base name (an itemID has no instance/suffix).
- C_Item.IsEquippedItem / EquipItemByName / UseItemByName: name matching
  is against the decorated name (a suffixed item matches its full name,
  not the base), noting the one shared predicate behind all three.

Left the C_Item.GetItemData return-table `name` row as base m_name[0] on
purpose: that table is a static itemID-keyed record dump (same contract
as GetItemInfoInstant, which doesn't decorate either).
2026-07-15 15:36:54 -05:00
Brues 2a218a0a76 item: match decorated (suffixed) name via shared MatchesArg predicate
IsEquippedItem(name) and the bag find-by-name (FindByArgInBags, behind
UseItemByName/EquipItemByName/UseAtCursor) compared the caller's string
against the base ItemStats m_name[0], so a random-suffix item ("Foo of
the Owl") only matched when queried by its base name ("Foo"). The modern
client does the opposite -- verified in-game on both the modern client
and ours:

  IsEquippedItem("Iridium Chain")               -> false
  IsEquippedItem("Iridium Chain of the Owl")    -> true
  IsEquippedItem("iridium chain of the owl")    -> true  (case-insensitive)
  IsEquippedItem(12022)                         -> true  (itemID)

Match the decorated display name instead, via the engine name builder
(Item::Link::NameFromCGItem), which falls back to the base name for
unsuffixed items so plain items still match.

The match predicate was duplicated inline in both call sites -- which is
why this took two edits. Consolidate it into a single
Item::Location::MatchesArg(cgItem, resolvedArg): itemID-compare when
arg.itemID > 0, else case-insensitive decorated-name compare. Both
IsEquippedItem and FindByArgInBags now delegate to it, so the full chain
is single-sourced (Item::Arg parses input -> MatchesArg decides the match
-> NameFromCGItem / ID::FromCGItem supply the comparands). Also drop a
now-unused <string.h> from Equipment.cpp and fix the stale m_name[0] doc
on FindByArgInBags.
2026-07-15 15:31:55 -05:00
Brues e8a9003bf0 item: dress GameTooltip:GetItem() name with random suffix
GameTooltip:GetItem() resolved the CGItem and built the suffixed link via
Item::Link::FromCGItem, but returned the base ItemStats name beside it --
so name and link disagreed ("Iridium Chain" vs "[Iridium Chain of the
Owl]"). The old comment claimed the engine didn't expose the dressed name
as a separate string; it does, via the same builder the link uses.

Extract that builder into a shared Item::Link::NameFromCGItem helper
(next to FromCGItem, wrapping FUN_ITEM_BUILD_INSTANCE_NAME) and use it in
both GetItem and C_Item.GetItemName so the returned name matches the link
and modern behavior. Verified in-game: GetItem() now returns "Iridium
Chain of the Owl" alongside its matching link.

Left the base-name reads that are correct as-is: itemID-only paths (mail,
cursor-by-id, GetItemInfo, equipment-set missing items) have no instance,
and the by-name *matching* in IsEquippedItem / bag lookups compares
against a caller string (a separate semantics question).
2026-07-15 15:13:52 -05:00
Brues aa0279a600 item: decorate C_Item.GetItemName location form with random suffix
The location form of C_Item.GetItemName points at a real item instance,
so its name should carry random-suffix decoration ("... of the Owl") the
way modern WoW does -- but we were reading m_name[0] off the itemID-keyed
ItemStats_C cache, which only holds the base name.

Resolve the location to its CGItem and build the name via the engine's
own per-instance name builder (FUN_005D8BC0): it reads the suffix ID off
the descriptor (+0x98) and formats base + ItemRandomProperties localized
suffix through the engine's ITEM_SUFFIX_TEMPLATE. This is the same
builder FUN_GAMETOOLTIP_BUILD_ITEM_LINK wraps in brackets, so the output
now matches GetItemLink's bracketed name and modern C_Item.GetItemName
exactly (verified in-game: "Iridium Chain of the Owl"). Falls back to the
base ItemStats name (and warms the cache) when the instance build yields
nothing.

GetItemNameByID is unchanged -- an itemID has no instance, so base name
only is correct.
2026-07-15 15:06:04 -05:00
Brues a754d1ba22 Update TODO.md 2026-07-15 01:22:14 -05:00
Brues d55877649f item, unit: drop hand-rolled unit-token grammar mirrors
FUN_TOKEN_TO_GUID (0x00515970) is a pure parser: it returns 0 for any
input it doesn't recognize and never raises -- verified from the
disassembly (plain stack frame, no assert/SEH prologue; every
unknown-input path is xor eax,eax; ret). Both call sites had mirrored
the engine's token grammar by hand to pre-screen input, on the mistaken
belief this function throws (it was conflated with its sibling
FUN_RESOLVE_UNIT_TOKEN 0x00515940, which does throw).

- item/Use.cpp UseItemByName: delete LooksLikeToken / MatchBase /
  SkipTargetSuffixes / HasPrefix; just call FUN_TOKEN_TO_GUID and let it
  return 0 for non-tokens.

- unit/Flags.cpp UnitIsInMyGuild: delete LooksLikeKnownToken / HasPrefix
  / AllDigits. Resolve the input to a GUID via FUN_TOKEN_TO_GUID, then
  resolve GUID -> object via the non-throwing FUN_OBJECT_RESOLVE_BY_GUID
  (unit|player mask) for the fast guild-key compare, and GUID -> name via
  the NameCache for the roster fallback. This avoids the throwing
  resolver entirely, and -- because the token->GUID step goes through
  our TokenExtensions hook -- now supports focus / nameplateN, which the
  old grammar mirror silently treated as literal names. Matches what
  3.3.5's Script_UnitIsInMyGuild does (resolve to a GUID first).

No grammar to keep in sync with the engine anymore. Behavior otherwise
unchanged (self, guildmate/other-guild target, NPC, OOR raid member,
literal name, empty slot all verified case-by-case).
2026-07-14 16:29:14 -05:00
Brues f55779f87e item: fix UseItemByName ignoring the unit target for all but current target
UseItemByName resolved the unit token (arg 2) AFTER FindByArgInBags,
which stomps the Lua stack (clears it and pushes bag-slot numbers for
PackBagSlot). So ResolveUnitGuid read a leftover slot number instead of
the token: IsString failed, the GUID came back 0, and the engine fell
back to its default target. That default is the player's current target
for a targeted-use item, so "target" appeared to work while "focus",
"party1", "mouseover", etc. silently did nothing useful.

Resolve the target GUID before the bag walk (as the sibling UseAtUnit
already does). ResolveUnitGuid only reads slot 2 and resolves a C
string -- no stack stomp -- and leaves arg.name (slot 1) intact for
FindByArgInBags; the GUID is a plain value by the time the stack is
blown away.
2026-07-14 15:59:07 -05:00
Brues 91e88d768a unit: add UnitInLineOfSight(unit)
ClassicAPI extension (retail has no such global): true if the player
has clear LoS to unit, false if world geometry blocks it, nil when the
check can't apply (absent/unresolvable token, or non-unit object).

Traces a ray between the two units through the client's world-collision
core CWorld::Intersect (0x672170, verified in-binary: __fastcall(start,
end, unused, hitOut, tOut, flags), tail-calls the real intersect
FUN_0069BFF0). Flags 0x100111 = terrain + WMO (0x100171 also tests M2
doodads but crashes in some dungeons; matches vanilla server LoS which
ignores doodads). Endpoints are raised by each unit's collision-box
height (CMovement+0xB4) so foot-to-foot rays don't false-block on
terrain, with a two-pass level/look-up trace for height mismatches and
a 150yd guard against a long-segment crash.

Mirrors UnitXP_SP3's proven implementation (same VA, flags, guard, and
two-pass logic) but native, so it works with or without that addon --
we call the intersect rather than hooking it, and our flag isn't one
UnitXP_SP3's detour acts on. Gated on object type (unit/player) so it
never reads CMovement off a GameObject.

Adds FUN_CWORLD_INTERSECT, OFF_CMOVEMENT_COLLISION_BOX_HEIGHT,
OFF_CGOBJECT_TYPE_ID, OBJECT_TYPE_UNIT/PLAYER (reuses the existing
OFF_UNIT_MOVEMENT_INFO_PTR = 0x118), plus API.md and README entries.
2026-07-14 15:48:55 -05:00
Brues d358bd9515 spell: add C_Spell.IsSpellInRange(spellIdentifier, targetUnit)
Returns true/false for in/out of range, nil when the check does not
apply (rangeless spell, or unresolvable spell/unit). spellIdentifier
accepts a spellID, link, or spellbook name; targetUnit is a unit token.

Backed by the engine's own geometric range core FUN_006E47B0 -- the
same test the action-button range coloring uses (Script_IsActionInRange
to FUN_004E56F0 to FUN_006E4440 to FUN_006E47B0). It derives the
spell min/max range via FUN_006E3480 (which folds in the target's
bounding radius AND applies the range SpellMod op 5, so range-extending
talents/items like Hawk Eye and Nature's Reach count) then compares
center-to-center distance, so the boundary matches the client exactly,
melee and min-range spells included.

We call the pure core rather than FUN_006E4440: that wrapper also gates
on target type and folds range-not-applicable into the same truthy
return as in-range, so it cannot yield a clean true/false/nil. The core
is range-only, matching retail (ignores line of sight; does not reject
wrong-faction targets, documented). Positions are guarded via
Unit::Position::Read before the engine call, which dereferences the
GetPosition result without a null check.

Adds Offsets::FUN_SPELL_RANGE_CHECK (0x006E47B0) with derivation notes,
plus API.md and README entries.
2026-07-14 15:00:28 -05:00
Brues 4ba82e59e4 table: reset getn length counter in table.wipe
table.wipe nil'd every key via lua_next + rawset(nil) but left the
Lua 5.0 length counter untouched. In 5.0 a table's table.insert/getn
length lives out of band from its keys (a t.n field, else a weak
sizes[t] entry in the registry's LUA_SIZES table), so it survived the
clear. After a wipe, getn stayed at its old value and subsequent
table.insert appended past the wiped slots -- t[1] stayed nil. The
3.3.5 (Lua 5.1) twipe this was ported from has no getn legacy, which
is why the ported logic looked complete.

Fix: call luaL_setn(L, 1, 0) after the clear loop. Bound the engine's
luaL_setn (FUN_006f4ea0, verified against 5.0.2; located via
table.insert FUN_007fb6b0) as Game::Lua::SetN.

Repro before: table.insert(t,1); table.insert(t,2); table.wipe(t);
table.insert(t,3) -> getn 3, t[1] nil, t[3]=3.
After: getn 2, t[1]=3, t[2]=4. Verified in-game.
2026-07-14 00:37:19 -05:00
Brues b05c15ffa7 input: evict GetMouseButtonClicked so it reads nil outside a handler
Previously g_lastButton persisted as the last click forever. Modern
WoW returns the button only while a mouse handler is running and nil
otherwise (verified in 3.3.5: GetMouseButtonClicked pushes a
frame-manager field [mgr+0x1234] that is set before a mouse handler
dispatches and cleared after, so it is nil when null).

We cannot bracket the handler the same way: WoW dispatches the
frame-script mouse handlers deferred from the WH_GETMESSAGE pump, so
eviction is time-based via the existing per-frame WorldTick. The
button is still captured on each WM button message; EvictTick clears
it after a couple of quiet ticks with nothing held. A held button
keeps it (OnDragStart still reads it) and it survives the whole frame
its click lands in, so multiple addons hooking one OnClick all see it,
avoiding the multi-reader hole a consume-on-read latch would have.

Verified in-game: value matches the GLOBAL_MOUSE_DOWN button arg inside
a handler, and reads nil once clicks settle.
2026-07-13 23:41:33 -05:00
Brues 4daf6b9364 input: add GetMouseButtonClicked()
Returns the button name of the most recent mouse-button message
("LeftButton"/.../"Button5"), or nil before any click. Rides the
existing WH_GETMESSAGE stream in GlobalMouse that already backs
GLOBAL_MOUSE_DOWN/UP and IsMouseButtonDown, so no engine hook is
needed: g_lastButton is captured on every press/release, and the
Script fn pushes it (null tail-jumps to pushnil for the "no click
yet" case).

The hook runs at message-dequeue, synchronously before the engine
dispatches the click to the Lua handler, so the value reflects the
button of the handler currently running (and is readable from nested
helpers where arg1 isn't in scope). Not cleared between events -- no
"handler ended" signal in the 1.12 stream -- so outside a mouse
handler it returns the last-clicked button rather than nil; documented.
2026-07-13 19:02:51 -05:00
Brues 4c6c9deae6 namecache: share the on-disk cache across accounts per server
Move the persistent name cache from the per-account
WTF\Account\<acct>\<realm>\ClassicAPI_NameCache.txt to a shared
WTF\ClassicAPI\<realmList>\<realm>\ClassicAPI_NameCache.txt, so alts on
different accounts of the same server pool into one file instead of each
rebuilding their own.

Keyed by the realmlist address (unambiguous server identity — can't collide
across unrelated private servers, the same reason CredStore scopes on it)
plus the realm name. Since this path isn't under Account\, WoW doesn't
create it: EnsureParentDirs makes the tree before saving. On first load with
no shared file yet, a pre-existing per-account cache is migrated in (load
old file, mark dirty so the next save lands in the shared location); the old
file is left untouched.

The PersistentNameCacheEnabled / NameCacheScanEnabled toggles stay
per-account in WTF\Account\<acct>\ClassicAPI.txt — each account opts in
independently; only the cache contents are shared.
2026-07-13 12:52:52 -05:00
Brues 983cc3bdff unit: add UnitDistanceSquared
Backport retail's UnitDistanceSquared(unit) -> (distanceSquared,
checkedPosition): the squared world distance from the player to the unit,
plus a flag for whether both positions were readable. Squared because
almost all distance logic is a threshold compare or nearest-unit sort,
neither of which needs the sqrt — which is why retail never shipped a plain
UnitDistance.

Added to the existing Unit::Range module alongside UnitInRange (both now
share one PlayerToUnitDistSq compute off the CGObject::GetPosition vtable
virtual). Center-to-center, self-contained (reads the position in C — no
SuperWoW dependency, and leaves SuperWoW's own UnitPosition untouched).
Verified in-game to match SuperWoW UnitPosition math to float precision.

On a position miss returns (0, false); no self-quirk, so
UnitDistanceSquared("player") is a legitimate (0, true).
2026-07-13 00:23:58 -05:00
Brues 18ac033381 spell: add GetSpellLevelInfo + GetSpellRequiredTargetLevel
Expose the target-level gate for ranked beneficial auras — e.g. Divine
Spirit Rank 1 (14752) can only be applied to a target level >= 20.

- C_Spell.GetSpellLevelInfo(spellID) -> spellLevel, baseLevel, maxLevel
  (raw Spell.dbc level fields; nil for an unknown spell).
- GetSpellRequiredTargetLevel(spellID) (global, plus C_Spell mirror) ->
  the minimum castable target level (0 = no restriction; nil if unknown).

The computed helper mirrors the server's SpellMgr::SelectAuraRankForLevel:
returns spellLevel - 10 only when the spell is a ranked positive aura
(spellLevel > 10, not passive, has a Rank string, and has an APPLY_AURA
effect on a friendly/party/raid target or an APPLY_AREA_AURA_PARTY effect),
else 0. All fields read directly from the client's Spell.dbc.

The explicit MinTargetLevel / MaxTargetLevel fields the server also checks
are server-only columns (absent from the 1.12 client DBC, whose tail is
SpellFamilyName / SpellFamilyFlags / MaxAffectedTargets), so the spellLevel
rule is the only client-readable target-level mechanism.
2026-07-12 23:28:41 -05:00
Brues 81434f7014 aura: evict phantom cache entries on removal and descriptor reconcile
C_UnitAuras' descriptor-drop fallback could surface a "phantom" aura that
was actually gone — enumerated with a spellId but SetUnitAura rendering an
empty tooltip. Two cases, both fixed:

- Owner cancels a buff (e.g. a flask) while dead: the server keeps
  death-persistent auras through death without changing any field, so death
  itself fires no OnAuraRemoved. Any OnAuraRemoved we do receive for one is
  genuine (cancel/dispel/expiry), so always evict the cache entry — including
  death-persistent auras on dead units. Fixes the phantom for the caster and
  nearby observers (both receive the removal packet).

- A buff cancelled while its owner is out of an observer's range sends no
  packet, so the stale entry lingers. Reconcile on return: when a unit's
  descriptor holds >=1 raw aura it's in view and fully synced, so it's
  authoritative — evict any cached entry whose spell isn't in the array
  (Aura::Data::ReconcileCache -> Aura::Source::EvictAbsent, run at the top of
  the fallback path). Reads raw slots so a flag-hidden aura still counts as
  present; skips an empty array (can't tell out-of-range from buffless).

The only residual is a buff cancelled while the owner is still out of range,
which vanilla can't report until they return.
2026-07-12 17:10:27 -05:00
Brues 22605dad64 tooltip: format compare-item percent stats via PERCENTAGE_STRING
Block/dodge/parry chance and crit/hit are native vanilla percentages, so
their compare-tooltip delta read as a bare number ("-5 Block"). Attach the
percent via the locale-aware PERCENTAGE_STRING global so it renders
"-5% Block" without touching any _SHORT label (correct in every locale).

IsPercentStat marks the percent keys; FormatPercent substitutes the value
into PERCENTAGE_STRING's first conversion slot by hand (never feeds the
locale format to snprintf) with a plain "%" fallback. Flat stats (Defense,
Attack Power, Block Value) stay bare; dropped the now-redundant trailing
" %" from the English fallback labels.
2026-07-12 14:23:54 -05:00
Brues 7378e0b128 unit: add UnitIsMinion / UnitIsPet / UnitIsOtherPlayersPet
Player-minion classification for a unit, all owner-based:

- UnitIsMinion(unit): owned by a player (pet/guardian/totem). Primary
  check is the owner GUID, since summoned guardians ("X's Minion") carry
  an owner but not UNIT_FLAG_PLAYER_CONTROLLED; the flag is a fallback.
- UnitIsPet(unit): a player's controllable pet specifically -- owned by a
  player AND the engine's creature-family pet/minion classifier
  FUN_00605570 == 1, the same signal driving the UNITNAME_TITLE_PET vs
  _MINION tooltip label. The GUID can't be used (pets and guardians share
  the 0xF14 prefix) nor can PLAYER_CONTROLLED (a Minion can have it).
  ClassicAPI extension.
- UnitIsOtherPlayersPet(unit): owner is a player other than you; matches
  5.4.8's owner-based Script_UnitIsOtherPlayersPet.

Owner GUID read from CHARMEDBY (+0x10, verified via Script_UnitIsCharmed)
and CREATEDBY (+0x20, verified via the unit title builder FUN_0052FD30).
Verified in-game: Salvatory's Pet is a pet; Jimmyf's/Methl's Minion is a
minion but not a pet.
2026-07-12 03:06:11 -05:00
Brues 94b0545631 player: add C_PlayerInfo.CanUseItem (equip/use requirement gate)
The proficiency/level/class/skill/spell/rep gate that answers "can this
player equip or use this item" -- the tooltip's red-requirement logic,
distinct from IsEquippableItem (fits a slot) and IsUsableItem (on-use
castable). Mirrors the requirement checks FUN_0052B650 inlines:

  1. proficiency  - VAR_PROFICIENCY_TABLE[m_class] & (1<<m_subClass)
  2. RequiredLevel
  3. AllowableClass / AllowableRace
  4. RequiredSkill  - effective rank via FUN_SKILL_LINE_TO_SLOT
  5. RequiredSpell  - spell-knowledge bitmap (crafting specializations
                      like Armorsmith, proficiency spells)
  6. RequiredHonorRank / RequiredCityRank - PvP honor rank + medal mask
  7. RequiredReputation - current standing vs the reaction-min band

Verified in-game: mail boots false (proficiency), Riding mount false
without skill 150, Plans: Lionheart Helm false until Armorsmith learned.
Residual gap: a ranked RequiredSpell known only at a different rank.

Adds OFF_CGPLAYER_HONOR_RANK / OFF_CGPLAYER_PVP_MEDALS.
2026-07-12 01:54:05 -05:00
Brues 243ab37836 tooltip: localize item-compare stat labels via GlobalStrings keys
Compare-tooltip stat deltas now resolve their display label through
_G[key] (the WoW GlobalString), falling back to the built-in English
only when undefined. LabelFor tries _G[key], then _G[key.."_SHORT"],
then the English fallback: primary stats / resistances / CURRENTLY_EQUIPPED
resolve directly, while the rating/regen tokens GetItemStats keys on
(ITEM_MOD_CRIT_MELEE_RATING, ...) — whose own global is a "%s"
description — map to their compact, translatable _SHORT sibling for
display. StatAccum keys are left untouched (the GetItemStats contract,
confirmed against a TBC dump: ratings key on the non-_SHORT token).

The format guard now rejects only real printf conversions (%d/%s/%1$s),
letting a literal "%" unit through.

enUS.lua gains the ITEM_MOD_*_SHORT, ITEM_DELTA_DESCRIPTION and format
keys (native RESISTANCE*/CURRENTLY_EQUIPPED left to the client). The
non-US locales (deDE/esES/frFR/ruRU/zhCN/zhTW) are auto-filled from
Blizzard Classic (1.15) per-locale GlobalStrings; only the custom
BINDING_NAME_AOELOOT stays commented as an enUS fallback.

Fixes #8
2026-07-11 16:40:10 -05:00
Brues a12fff6704 Small refactor for clarity 2026-07-11 16:28:46 -05:00
Brues d747c699f5 Tighten up pfUI HookScript compat
Defer CreateFrame hook application until the updatenotify module loads, rather than applying it globally so it only affects the actionar module
2026-07-11 16:21:43 -05:00
Brues 88d76c04ad item: add IsUsableItem / C_Item.IsUsableItem (on-use usability)
Item analog of IsUsableSpell, returning (usable, noMana) for an item's
on-use ability -- not equippability. Gates on the item having an ON_USE
spell, its use requirements (RequiredLevel, AllowableClass/Race), then
the on-use spell's castability via the engine helper FUN_SPELL_IS_USABLE
(0x006E3D60), which sets noMana on power shortfall.

Shares the on-use spell-slot walk with C_Item.GetItemSpell: promoted
Item::Spell::FindOnUseSpellIDInRecord to the header so both use it
instead of re-deriving the trigger scan.
2026-07-11 14:55:20 -05:00
Brues 47d4b9c660 loot: stable rollID, winnerIdx, FULL_UPDATE dispatch, timestamp, Clear
Bring C_LootHistory closer to the MoP contract and make a UI keying on it
robust across the ring saturating.

- GetItem now returns rollID, itemLink, numPlayers, isDone, winnerIdx,
  timestamp (was itemLink-first, with the winner as a name string). rollID
  is a stable monotonic ID assigned at creation, so addons can key expanded
  / highlighted rows on it instead of the volatile ring index. winnerIdx is
  the winner 1-based player index for GetPlayerInfo, matching MoP; the winner
  is inserted into the roster if their own roll packet never arrived, so it
  always resolves. timestamp is a ClassicAPI extension (GetTime()-comparable
  seconds).
- LOOT_HISTORY_FULL_UPDATE is now actually dispatched (was reserved-only):
  on a new item appearing (roll open) and on ring eviction, fired before the
  granular ROLL_CHANGED / ROLL_COMPLETE.
- Add C_LootHistory.Clear() (ClassicAPI extension) to wipe history and fire
  FULL_UPDATE.
- Factor roll/winner roster insertion into a shared FindOrAddPlayer helper.

Docs updated for the new signature, Clear, and the FULL_UPDATE semantics.
2026-07-10 21:03:51 -05:00
1111 changed files with 187864 additions and 20282 deletions
+1
View File
@@ -10,3 +10,4 @@
*.png binary
*.jpg binary
*.ico binary
*.blp binary
+118 -17
View File
@@ -4,48 +4,149 @@ on:
push:
branches: ['**']
tags: ['v*']
# Manual escape hatch (e.g. when push webhooks are throttled during a
# GitHub Actions incident). Run from the Actions UI:
# - select a `vX.Y.Z` tag ref -> release build of that tag, OR
# - run from a branch and pass `tag: vX.Y.Z` -> release build that
# creates/attaches the release to that tag.
# Leave `tag` blank on a branch run for a plain dev build (artifact).
workflow_dispatch:
inputs:
tag:
description: 'Release tag to build (e.g. v2.0.0). Blank = dev build.'
required: false
default: ''
permissions:
contents: write
jobs:
# Decide which runner the build lands on. `runs-on` is fixed before a job
# starts and a job pointed at an offline self-hosted runner queues forever
# instead of failing over — so we probe first and hand the label down.
pick-runner:
runs-on: ubuntu-latest
outputs:
label: ${{ steps.pick.outputs.label }}
steps:
- name: Probe for an online self-hosted runner
id: pick
env:
# Listing runners needs repo-admin access; the default GITHUB_TOKEN
# does NOT have it. Create a PAT (classic: `repo`; fine-grained:
# Administration → read) and store it as the RUNNER_CHECK_TOKEN
# secret. If the secret is missing, we fall back to windows-latest.
GH_TOKEN: ${{ secrets.RUNNER_CHECK_TOKEN }}
run: |
label=windows-latest
if [ -n "$GH_TOKEN" ]; then
online=$(gh api "repos/${{ github.repository }}/actions/runners" \
--jq '[.runners[] | select(.status=="online") | select([.labels[].name] | index("self-hosted"))] | length' \
2>/dev/null || echo 0)
if [ "${online:-0}" -gt 0 ]; then
label=self-hosted
fi
fi
echo "Selected runner: $label"
echo "label=$label" >> "$GITHUB_OUTPUT"
build:
runs-on: windows-latest
needs: pick-runner
runs-on: ${{ needs.pick-runner.outputs.label }}
outputs:
tag: ${{ steps.ver.outputs.tag }}
is_release: ${{ steps.ver.outputs.is_release }}
# Windows PowerShell 5.1 is always present; the runner's default `pwsh`
# (PowerShell Core) is not installed by default, and `shell: bash` on a
# self-hosted box resolves to the WSL launcher in System32.
defaults:
run:
shell: powershell
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Stamp embedded TOC version
if: startsWith(github.ref, 'refs/tags/v')
shell: pwsh
# Resolve the effective version once so every step below agrees.
# is_release=true when a vX.Y.Z tag is in play (pushed tag,
# dispatched-from-tag, or a `tag` input); the embedded addon's
# `## Version:` and the compiled CLASSIC_API_VERSION are both
# stamped from it at embed/compile time (see cmake/embed_resources.cmake)
# — no source edit.
- name: Resolve version
id: ver
env:
INPUT_TAG: ${{ inputs.tag }}
run: |
$version = '${{ github.ref_name }}' -replace '^v',''
$toc = 'AddOns/!!!ClassicAPI/!!!ClassicAPI.toc'
(Get-Content $toc) -replace '^## Version:.*', "## Version: $version" |
Set-Content $toc
if ($env:GITHUB_EVENT_NAME -eq 'workflow_dispatch' -and $env:INPUT_TAG) {
$tag = $env:INPUT_TAG
} elseif ($env:GITHUB_REF -like 'refs/tags/v*') {
$tag = $env:GITHUB_REF_NAME
} else {
$tag = ''
}
$isRelease = if ($tag) { 'true' } else { 'false' }
Add-Content -Path $env:GITHUB_OUTPUT -Value "tag=$tag" -Encoding utf8
Add-Content -Path $env:GITHUB_OUTPUT -Value "is_release=$isRelease" -Encoding utf8
- name: Configure (tag)
if: startsWith(github.ref, 'refs/tags/v')
run: cmake -B build -A Win32 "-DCLASSICAPI_TAG=${{ github.ref_name }}"
- name: Configure (release)
if: steps.ver.outputs.is_release == 'true'
run: cmake -B build -A Win32 "-DCLASSICAPI_TAG=${{ steps.ver.outputs.tag }}"
- name: Configure (branch)
if: "!startsWith(github.ref, 'refs/tags/v')"
- name: Configure (dev)
if: steps.ver.outputs.is_release != 'true'
run: cmake -B build -A Win32
- name: Build
run: cmake --build build --config Release
# Dev builds carry their own symbols. With the PDB sitting next to the DLL
# the client's crash handler resolves our frames to file and line — a
# tester's log reads `Texture::Mask::PrimIndexed_h+12 (Mask.cpp,246)`
# instead of a bare address — and the map resolves `0001:offset` addresses
# by hand when there is no dump. Both match THIS build and nothing else,
# which is why they travel with it rather than being rebuilt later from the
# same commit. Unlike the release bundle these need no off-putting name:
# the artifact is behind the Actions UI, so whoever downloads it is already
# the audience for symbols.
- name: Upload artifact
if: "!startsWith(github.ref, 'refs/tags/v')"
if: steps.ver.outputs.is_release != 'true'
uses: actions/upload-artifact@v4
with:
name: ClassicAPI-${{ github.sha }}
path: build/Release/ClassicAPI.dll
# Shared parent is build/Release, so all three land at the zip root.
path: |
build/Release/ClassicAPI.dll
build/Release/ClassicAPI.pdb
build/Release/ClassicAPI.map
# A symbol-less artifact looks identical to a good one until someone
# needs a stack out of it, so fail the build instead of warning.
if-no-files-found: error
# Bundle both debug artifacts into one zip so a crash from a shipped DLL
# can be triaged exactly. The PDB gives WinDbg/x64dbg/VS a line-level
# symbolicated call stack from a crash dump; the map resolves the
# `0001:offset` addresses in WoW's ERROR #132 crash log by hand when no
# dump is available. Both match THIS exact DLL build.
# The filename is deliberately off-putting: it is NOT the addon and has no
# value to a normal player. The loud all-caps name keeps them from
# grabbing it by mistake; the tag suffix lets a dev match symbols to the
# exact build. (pdb/map keep their real names inside so the pdb signature
# still lines up with the DLL.)
- name: Package debug symbols for release
if: steps.ver.outputs.is_release == 'true'
run: >
Compress-Archive
-Path build/Release/ClassicAPI.pdb, build/Release/ClassicAPI.map
-DestinationPath build/Release/Crash-Symbols-Use-For-Debugging-${{ steps.ver.outputs.tag }}.zip
-Force
- name: Release
if: startsWith(github.ref, 'refs/tags/v')
if: steps.ver.outputs.is_release == 'true'
uses: softprops/action-gh-release@v2
with:
files: build/Release/ClassicAPI.dll
tag_name: ${{ steps.ver.outputs.tag }}
files: |
build/Release/ClassicAPI.dll
build/Release/Crash-Symbols-Use-For-Debugging-${{ steps.ver.outputs.tag }}.zip
generate_release_notes: true
+3 -1
View File
@@ -45,4 +45,6 @@
# debug information files
*.dwo
CLAUDE.md
CLAUDE.md
/src/embed/AddOns/*/.classicapi-dev
+3
View File
@@ -7,3 +7,6 @@
[submodule "external/tinycbor"]
path = external/tinycbor
url = https://github.com/intel/tinycbor.git
[submodule "external/unordered_dense"]
path = external/unordered_dense
url = https://github.com/martinus/unordered_dense.git
-40
View File
@@ -1,40 +0,0 @@
## Interface: 11200
## Title: !!!ClassicAPI
## Notes: Library to emulate aspects of the modern WoW API on 1.12.1 / Lua 5.0.
## Version: DEV
## Author: Brues
## X-Website: https://github.com/brues-code/ClassicAPI
locales\locales.xml
Compat.lua
Util\Print.lua
Util\Mixin.lua
Util\Color.lua
Util\Constants.lua
Util\String.lua
Util\TableUtil.lua
Util\MathUtil.lua
Util\PixelUtil.lua
Util\FrameUtil.lua
Util\FormattingUtil.lua
Util\TimeUtil.lua
Util\CallbackRegistry.lua
Util\GlobalCallbackRegistry.lua
Util\ColorUtil.lua
Util\ItemLocation.lua
Util\EventUtil.lua
Util\ItemUtil.lua
Util\AddOnCompat.lua
Util\FunctionUtil.lua
Util\CacheUtil.lua
Util\Pools.lua
Util\FrameWatcher.lua
Util\TimedCallback.lua
Util\EquipmentManager.lua
Util\PlayerUtil.lua
Util\SlashCommandsRegistry.lua
Util\LinkUtil.lua
Util\TradeSkillLink.lua
Util\IconDataProvider.lua
Util\GameTooltip.lua
-3
View File
@@ -1,3 +0,0 @@
if not _G then
_G = getfenv(0)
end
-40
View File
@@ -1,40 +0,0 @@
if C_AddOns.DoesAddOnExist('pfUI') then
EventUtil.ContinueOnAddOnLoaded('pfUI', function()
-- pfUI\pfUI.lua redeclares the RAID_CLASS_COLORS object at least 14 times (insane!!)
-- This stops it from replacing all our ColorMixin values
pfUI.UpdateColors = function() end
RAID_CLASS_COLORS = setmetatable(RAID_CLASS_COLORS, { __index = function()
local unknownColor = CreateColor(0.6, 0.6, 0.6)
unknownColor.colorStr = unknownColor:GenerateHexColor()
return unknownColor
end})
-- Compatibility with OLDER forks of pfUI. Our DLL adds the modern
-- HookScript widget method; older pfUI forks branch on
-- `if button.HookScript` and take a modern code path they were never
-- written for on their pfActionBar buttons, which breaks them. While
-- the actionbar module builds those buttons, temporarily wrap
-- CreateFrame to shadow HookScript with a falsy field so those forks
-- fall back to their vanilla SetScript path. The maintained "brues"
-- fork handles HookScript itself, so it's detected via the TOC
-- X-Website tag and left alone. The wrapper is removed as soon as the
-- actionbar module finishes loading so it affects nothing else.
local website = GetAddOnMetadata("pfUI", "X-Website")
if not website or not string.find(GetAddOnMetadata("pfUI", "X-Website") or '', 'brues') then
local _createFrame = CreateFrame
CreateFrame = function(frameType, name, parent, template)
if frameType == "Button" and string.find(name or "", "pfActionBar") then
local frame = _createFrame(frameType, name, parent, template)
frame.HookScript = false
return frame
end
return _createFrame(frameType, name, parent, template)
end
hooksecurefunc(pfUI, 'LoadModule', function(frame, moduleName)
if moduleName == "actionbar" then
CreateFrame = _createFrame
end
end)
end
end)
end
@@ -1,205 +0,0 @@
-- Backport of 3.3.5 FrameXML/CallbackRegistryMixin.lua to vanilla 1.12 / Lua 5.0.
--
-- Implementation differences from the 3.3.5 source:
-- - 1.12 has no taint or Secure-Templates system, so the entire
-- AttributeDelegate/SetForbidden machinery for inserting event keys
-- into the callback tables is unnecessary. Sub-tables are allocated
-- lazily inside RegisterCallback instead.
-- - securecallfunction/secureexecuterange don't exist; they reduce to
-- direct calls / explicit for-loops here.
-- - EnumUtil.MakeEnum is inlined as a plain string table.
-- - GenerateClosure doesn't exist in 1.12; provide a local one that
-- captures registration-time varargs via SafePack-style storage.
-- - Lua 5.0 has no select() or `wipe()`; we use the implicit `arg`
-- table and assign-nil to clear tables.
local generateOwnerID = CreateCounter()
local CallbackType = { Closure = "Closure", Function = "Function" }
-- Local GenerateClosure: binds `func` plus all of `...` so a later call
-- invokes func(boundArgs..., callArgs...). Mirrors 3.3.5's helper of the
-- same name. SafePack/SafeUnpack semantics so embedded nils survive.
local function GenerateClosure(func, ...)
local boundN = arg.n
local bound = {}
for i = 1, boundN do bound[i] = arg[i] end
return function(...)
local callN = arg.n
local merged = {}
for i = 1, boundN do merged[i] = bound[i] end
for i = 1, callN do merged[boundN + i] = arg[i] end
return func(unpack(merged, 1, boundN + callN))
end
end
CallbackRegistryMixin = CallbackRegistryMixin or {}
function CallbackRegistryMixin:OnLoad()
local callbackTables = {}
for _, value in pairs(CallbackType) do
callbackTables[value] = {}
end
self.callbackTables = callbackTables
end
function CallbackRegistryMixin:SetUndefinedEventsAllowed(allowed)
self.isUndefinedEventAllowed = allowed
end
function CallbackRegistryMixin:GetCallbackTables()
return self.callbackTables
end
function CallbackRegistryMixin:GetCallbackTable(callbackType)
return self.callbackTables[callbackType]
end
function CallbackRegistryMixin:GetCallbacksByEvent(callbackType, event)
local callbackTable = self:GetCallbackTable(callbackType)
return callbackTable[event]
end
function CallbackRegistryMixin:HasRegistrantsForEvent(event)
for _, callbackTable in pairs(self:GetCallbackTables()) do
local callbacks = callbackTable[event]
if callbacks and next(callbacks) then
return true
end
end
return false
end
-- Lazy allocation of per-event sub-tables. In 3.3.5 this went through a
-- forbidden attribute frame for taint-isolation reasons; that's a no-op
-- consideration on 1.12, so we just assign here.
function CallbackRegistryMixin:SecureInsertEvent(event)
for _, callbackTable in pairs(self:GetCallbackTables()) do
if not callbackTable[event] then
callbackTable[event] = {}
end
end
end
function CallbackRegistryMixin:RegisterCallback(event, func, owner, ...)
if type(event) ~= "string" then
error("CallbackRegistryMixin::RegisterCallback 'event' requires string type.")
elseif type(func) ~= "function" then
error("CallbackRegistryMixin::RegisterCallback 'func' requires function type.")
else
if owner == nil then
owner = generateOwnerID()
elseif type(owner) == "number" then
error("CallbackRegistryMixin:RegisterCallback 'owner' as number is reserved internally.")
end
end
self:SecureInsertEvent(event)
for _, callbackTable in pairs(self:GetCallbackTables()) do
local callbacks = callbackTable[event]
callbacks[owner] = nil
end
if arg.n > 0 then
local callbacks = self:GetCallbacksByEvent(CallbackType.Closure, event)
callbacks[owner] = GenerateClosure(func, owner, unpack(arg))
else
local callbacks = self:GetCallbacksByEvent(CallbackType.Function, event)
callbacks[owner] = func
end
return owner
end
local function CreateCallbackHandle(cbr, event, owner)
local handle =
{
Unregister = function()
cbr:UnregisterCallback(event, owner)
end,
}
return handle
end
function CallbackRegistryMixin:RegisterCallbackWithHandle(event, func, owner, ...)
owner = self:RegisterCallback(event, func, owner, unpack(arg))
return CreateCallbackHandle(self, event, owner)
end
function CallbackRegistryMixin:TriggerEvent(event, ...)
if type(event) ~= "string" then
error("CallbackRegistryMixin:TriggerEvent 'event' requires string type.")
elseif not self.isUndefinedEventAllowed and not (self.Event and self.Event[event]) then
error(string.format("CallbackRegistryMixin:TriggerEvent event '%s' doesn't exist.", event))
end
local closures = self:GetCallbacksByEvent(CallbackType.Closure, event)
if closures then
for _, closure in pairs(closures) do
closure(unpack(arg))
end
end
local funcs = self:GetCallbacksByEvent(CallbackType.Function, event)
if funcs then
for owner, func in pairs(funcs) do
-- Stock 3.3.5 passes the owner as the first arg so callers can
-- distinguish multiple registrations of the same function.
local n = arg.n
local merged = { owner }
for i = 1, n do merged[i + 1] = arg[i] end
func(unpack(merged, 1, n + 1))
end
end
end
function CallbackRegistryMixin:UnregisterCallback(event, owner)
if type(event) ~= "string" then
error("CallbackRegistryMixin:UnregisterCallback 'event' requires string type.")
elseif owner == nil then
error("CallbackRegistryMixin:UnregisterCallback 'owner' is required.")
end
for _, callbackTable in pairs(self:GetCallbackTables()) do
local callbacks = callbackTable[event]
if callbacks then
callbacks[owner] = nil
end
end
end
function CallbackRegistryMixin:UnregisterEvents(eventTable)
if eventTable then
for _, callbackTable in pairs(self:GetCallbackTables()) do
for event in pairs(eventTable) do
if callbackTable[event] then
callbackTable[event] = nil
end
end
end
else
for _, callbackTable in pairs(self:GetCallbackTables()) do
for k in pairs(callbackTable) do
callbackTable[k] = nil
end
end
end
end
function CallbackRegistryMixin:GenerateCallbackEvents(events)
if not self.Event then
self.Event = {}
end
for eventIndex, eventName in ipairs(events) do
if self.Event[eventName] then
error(string.format("CallbackRegistryMixin:GenerateCallbackEvents: event '%s' already exists.", eventName))
end
self.Event[eventName] = eventName
end
end
function CallbackRegistryMixin.DoesFrameHaveEvent(frame, event)
return frame.Event and frame.Event[event]
end
-118
View File
@@ -1,118 +0,0 @@
ColorMixin = ColorMixin or {}
function CreateColor(r, g, b, a)
local color = CreateFromMixins(ColorMixin)
color:OnLoad(r, g, b, a)
return color
end
function ColorMixin:OnLoad(r, g, b, a)
self:SetRGBA(r, g, b, a)
end
function ColorMixin:IsRGBEqualTo(otherColor)
return self.r == otherColor.r
and self.g == otherColor.g
and self.b == otherColor.b
end
function ColorMixin:IsEqualTo(otherColor)
return self:IsRGBEqualTo(otherColor) and self.a == otherColor.a
end
function ColorMixin:GetRGB()
return self.r, self.g, self.b
end
function ColorMixin:GetRGBAsBytes()
return self.r * 255, self.g * 255, self.b * 255
end
function ColorMixin:GetRGBA()
return self.r, self.g, self.b, self.a
end
function ColorMixin:GetRGBAAsBytes()
return self.r * 255, self.g * 255, self.b * 255, (self.a or 1) * 255
end
function ColorMixin:SetRGBA(r, g, b, a)
self.r = r
self.g = g
self.b = b
self.a = a
end
function ColorMixin:SetRGB(r, g, b)
self:SetRGBA(r, g, b, nil)
end
function ColorMixin:GenerateHexColor()
return string.format("ff%.2x%.2x%.2x", self:GetRGBAsBytes())
end
function ColorMixin:GenerateHexColorMarkup()
return "|c"..self:GenerateHexColor()
end
function ColorMixin:GenerateHexColorNoAlpha()
return string.format("%.2x%.2x%.2x", self:GetRGBAsBytes())
end
function ColorMixin:GetHSL()
local r, g, b, a = self.r, self.g, self.b, self.a
local max, min = math.max(r, g, b), math.min(r, g, b)
local h, s, l
l = (max + min) / 2
if max == min then
h, s = 0, 0 -- achromatic
else
local d = max - min
if l > 0.5 then
s = d / (2 - max - min)
else
s = d / (max + min)
end
if max == r then
h = (g - b) / d
if g < b then
h = h + 6
end
elseif max == g then
h = (b - r) / d + 2
elseif max == b then
h = (r - g) / d + 4
end
h = h / 6
end
return h, s, l, a or 1
end
function ColorMixin:WrapTextInColorCode(text)
return WrapTextInColorCode(text, self:GenerateHexColor())
end
function WrapTextInColorCode(text, colorHexString)
return string.format("|c%s%s|r", colorHexString, text)
end
function WrapTextInColor(text, color)
return WrapTextInColorCode(text, color:GenerateHexColor())
end
function ColorMixin:WrapTextInColorTableCode(text)
return WrapTextInColorCode(text, self:GenerateHexColor())
end
for _, v in pairs(ITEM_QUALITY_COLORS) do
v.color = CreateColor(v.r, v.g, v.b, 1)
end
do
local envTbl = _G
for _, dbColor in ipairs(C_UIColor.GetColors()) do
local color = CreateColor(dbColor.color.r, dbColor.color.g, dbColor.color.b, dbColor.color.a)
envTbl[dbColor.baseTag] = color
envTbl[dbColor.baseTag.."_CODE"] = color:GenerateHexColorMarkup()
end
end
-135
View File
@@ -1,135 +0,0 @@
-- Item location bitflags (Using tonumber because lua 5.0 doesn't support hexadecimal literals. 0x)
ITEM_INVENTORY_LOCATION_PLAYER = tonumber("0x00100000", 16);
ITEM_INVENTORY_LOCATION_BAGS = tonumber("0x00200000", 16);
ITEM_INVENTORY_LOCATION_BANK = tonumber("0x00400000", 16);
ITEM_INVENTORY_BAG_BIT_OFFSET = 8; -- Number of bits that the bag index in GetInventoryItemsForSlot gets shifted to the left.
ITEM_INVENTORY_BANK_BAG_OFFSET = 4;
-- Inventory slots
INVSLOT_AMMO = 0;
INVSLOT_HEAD = 1; INVSLOT_FIRST_EQUIPPED = INVSLOT_HEAD;
INVSLOT_NECK = 2;
INVSLOT_SHOULDER = 3;
INVSLOT_BODY = 4;
INVSLOT_CHEST = 5;
INVSLOT_WAIST = 6;
INVSLOT_LEGS = 7;
INVSLOT_FEET = 8;
INVSLOT_WRIST = 9;
INVSLOT_HAND = 10;
INVSLOT_FINGER1 = 11;
INVSLOT_FINGER2 = 12;
INVSLOT_TRINKET1 = 13;
INVSLOT_TRINKET2 = 14;
INVSLOT_BACK = 15;
INVSLOT_MAINHAND = 16;
INVSLOT_OFFHAND = 17;
INVSLOT_RANGED = 18;
INVSLOT_TABARD = 19; INVSLOT_LAST_EQUIPPED = INVSLOT_TABARD;
INVSLOTS_EQUIPABLE_IN_COMBAT = {
[INVSLOT_MAINHAND] = true,
[INVSLOT_OFFHAND] = true,
[INVSLOT_RANGED] = true,
}
-- Item IDs
HEARTHSTONE_ITEM_ID = 6948;
--
-- Equipment Set
--
MAX_EQUIPMENT_SETS_PER_PLAYER = 10;
EQUIPMENT_SET_EMPTY_SLOT = 0;
EQUIPMENT_SET_IGNORED_SLOT = 1;
EQUIPMENT_SET_ITEM_MISSING = -1;
--
-- Totems
--
MAX_TOTEMS = 4;
FIRE_TOTEM_SLOT = 1;
EARTH_TOTEM_SLOT = 2;
WATER_TOTEM_SLOT = 3;
AIR_TOTEM_SLOT = 4;
STANDARD_TOTEM_PRIORITIES = {1, 2, 3, 4};
SHAMAN_TOTEM_PRIORITIES = {
EARTH_TOTEM_SLOT,
FIRE_TOTEM_SLOT,
WATER_TOTEM_SLOT,
AIR_TOTEM_SLOT,
};
-- Druid Forms.
CAT_FORM = 1;
BEAR_FORM = 5;
--
-- Class
--
CLASS_SORT_ORDER = {
"WARRIOR",
"PALADIN",
"PRIEST",
"SHAMAN",
"DRUID",
"ROGUE",
"MAGE",
"WARLOCK",
"HUNTER",
};
MAX_CLASSES = table.getn(CLASS_SORT_ORDER);
LOCALIZED_CLASS_NAMES_MALE = {};
LOCALIZED_CLASS_NAMES_FEMALE = {};
FillLocalizedClassList(LOCALIZED_CLASS_NAMES_MALE, false);
FillLocalizedClassList(LOCALIZED_CLASS_NAMES_FEMALE, true);
--
-- Inventory
--
BAG_ITEM_QUALITY_COLORS =
{
[LE_ITEM_QUALITY_COMMON] = COMMON_GRAY_COLOR,
[LE_ITEM_QUALITY_UNCOMMON] = UNCOMMON_GREEN_COLOR,
[LE_ITEM_QUALITY_RARE] = RARE_BLUE_COLOR,
[LE_ITEM_QUALITY_EPIC] = EPIC_PURPLE_COLOR,
[LE_ITEM_QUALITY_LEGENDARY] = LEGENDARY_ORANGE_COLOR,
[LE_ITEM_QUALITY_ARTIFACT] = ARTIFACT_GOLD_COLOR,
};
-- faction
PLAYER_FACTION_GROUP = { [0] = "Horde", [1] = "Alliance", Horde = 0, Alliance = 1 };
FACTION_LABELS = {
[0] = FACTION_HORDE,
[1] = FACTION_ALLIANCE,
};
FACTION_LABELS_FROM_STRING = {
["Horde"] = FACTION_HORDE,
["Alliance"] = FACTION_ALLIANCE,
}
PLAYER_FACTION_COLORS =
{
[0] = PLAYER_FACTION_COLOR_HORDE,
[1] = PLAYER_FACTION_COLOR_ALLIANCE,
};
--
-- Glyph
--
INSCRIPTION_AVAILABLE = false;
-- PaperDollFrame.lua
EQUIPPED_FIRST = 1;
EQUIPPED_LAST = 19;
BASE_MOVEMENT_SPEED = 7;
@@ -1,108 +0,0 @@
-- Backport of FrameXML/FormattingUtil.lua (feasible subset) to vanilla
-- 1.12 / Lua 5.0.
--
-- 5.0 notes: no `#`/`%`/string-method syntax — uses string.*, math.mod.
-- The currency/cost helpers (C_CurrencyInfo etc.) are omitted. GetMoneyString
-- uses text symbols, not coin texture markup (markup doesn't render in 1.12).
--
-- The FrameXML format-string globals these functions consume
-- (LARGE_NUMBER_SEPERATOR, PERCENTAGE_STRING, GOLD_AMOUNT_SYMBOL, …) are
-- defined in the locale layer (locales/enUS.lua), which loads first.
COPPER_PER_SILVER = 100;
SILVER_PER_GOLD = 100;
COPPER_PER_GOLD = COPPER_PER_SILVER * SILVER_PER_GOLD;
function FormatLargeNumber(amount)
amount = tostring(amount);
local newDisplay = "";
local strlen = string.len(amount);
-- Insert a separator before each group of three trailing digits.
for i = 4, strlen, 3 do
newDisplay = LARGE_NUMBER_SEPERATOR ..
string.sub(amount, -(i - 1), -(i - 3)) .. newDisplay;
end
-- Prepend everything before the first separator.
local lead = (math.mod(strlen, 3) == 0) and 3 or math.mod(strlen, 3);
newDisplay = string.sub(amount, 1, lead) .. newDisplay;
return newDisplay;
end
function FormatPercentage(percentage, roundToNearestInteger)
if roundToNearestInteger then
percentage = Round(percentage * 100);
else
percentage = percentage * 100;
end
return string.format(PERCENTAGE_STRING, percentage);
end
function FormatFraction(numerator, denominator)
return string.format(GENERIC_FRACTION_STRING, numerator, denominator);
end
function SplitTextIntoLines(text, delimiter)
local lines = {};
local startIndex = 1;
local foundIndex = string.find(text, delimiter);
while foundIndex do
table.insert(lines, string.sub(text, startIndex, foundIndex - 1));
startIndex = foundIndex + 2;
foundIndex = string.find(text, delimiter, startIndex);
end
if startIndex <= string.len(text) then
table.insert(lines, string.sub(text, startIndex));
end
return lines;
end
function SplitTextIntoHeaderAndNonHeader(text)
local foundIndex = string.find(text, "|n");
local len = string.len(text);
if not foundIndex then
return text; -- no newline: whole thing is a header
elseif len == 2 then
return nil; -- the string was just a newline
elseif foundIndex == 1 then
return string.sub(text, 3); -- leading newline: rest is a header
elseif foundIndex == len - 1 then
return string.sub(text, 1, foundIndex - 1); -- trailing newline
else
return string.sub(text, 1, foundIndex - 1), string.sub(text, foundIndex + 2);
end
end
-- (money, separateThousands [, checkGoldThreshold, showZeroAsGold])
-- Text-symbol form ("12g 34s 56c"); the coin-texture form from the
-- reference is dropped since texture markup doesn't render in 1.12. The
-- checkGoldThreshold arg is accepted for signature compatibility but not
-- applied (it relied on modern Constants tables).
function GetMoneyString(money, separateThousands, checkGoldThreshold, showZeroAsGold)
local gold = math.floor(money / COPPER_PER_GOLD);
local silver = math.floor(math.mod(money, COPPER_PER_GOLD) / COPPER_PER_SILVER);
local copper = math.mod(money, COPPER_PER_SILVER);
local goldString = (separateThousands and FormatLargeNumber(gold) or tostring(gold)) ..
GOLD_AMOUNT_SYMBOL;
local silverString = silver .. SILVER_AMOUNT_SYMBOL;
local copperString = copper .. COPPER_AMOUNT_SYMBOL;
if showZeroAsGold and money == 0 then
return goldString;
end
local moneyString = "";
local separator = "";
if gold > 0 then
moneyString = goldString;
separator = " ";
end
if silver > 0 then
moneyString = moneyString .. separator .. silverString;
separator = " ";
end
if copper > 0 or moneyString == "" then
moneyString = moneyString .. separator .. copperString;
end
return moneyString;
end
-64
View File
@@ -1,64 +0,0 @@
-- Backport of FrameXML/FrameUtil.lua (core subset) to vanilla 1.12.
--
-- Only the dependency-light, commonly-called helpers are ported. Omitted:
-- - the fade/flash functions (UIFrameFade*/UIFrameFlash*) are already
-- native in 1.12.
-- - RegisterFrameForUnitEvents (no RegisterUnitEvent in 1.12), and the
-- scale/layout/secure/EventRegistry helpers (rely on APIs absent here).
FrameUtil = FrameUtil or {};
function FrameUtil.RegisterFrameForEvents(frame, events)
for i, event in ipairs(events) do
frame:RegisterEvent(event);
end
end
function FrameUtil.UnregisterFrameForEvents(frame, events)
for i, event in ipairs(events) do
frame:UnregisterEvent(event);
end
end
function FrameUtil.GetRootParent(frame)
local parent = frame:GetParent();
while parent do
local nextParent = parent:GetParent();
if not nextParent then
break;
end
parent = nextParent;
end
return parent;
end
-- Reparents while preserving the frame's render layering.
function FrameUtil.SetParentMaintainRenderLayering(frame, parent)
local origStrata = frame:GetFrameStrata();
local origFrameLevel = frame:GetFrameLevel();
frame:SetParent(parent);
frame:SetFrameStrata(origStrata);
frame:SetFrameLevel(origFrameLevel);
end
function DoesAncestryInclude(ancestry, frame)
if ancestry then
local currentFrame = frame;
while currentFrame do
if currentFrame == ancestry then
return true;
end
currentFrame = currentFrame:GetParent();
end
end
return false;
end
function DoesAncestryIncludeAny(ancestry, frames)
for _, frame in ipairs(frames) do
if DoesAncestryInclude(ancestry, frame) then
return true;
end
end
return false;
end
@@ -1,89 +0,0 @@
-- Backport of 3.3.5 FrameXML/GlobalCallbackRegistry.lua to vanilla 1.12 / Lua 5.0.
--
-- Implementation differences from the 3.3.5 source:
-- - 3.3.5 ref-counts WoW frame events via a SetAttribute/OnAttributeChanged
-- dance because attribute mutations are taint-safe in the secure-template
-- model. 1.12 has neither secure templates nor SetAttribute on frames,
-- so we keep an ordinary {[event]=count} table and Register/Unregister
-- on 0<->1 transitions.
EventRegistry = CreateFromMixins(CallbackRegistryMixin)
function EventRegistry:OnLoad()
CallbackRegistryMixin.OnLoad(self)
self:SetUndefinedEventsAllowed(true)
self.eventCounts = {}
self.frameEventFrame = CreateFrame("Frame")
self.frameEventFrame.registry = self
self.frameEventFrame:SetScript("OnEvent", function()
-- 1.12 globals: `event` is the event name; `arg1..argN` are payload.
-- We don't repack them here; CallbackRegistryMixin:TriggerEvent uses
-- Lua-5.0 varargs, so we forward through a small wrapper.
self:DispatchGameEvent(event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)
end)
end
-- Helper so we can forward up to nine event args (the most any vanilla
-- event currently emits) into TriggerEvent's vararg machinery.
function EventRegistry:DispatchGameEvent(event, ...)
self:TriggerEvent(event, unpack(arg))
end
function EventRegistry:RegisterFrameEvent(frameEvent)
local n = (self.eventCounts[frameEvent] or 0) + 1
self.eventCounts[frameEvent] = n
if n == 1 then
self.frameEventFrame:RegisterEvent(frameEvent)
end
end
function EventRegistry:UnregisterFrameEvent(frameEvent)
local n = self.eventCounts[frameEvent] or 0
if n > 0 then
n = n - 1
self.eventCounts[frameEvent] = n
if n == 0 then
self.frameEventFrame:UnregisterEvent(frameEvent)
end
end
end
function EventRegistry:RegisterFrameEventAndCallback(frameEvent, ...)
self:RegisterFrameEvent(frameEvent)
return self:RegisterCallback(frameEvent, unpack(arg))
end
local function CreateCallbackHandle(cbr, cbrHandle, frameEvent)
local handle = {
Unregister = function()
cbr:UnregisterFrameEvent(frameEvent)
cbrHandle:Unregister()
end,
}
return handle
end
function EventRegistry:RegisterFrameEventAndCallbackWithHandle(frameEvent, ...)
self:RegisterFrameEvent(frameEvent)
local cbrHandle = self:RegisterCallbackWithHandle(frameEvent, unpack(arg))
return CreateCallbackHandle(self, cbrHandle, frameEvent)
end
function EventRegistry:UnregisterFrameEventAndCallback(frameEvent, ...)
self:UnregisterFrameEvent(frameEvent)
self:UnregisterCallback(frameEvent, unpack(arg))
end
function EventRegistry:GetEventCounts(...)
local counts = {}
for i = 1, arg.n do
local frameEvent = arg[i]
local count = self.eventCounts[frameEvent] or "?"
table.insert(counts, frameEvent .. " : " .. tostring(count))
end
return table.concat(counts, "\n")
end
EventRegistry:OnLoad()
-420
View File
@@ -1,420 +0,0 @@
-- Backport of 3.3.5 FrameXML/ItemUtil.lua to vanilla 1.12 / Lua 5.0.
--
-- Implementation differences from the 3.3.5 source:
-- - Many C_Item.* calls the modern code expects are not exposed by
-- ClassicAPI.dll. We shim the missing ones at the top using the
-- stock 1.12 globals (GetItemInfo, GetInventoryItemLink,
-- GetContainerItemLink/Info). DLL-provided functions are left alone
-- via `or` guards so we never clobber a real implementation.
-- - Lua 5.0 has no select(); calls that previously did
-- `select(N, GetItemInfo(...))` use named locals to peel off the
-- return values instead.
-- - CallErrorHandler isn't in 1.12; we route through geterrorhandler().
-- - In 1.12 OnEvent scripts, event name + payload are exposed via the
-- `event`, `arg1`, `arg2`... globals rather than as function args.
-- - 1.12 has no concept of an item GUID and no public item-lock API,
-- so those return nil / no-op.
C_Item.GetItemInfo = GetItemInfo
----------------------------------------------------------------------
Item = {}
ItemMixin = {}
local ItemEventListener
--[[static]] function Item:CreateFromItemLocation(itemLocation)
if type(itemLocation) ~= "table" or type(itemLocation.HasAnyLocation) ~= "function" or not itemLocation:HasAnyLocation() then
error("Usage: Item:CreateFromItemLocation(notEmptyItemLocation)", 2)
end
local item = CreateFromMixins(ItemMixin)
item:SetItemLocation(itemLocation)
return item
end
--[[static]] function Item:CreateFromBagAndSlot(bagID, slotIndex)
if type(bagID) ~= "number" or type(slotIndex) ~= "number" then
error("Usage: Item:CreateFromBagAndSlot(bagID, slotIndex)", 2)
end
local item = CreateFromMixins(ItemMixin)
item:SetItemLocation(ItemLocation:CreateFromBagAndSlot(bagID, slotIndex))
return item
end
--[[static]] function Item:CreateFromEquipmentSlot(equipmentSlotIndex)
if type(equipmentSlotIndex) ~= "number" then
error("Usage: Item:CreateFromEquipmentSlot(equipmentSlotIndex)", 2)
end
local item = CreateFromMixins(ItemMixin)
item:SetItemLocation(ItemLocation:CreateFromEquipmentSlot(equipmentSlotIndex))
return item
end
--[[static]] function Item:CreateFromItemLink(itemLink)
if type(itemLink) ~= "string" then
error("Usage: Item:CreateFromItemLink(itemLinkString)", 2)
end
local item = CreateFromMixins(ItemMixin)
item:SetItemLink(itemLink)
return item
end
--[[static]] function Item:CreateFromItemID(itemID)
if type(itemID) ~= "number" then
error("Usage: Item:CreateFromItemID(itemID)", 2)
end
local item = CreateFromMixins(ItemMixin)
item:SetItemID(itemID)
return item
end
--[[static]] function Item:CreateFromItemGUID(itemGUID)
if type(itemGUID) ~= "string" then
error("Usage: Item:CreateFromItemGUID(itemGUIDString)", 2);
end
local item = CreateFromMixins(ItemMixin);
item:SetItemGUID(itemGUID);
return item;
end
--[[static]] function Item:DoItemsMatch(item1, item2)
if not item1 or not item2 then
return false;
end
return item1:Matches(item2);
end
function ItemMixin:Matches(item)
if not item then
return false;
end
local itemID = item:GetItemID();
if (itemID ~= nil) and (self:GetItemID() == itemID) then
return true;
end
local itemLocation = item:GetItemLocation();
if (itemLocation ~= nil) and itemLocation:IsEqualTo(self:GetItemLocation()) then
return true;
end
return false;
end
function ItemMixin:SetItemLocation(itemLocation)
self:Clear()
self.itemLocation = itemLocation
end
function ItemMixin:SetItemLink(itemLink)
self:Clear()
self.itemLink = itemLink
end
function ItemMixin:SetItemID(itemID)
self:Clear()
self.itemID = itemID
end
function ItemMixin:SetItemGUID(itemGUID)
self:Clear();
self.itemGUID = itemGUID;
end
function ItemMixin:GetItemLocation()
if self.itemLocation then
return self.itemLocation;
end
if self.itemGUID then
return C_Item.GetItemLocation(self.itemGUID);
end
return nil;
end
function ItemMixin:HasItemLocation()
return self.itemLocation ~= nil
end
function ItemMixin:Clear()
self.itemLocation = nil
self.itemLink = nil
self.itemID = nil
self.itemGUID = nil
end
function ItemMixin:IsItemEmpty()
if self:GetStaticBackingItem() then
return not C_Item.DoesItemExistByID(self:GetStaticBackingItem())
end
return not self:IsItemInPlayersControl()
end
function ItemMixin:GetStaticBackingItem()
return self.itemLink or self.itemID
end
function ItemMixin:IsItemInPlayersControl()
local itemLocation = self:GetItemLocation()
return itemLocation and C_Item.DoesItemExist(itemLocation)
end
-- Item API
function ItemMixin:GetItemID()
if self:GetStaticBackingItem() then
return (C_Item.GetItemInfoInstant(self:GetStaticBackingItem()))
end
if not self:IsItemEmpty() then
return C_Item.GetItemID(self:GetItemLocation())
end
return nil
end
function ItemMixin:IsItemLocked()
return self:IsItemInPlayersControl() and C_Item.IsLocked(self:GetItemLocation())
end
function ItemMixin:LockItem()
if self:IsItemInPlayersControl() then
C_Item.LockItem(self:GetItemLocation())
end
end
function ItemMixin:UnlockItem()
if self:IsItemInPlayersControl() then
C_Item.UnlockItem(self:GetItemLocation())
end
end
function ItemMixin:GetItemIcon() -- requires item data to be loaded
if self:GetStaticBackingItem() then
return C_Item.GetItemIconByID(self:GetStaticBackingItem())
end
if not self:IsItemEmpty() then
return C_Item.GetItemIcon(self:GetItemLocation())
end
end
function ItemMixin:GetItemName() -- requires item data to be loaded
if self:GetStaticBackingItem() then
return C_Item.GetItemNameByID(self:GetStaticBackingItem())
end
if not self:IsItemEmpty() then
return C_Item.GetItemName(self:GetItemLocation())
end
return nil
end
function ItemMixin:GetItemLink() -- requires item data to be loaded
if self.itemLink then
return self.itemLink
end
if self.itemID then
local _, link = GetItemInfo(self.itemID)
return link
end
if not self:IsItemEmpty() then
return C_Item.GetItemLink(self:GetItemLocation())
end
return nil
end
function ItemMixin:GetItemQuality() -- requires item data to be loaded
if self:GetStaticBackingItem() then
return C_Item.GetItemQualityByID(self:GetStaticBackingItem())
end
if not self:IsItemEmpty() then
return C_Item.GetItemQuality(self:GetItemLocation())
end
return nil
end
function ItemMixin:GetCurrentItemLevel() -- requires item data to be loaded
if self:GetStaticBackingItem() then
return (C_Item.GetDetailedItemLevelInfo(self:GetStaticBackingItem()))
end
if not self:IsItemEmpty() then
return C_Item.GetCurrentItemLevel(self:GetItemLocation())
end
return nil
end
function ItemMixin:GetItemQualityColor() -- requires item data to be loaded
local itemQuality = self:GetItemQuality()
return ITEM_QUALITY_COLORS[itemQuality] -- may be nil if item data isn't loaded
end
function ItemMixin:GetItemQualityColorRGB() -- requires item data to be loaded
local colorTbl = self:GetItemQualityColor()
return colorTbl.color:GetRGB()
end
function ItemMixin:GetItemMaxStackSize() -- requires item data to be loaded
if self:GetStaticBackingItem() then
return C_Item.GetItemMaxStackSizeByID(self:GetStaticBackingItem());
end
if not self:IsItemEmpty() then
return C_Item.GetItemMaxStackSize(self:GetItemLocation());
end
return nil;
end
function ItemMixin:IsStackable() -- requires item data to be loaded
local maxStackSize = self:GetItemMaxStackSize();
return maxStackSize and maxStackSize > 1;
end
function ItemMixin:GetInventoryType()
if self:GetStaticBackingItem() then
return C_Item.GetItemInventoryTypeByID(self:GetStaticBackingItem())
end
if not self:IsItemEmpty() then
return C_Item.GetItemInventoryType(self:GetItemLocation())
end
return nil
end
function ItemMixin:GetItemGUID()
if self:GetStaticBackingItem() then
return nil
end
if not self:IsItemEmpty() then
return C_Item.GetItemGUID(self:GetItemLocation())
end
return nil
end
function ItemMixin:GetInventoryTypeName()
if not self:IsItemEmpty() then
-- GetItemInfoInstant returns: itemID, itemType, itemSubType, equipLoc, ...
local _, _, _, equipLoc = C_Item.GetItemInfoInstant(self:GetItemID())
return equipLoc
end
end
function ItemMixin:IsItemDataCached()
if self:GetStaticBackingItem() then
return C_Item.IsItemDataCachedByID(self:GetStaticBackingItem())
end
if not self:IsItemEmpty() then
return C_Item.IsItemDataCached(self:GetItemLocation())
end
return true
end
function ItemMixin:IsDataEvictable()
return true
end
-- Default error handler routing: stock 1.12 has no CallErrorHandler.
local function ItemUtilErrorHandler(err)
local h = geterrorhandler and geterrorhandler()
if h then return h(err) end
end
function ItemMixin:ContinueOnItemLoad(callbackFunction)
if type(callbackFunction) ~= "function" or self:IsItemEmpty() then
error("Usage: NonEmptyItem:ContinueOnLoad(callbackFunction)", 2)
end
ItemEventListener:AddCallback(self:GetItemID(), callbackFunction)
end
function ItemMixin:ContinueWithCancelOnItemLoad(callbackFunction)
if type(callbackFunction) ~= "function" or self:IsItemEmpty() then
error("Usage: NonEmptyItem:ContinueWithCancelOnItemLoad(callbackFunction)", 2)
end
return ItemEventListener:AddCancelableCallback(self:GetItemID(), callbackFunction)
end
--[ Item Event Listener ]
ItemEventListener = CreateFrame("Frame")
ItemEventListener.callbacks = {}
-- 1.12 OnEvent receives no function args; event name and payload live in
-- the `event`, `arg1`, ... globals.
ItemEventListener:SetScript("OnEvent", function()
if event == "ITEM_DATA_LOAD_RESULT" then
local itemID, success = arg1, arg2
if success then
ItemEventListener:FireCallbacks(itemID)
else
ItemEventListener:ClearCallbacks(itemID)
end
end
end)
ItemEventListener:RegisterEvent("ITEM_DATA_LOAD_RESULT")
local CANCELED_SENTINEL = -1
function ItemEventListener:AddCallback(itemID, callbackFunction)
local callbacks = self:GetOrCreateCallbacks(itemID)
table.insert(callbacks, callbackFunction)
C_Item.RequestLoadItemDataByID(itemID)
end
function ItemEventListener:AddCancelableCallback(itemID, callbackFunction)
local callbacks = self:GetOrCreateCallbacks(itemID)
table.insert(callbacks, callbackFunction)
C_Item.RequestLoadItemDataByID(itemID)
local index = table.getn(callbacks)
return function()
if table.getn(callbacks) > 0 and callbacks[index] ~= CANCELED_SENTINEL then
callbacks[index] = CANCELED_SENTINEL
return true
end
return false
end
end
function ItemEventListener:FireCallbacks(itemID)
local callbacks = self:GetCallbacks(itemID)
if callbacks then
self:ClearCallbacks(itemID)
for i, callback in ipairs(callbacks) do
if callback ~= CANCELED_SENTINEL then
xpcall(callback, ItemUtilErrorHandler)
end
end
for i = table.getn(callbacks), 1, -1 do
callbacks[i] = nil
end
end
end
function ItemEventListener:ClearCallbacks(itemID)
self.callbacks[itemID] = nil
end
function ItemEventListener:GetCallbacks(itemID)
return self.callbacks[itemID]
end
function ItemEventListener:GetOrCreateCallbacks(itemID)
local callbacks = self.callbacks[itemID]
if not callbacks then
callbacks = {}
self.callbacks[itemID] = callbacks
end
return callbacks
end
-27
View File
@@ -1,27 +0,0 @@
-- Backport of 3.3.5 FrameXML/Mixin.lua to vanilla 1.12 / Lua 5.0.
--
-- Implementation differences from the 3.3.5 source:
-- - Lua 5.0 has no select(); inside a vararg function the args are
-- gathered into an implicit `arg` table (`arg.n` for the count).
function Mixin(object, ...)
for i = 1, arg.n do
local mixin = arg[i]
if mixin then
for k, v in pairs(mixin) do
object[k] = v
end
end
end
return object
end
function CreateFromMixins(...)
return Mixin({}, unpack(arg))
end
function CreateAndInitFromMixin(mixin, ...)
local object = CreateFromMixins(mixin)
object:Init(unpack(arg))
return object
end
-521
View File
@@ -1,521 +0,0 @@
-- Backport of FrameXML/Pools.lua to vanilla 1.12 / Lua 5.0.
--
-- Implementation differences from the modern source:
-- - 1.12 has no taint/secure system, so the entire Secure*/Proxy
-- machinery (SecureTypes, ProxyUtil, securecallfunction,
-- CreateForbiddenFrame) is dropped. Only the Unsecured pools and
-- pool collections exist; the canonical `CreateObjectPool` /
-- `CreateFramePool` / etc. globals are aliased to them at the
-- bottom of the file.
-- - FrameUtil.SpecializeFrameWithMixins isn't a thing in 1.12; the
-- "table specialization" branch is inlined as a plain Mixin().
-- - CreateMaskTexture and CreateActor aren't in 1.12 — the
-- corresponding pool creators are kept as stubs so chunk-load of
-- consumer addons doesn't fail; they'll error at Acquire() time
-- if anything actually invokes them.
-- - Lua 5.0 has no `...` as expression; the converter mixins use
-- `unpack(arg, 1, arg.n)` to forward varargs.
-- - assertsafe / nop aren't globals in stock 1.12; defined as local
-- fallbacks (same pattern as FunctionUtil.lua).
local function nop() end
local function assertsafe(condition, msg)
if not condition then
local h = geterrorhandler and geterrorhandler()
if h then h(msg or "assertion failed!") end
end
end
local ObjectPoolBaseMixin = {};
--[[
Reserve() is not exposed on the pool to prevent the attack vector of addons having control
over the quantity of objects available to a preexisting pool.
]]--
local function Reserve(pool, capacity)
pool.capacity = capacity or math.huge;
if pool.capacity ~= math.huge then
for index = 1, pool.capacity do
pool:Acquire();
end
pool:ReleaseAll();
end
end
local function GetObjectIsInvalidMsg(object, poolOrCollection)
if poolOrCollection:DoesObjectBelongToPool(object) then
return string.format("Attempted to release inactive object '%s'", tostring(object));
else
return string.format("Attempted to release object '%s' that doesn't belong to this pool", tostring(object));
end
end
function ObjectPoolBaseMixin:Acquire()
if self:GetNumActive() == self.capacity then
return nil, false;
end
local object = self:PopInactiveObject();
local new = object == nil;
if new then
object = self:CallCreate();
--[[
While pools don't necessarily need to only contain tables, support for other types
has not been tested, and therefore isn't allowed until we can justify a use for them.
]]--
assert(type(object) == "table");
self:CallReset(object, new);
end
self:AddObject(object);
return object, new;
end
function ObjectPoolBaseMixin:Release(object, canFailToFindObject)
local active = self:IsActive(object);
--[[
If Release() is called on a pool directly from external code, then we expect
an assert if the object is not found. However, if it was called from a pool
collection, the object not being active is expected as the pool collection iterates
all the pools until it is found. A separate assert in pool collections accounts for
the case where the object was not found in any pool.
]]--
if not canFailToFindObject then
assertsafe(active, GetObjectIsInvalidMsg(object, self));
end
if active then
self:CallReset(object);
self:ReclaimObject(object);
end
return active;
end
function ObjectPoolBaseMixin:Dump()
for index, object in self:EnumerateActive() do
print(tostring(object));
end
end
local ObjectPoolMixin = CreateFromMixins(ObjectPoolBaseMixin);
function ObjectPoolMixin:Init(createFunc, resetFunc, capacity)
self.createFunc = createFunc;
self.resetFunc = resetFunc;
self.activeObjects = {};
self.inactiveObjects = {};
self.activeObjectCount = 0;
Reserve(self, capacity);
end
function ObjectPoolMixin:CallReset(object, new)
self.resetFunc(self, object, new);
end
function ObjectPoolMixin:CallCreate()
-- The pool argument 'self' is passed only for addons already reliant on it.
return self.createFunc(self);
end
function ObjectPoolMixin:PopInactiveObject()
return tremove(self.inactiveObjects);
end
function ObjectPoolMixin:AddObject(object)
local dummy = true;
self.activeObjects[object] = dummy;
self.activeObjectCount = self.activeObjectCount + 1;
end
function ObjectPoolMixin:ReclaimObject(object)
tinsert(self.inactiveObjects, object);
self.activeObjects[object] = nil;
self.activeObjectCount = self.activeObjectCount - 1;
end
function ObjectPoolMixin:ReleaseAll()
for object in pairs(self.activeObjects) do
self:Release(object);
end
end
function ObjectPoolMixin:EnumerateActive()
return pairs(self.activeObjects);
end
function ObjectPoolMixin:GetNextActive(current)
return next(self.activeObjects, current);
end
function ObjectPoolMixin:IsActive(object)
return self.activeObjects[object] ~= nil;
end
function ObjectPoolMixin:DoesObjectBelongToPool(object)
if self:IsActive(object) then
return true;
end
for index, candidate in pairs(self.inactiveObjects) do
if candidate == object then
return true;
end
end
return false;
end
function ObjectPoolMixin:GetNumActive()
return self.activeObjectCount;
end
local function GetPoolKey(template, specialization)
if specialization == nil then
return template.."nil";
end
return template..tostring(specialization);
end
local PoolCollectionBaseMixin = {};
function PoolCollectionBaseMixin:GetPool(template, specialization)
local poolKey = GetPoolKey(template, specialization);
return self:GetPoolByKey(poolKey);
end
function PoolCollectionBaseMixin:HasPool(poolKey)
return self:GetPoolByKey(poolKey) ~= nil;
end
function PoolCollectionBaseMixin:Acquire(template, specialization)
local pool = self:GetPool(template, specialization);
return pool:Acquire();
end
function PoolCollectionBaseMixin:ReleaseAllByTemplate(template, specialization)
local pool = self:GetPool(template, specialization);
if pool then
pool:ReleaseAll();
end
end
function PoolCollectionBaseMixin:EnumerateActiveByTemplate(template, specialization)
local pool = self:GetPool(template, specialization);
if pool then
return pool:EnumerateActive();
end
return nop;
end
function PoolCollectionBaseMixin:GetOrCreatePool(...)
assert(false);
end
function PoolCollectionBaseMixin:CreatePool(...)
assert(false);
end
function PoolCollectionBaseMixin:CreatePoolWithArgs(args)
local poolKey = self:CreatePoolKeyFromPoolArgs(args);
assert(not self:HasPool(poolKey));
local pool = self:CreatePoolInternal(args);
self:SetPool(poolKey, pool);
return pool;
end
function PoolCollectionBaseMixin:GetOrCreatePoolWithArgs(args)
local poolKey = self:CreatePoolKeyFromPoolArgs(args);
local pool = self:GetPoolByKey(poolKey);
local new = pool == nil;
if new then
pool = self:CreatePoolWithArgs(args);
end
return pool, new;
end
function PoolCollectionBaseMixin:Dump()
for object in self:EnumerateActive() do
print(tostring(object));
end
end
local PoolCollectionMixin = CreateFromMixins(PoolCollectionBaseMixin);
function PoolCollectionMixin:Init()
self.pools = {};
end
function PoolCollectionMixin:GetNumActive()
local total = 0;
for poolKey, pool in pairs(self.pools) do
total = total + pool:GetNumActive();
end
return total;
end
function PoolCollectionMixin:SetPool(poolKey, pool)
self.pools[poolKey] = pool;
end
function PoolCollectionMixin:GetPoolByKey(poolKey)
return self.pools[poolKey];
end
function PoolCollectionMixin:Release(object)
local canFailToFindObject = true;
for poolKey, pool in pairs(self.pools) do
if pool:Release(object, canFailToFindObject) then
return;
end
end
assertsafe(false, GetObjectIsInvalidMsg(object, self));
end
function PoolCollectionMixin:DoesObjectBelongToPool(object)
for poolKey, pool in pairs(self.pools) do
if pool:DoesObjectBelongToPool(object) then
return true;
end
end
return false;
end
function PoolCollectionMixin:ReleaseAll()
for poolKey, pool in pairs(self.pools) do
pool:ReleaseAll();
end
end
-- Warning: this function only returns the object, unlike a pool that also returns the key.
function PoolCollectionMixin:EnumerateActive()
local currentObject = nil;
local currentPoolKey, currentPool = next(self.pools, currentObject);
return function()
if currentPool then
currentObject = currentPool:GetNextActive(currentObject);
while not currentObject do
currentPoolKey, currentPool = next(self.pools, currentPoolKey)
if currentPool then
currentObject = currentPool:GetNextActive(nil);
else
break;
end
end
end
return currentObject;
end, nil;
end
function Pool_HideAndClearAnchors(pool, region)
region:Hide();
region:ClearAllPoints();
end
function ActorPool_HideAndClearModel(actorPool, actor)
actor:ClearModel();
actor:Hide();
end
--[[
In addition to a specialization being used to create separate pools for the same template, it can
be used to modify a frame after being created. On modern WoW this delegates to
FrameUtil.SpecializeFrameWithMixins (which also wires up conventional script handlers); on 1.12
we just Mixin() the table into the frame and let the consumer call SetScript() if needed.
]]--
local function ConvertSpecializationToPostCreate(specialization)
local specializationType = type(specialization);
if specializationType == "function" then
return specialization;
elseif specializationType == "table" then
local function Initializer(frame)
Mixin(frame, specialization);
end
return Initializer;
end
return nil;
end
function CreateUnsecuredRegionPoolInstance(template, createFunc, resetFunc, capacity)
local pool = CreateFromMixins(ObjectPoolMixin);
pool:Init(createFunc, resetFunc or Pool_HideAndClearAnchors, capacity);
pool.GetTemplate = function(self)
return template;
end
return pool;
end
--[[
Args are packed into a table for ease of implementation in PoolCollectionBaseMixin, which is
derived with different argument signatures. This also makes it easy to access named fields
like `parent` off the table without dealing with argument position.
]]--
local function FramePoolCollection_ArgsToTable(frameType, parent, template, resetFunc, forbidden, specialization, capacity)
return {
frameType = frameType,
parent = parent,
template = template,
resetFunc = resetFunc,
forbidden = forbidden, -- ignored on 1.12 (no CreateForbiddenFrame)
specialization = specialization,
capacity = capacity,
};
end
local FramePoolCollectionConverterMixin = {};
function FramePoolCollectionConverterMixin:CreatePoolKeyFromPoolArgs(args)
return GetPoolKey(args.template, args.specialization);
end
function FramePoolCollectionConverterMixin:GetOrCreatePool(...)
local args = FramePoolCollection_ArgsToTable(unpack(arg, 1, arg.n));
return self:GetOrCreatePoolWithArgs(args);
end
function FramePoolCollectionConverterMixin:CreatePool(...)
local args = FramePoolCollection_ArgsToTable(unpack(arg, 1, arg.n));
return self:CreatePoolWithArgs(args);
end
local FramePoolCollectionMixin = CreateFromMixins(PoolCollectionMixin, FramePoolCollectionConverterMixin);
do
local function CreateFramePoolInstance(frameType, parent, template, resetFunc, postCreate, capacity)
local function Create()
local name = nil;
local frame = CreateFrame(frameType, name, parent, template);
if postCreate then
postCreate(frame);
end
return frame;
end
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
end
function FramePoolCollectionMixin:CreatePoolInternal(args)
local postCreate = ConvertSpecializationToPostCreate(args.specialization);
return CreateFramePoolInstance(args.frameType, args.parent, args.template, args.resetFunc, postCreate, args.capacity);
end
end
local FontStringPoolCollectionMixin = CreateFromMixins(PoolCollectionMixin);
function FontStringPoolCollectionMixin:CreatePoolKeyFromPoolArgs(args)
return args.template;
end
local function FontStringPoolCollection_ArgsToTable(parent, layer, subLayer, template, resetFunc, capacity)
return {
parent = parent,
layer = layer,
subLayer = subLayer,
template = template,
resetFunc = resetFunc,
capacity = capacity,
};
end
function FontStringPoolCollectionMixin:GetOrCreatePool(...)
local args = FontStringPoolCollection_ArgsToTable(unpack(arg, 1, arg.n));
return self:GetOrCreatePoolWithArgs(args);
end
function FontStringPoolCollectionMixin:CreatePool(...)
local args = FontStringPoolCollection_ArgsToTable(unpack(arg, 1, arg.n));
return self:CreatePoolWithArgs(args);
end
function FontStringPoolCollectionMixin:CreatePoolInternal(args)
return CreateUnsecuredFontStringPool(args.parent, args.layer, args.subLayer, args.template, args.resetFunc, args.capacity);
end
function CreateUnsecuredObjectPool(createFunc, resetFunc, capacity)
local pool = CreateFromMixins(ObjectPoolMixin);
pool:Init(createFunc, resetFunc, capacity);
return pool;
end
function CreateUnsecuredFramePool(frameType, parent, template, resetFunc, capacity)
local function Create()
local name = nil;
return CreateFrame(frameType, name, parent, template);
end
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
end
function CreateUnsecuredTexturePool(parent, layer, subLayer, template, resetFunc, capacity)
local function Create()
local name = nil;
return parent:CreateTexture(name, layer, template, subLayer);
end
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
end
function CreateUnsecuredFontStringPool(parent, layer, subLayer, template, resetFunc, capacity)
local function Create()
local name = nil;
return parent:CreateFontString(name, layer, template, subLayer);
end
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
end
-- Stub: 1.12 has no CreateActor (model actors are Cataclysm+). Acquire()
-- will raise once it actually tries to call parent:CreateActor — kept so
-- that addon code merely referencing the symbol doesn't fail to load.
function CreateUnsecuredActorPool(parent, template, resetFunc, capacity)
local function Create()
local name = nil;
return parent:CreateActor(name, template);
end
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc or ActorPool_HideAndClearModel, capacity);
end
-- Stub: 1.12 has no CreateMaskTexture (mask textures are post-vanilla).
-- Same caveat as CreateUnsecuredActorPool.
function CreateUnsecuredMaskTexturePool(parent, layer, subLayer, template, resetFunc, capacity)
local function Create()
local name = nil;
return parent:CreateMaskTexture(name, layer, template, subLayer);
end
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
end
function CreateUnsecuredFramePoolCollection()
local poolCollection = CreateFromMixins(FramePoolCollectionMixin);
poolCollection:Init();
return poolCollection;
end
function CreateUnsecuredFontStringPoolCollection()
local poolCollection = CreateFromMixins(FontStringPoolCollectionMixin);
poolCollection:Init();
return poolCollection;
end
-- Canonical API aliases. On modern WoW these point at the Secure variants;
-- on 1.12 there's no taint system, so they all go straight to the Unsecured
-- implementations.
CreateObjectPool = CreateUnsecuredObjectPool;
CreateFramePool = CreateUnsecuredFramePool;
CreateTexturePool = CreateUnsecuredTexturePool;
CreateFontStringPool = CreateUnsecuredFontStringPool;
CreateActorPool = CreateUnsecuredActorPool;
CreateFramePoolCollection = CreateUnsecuredFramePoolCollection;
CreateFontStringPoolCollection = CreateUnsecuredFontStringPoolCollection;
CreateMaskTexturePool = CreateUnsecuredMaskTexturePool;
@@ -1,25 +0,0 @@
function RegisterNewSlashCommand(callback, command, commandAlias)
local name = string.upper(command);
_G["SLASH_"..name.."1"] = "/"..command;
_G["SLASH_"..name.."2"] = "/"..commandAlias;
SlashCmdList[name] = callback;
end
SlashCmdList["FOCUS"] = function(msg)
if msg == "" then
FocusUnit();
else
FocusUnit(msg);
end
end
SlashCmdList["CLEARFOCUS"] = function(msg)
ClearFocus()
end
SlashCmdList["EQUIP_SET"] = function(msg)
if msg ~= "" then
C_EquipmentSet.UseEquipmentSet(C_EquipmentSet.GetEquipmentSetID(msg))
end
end
-13
View File
@@ -1,13 +0,0 @@
function string.match(s, pattern, init)
if s == nil then return nil end
local r1, r2, c1, c2, c3, c4, c5, c6, c7, c8, c9 =
string.find(s, pattern, init)
if r1 == nil then return nil end
if c1 ~= nil then
return c1, c2, c3, c4, c5, c6, c7, c8, c9
end
return string.sub(s, r1, r2)
end
string.gmatch = string.gfind
-725
View File
@@ -1,725 +0,0 @@
-- Backport of 3.3.5 FrameXML/TableUtil.lua to vanilla 1.12 / Lua 5.0.
--
-- Implementation differences from the 3.3.5 source:
-- - Lua 5.0 has no length operator (#). Sequence length comes from
-- table.getn(t), which honors an explicit .n field when present.
-- - Lua 5.0 has no select() and no `...` outside a vararg function
-- body; varargs are passed via the implicit `arg` table.
-- - 1.12 has no global wipe(); we ship a local Wipe() helper instead.
-- - Lua 5.0 has no math.huge; 1/0 yields the same +inf sentinel.
local tRemove, tInsert, tWipe = table.remove, table.insert, table.wipe
local tGetN = table.getn
TableUtil = TableUtil or {}
TableUtil.Constants =
{
AssociativePriorityTable = true,
ArraylikePriorityTable = false,
IsIndexTable = true,
}
function ipairs_reverse(table)
local function Enumerator(table, index)
index = index - 1
local value = table[index]
if value ~= nil then
return index, value
end
end
return Enumerator, table, tGetN(table) + 1
end
function CreateTableEnumerator(tbl, minIndex, maxIndex)
minIndex = minIndex and (minIndex - 1) or 0
maxIndex = maxIndex or math.huge
local function Enumerator(tbl, index)
index = index + 1
if index <= maxIndex then
local value = tbl[index]
if value ~= nil then
return index, value
end
end
end
return Enumerator, tbl, minIndex
end
function CreateTableReverseEnumerator(tbl, minIndex, maxIndex)
minIndex = minIndex or 1
maxIndex = (maxIndex or tGetN(tbl)) + 1
local function Enumerator(tbl, index)
index = index - 1
if index >= minIndex then
local value = tbl[index]
if value ~= nil then
return index, value
end
end
end
return Enumerator, tbl, maxIndex
end
function tDeleteItem(tbl, item)
local size = tGetN(tbl);
local index = size;
while index > 0 do
if item == tbl[index] then
tRemove(tbl, index);
end
index = index - 1;
end
return size - tGetN(tbl);
end
function tIndexOf(tbl, item)
for i, v in ipairs(tbl) do
if item == v then
return i
end
end
end
function tContains(tbl, item)
for k, v in pairs(tbl) do
if item == v then
return true;
end
end
return false;
end
function TableUtil.ContainsAllKeys(lhsTable, rhsTable)
for key, _ in pairs(lhsTable) do
if rhsTable[key] == nil then
return false
end
end
return true
end
function TableUtil.CompareValuesAsKeys(lhsTable, rhsTable, valueToKeyOp)
local lhsKeys = CopyTransformedValuesAsKeys(lhsTable, valueToKeyOp)
local rhsKeys = CopyTransformedValuesAsKeys(rhsTable, valueToKeyOp)
return TableUtil.ContainsAllKeys(lhsKeys, rhsKeys)
end
function tCompare(lhsTable, rhsTable, depth)
depth = depth or 1
for key, value in pairs(lhsTable) do
if type(value) == "table" then
local rhsValue = rhsTable[key]
if type(rhsValue) ~= "table" then
return false
end
if depth > 1 then
if not tCompare(value, rhsValue, depth - 1) then
return false
end
end
elseif value ~= rhsTable[key] then
return false
end
end
for key, value in pairs(rhsTable) do
if lhsTable[key] == nil then
return false
end
end
return true
end
function tInvert(tbl)
local inverted = {}
for k, v in pairs(tbl) do
inverted[v] = k
end
return inverted
end
function TableUtil.TrySet(tbl, key)
if not tbl[key] then
tbl[key] = true
return true
end
return false
end
function TableUtil.CopyUnique(tbl, isIndexTable)
local found = {}
local function FilterPredicate(value)
return TableUtil.TrySet(found, value)
end
return tFilter(tbl, FilterPredicate, isIndexTable)
end
function TableUtil.CopyUniqueByPredicate(tbl, isIndexTable, unaryPredicate)
local found = {}
local function FilterPredicate(value)
return TableUtil.TrySet(found, unaryPredicate(value))
end
return tFilter(tbl, FilterPredicate, isIndexTable)
end
function tFilter(tbl, pred, isIndexTable)
local out = {}
if isIndexTable then
local currentIndex = 1
for i, v in ipairs(tbl) do
if pred(v) then
out[currentIndex] = v
currentIndex = currentIndex + 1
end
end
else
for k, v in pairs(tbl) do
if pred(v) then
out[k] = v
end
end
end
return out
end
function tAppendAll(table, addedArray)
for i, element in ipairs(addedArray) do
tInsert(table, element)
end
end
function tInsertUnique(tbl, item)
if not tContains(tbl, item) then
tInsert(tbl, item)
return tGetN(tbl)
end
return nil
end
function tUnorderedRemove(tbl, index)
local n = tGetN(tbl)
if index ~= n then
tbl[index] = tbl[n]
end
tRemove(tbl)
end
function CopyTable(settings, shallow)
local copy = {}
for k, v in pairs(settings) do
if type(v) == "table" and not shallow then
copy[k] = CopyTable(v)
else
copy[k] = v
end
end
return copy
end
function CopyTableSafe(settings, shallow)
if not settings then
return nil;
end
return CopyTable(settings, shallow);
end
function MergeTable(destination, source)
for k, v in pairs(source) do
destination[k] = v
end
end
function SetTablePairsToTable(destination, source)
tWipe(destination)
MergeTable(destination, source)
end
function CountTable(tbl)
local count = 0;
for k, v in pairs(tbl) do
count = count + 1;
end
return count;
end
function Accumulate(tbl)
local count = 0
for k, v in pairs(tbl) do
count = count + v
end
return count
end
function AccumulateOp(tbl, op)
local count = 0
for k, v in pairs(tbl) do
count = count + op(v)
end
return count
end
function TableUtil.Execute(tbl, op)
for k, v in pairs(tbl) do
op(v)
end
end
function TableUtil.ExecuteOnKeys(tbl, op)
for k in pairs(tbl) do
op(k)
end
end
function TableUtil.ExecuteUntil(tbl, op)
for k, v in pairs(tbl) do
local operationResult = op(v)
if operationResult then
return operationResult
end
end
return nil
end
function TableUtil.Transform(tbl, op)
local result = {}
for k, v in pairs(tbl) do
tInsert(result, op(v))
return result
end
end
-- Returns the value in a table deemed smallest by evaluating each value returned by the op function parameter.
-- The return of the op function must return a number.
function TableUtil.FindMin(tbl, op)
local result = nil;
local min = math.huge;
for k, v in pairs(tbl) do
local value = op(v);
if value < min then
min = value;
result = v;
end
end
return result;
end
-- Returns the value in a table deemed largest by evaluating each value returned by the op function parameter.
-- The return of the op function must return a number.
function TableUtil.FindMax(tbl, op)
local result = nil;
local max = -math.huge;
for k, v in pairs(tbl) do
local value = op(v);
if value > max then
max = value;
result = v;
end
end
return result;
end
function ContainsIf(tbl, pred)
for k, v in pairs(tbl) do
if pred(v) then
return true
end
end
return false
end
function FindInTable(tbl, value)
for k, v in pairs(tbl) do
if v == value then
return k, v;
end
end
return nil;
end
function FindInTableIf(tbl, pred)
for k, v in pairs(tbl) do
if pred(v) then
return k, v
end
end
return nil
end
function FindValueInTableIf(tbl, pred)
local _, value = FindInTableIf(tbl, pred)
return value
end
local function FindSortedIndexImplementation(tbl, searchComparison, startIndex, rangeStart, rangeEnd)
local comparisonResult = searchComparison(tbl[startIndex])
if comparisonResult == 0 then
return startIndex
end
if comparisonResult > 0 then
if startIndex >= rangeEnd then
return startIndex + 1
end
rangeStart = startIndex + 1
return FindSortedIndexImplementation(tbl, searchComparison, startIndex + math.ceil((rangeEnd - startIndex) / 2), rangeStart, rangeEnd)
end
if startIndex <= rangeStart then
return startIndex
end
rangeEnd = startIndex - 1
return FindSortedIndexImplementation(tbl, searchComparison, math.floor(startIndex / 2), rangeStart, rangeEnd)
end
function FindSortedIndex(tbl, searchComparison)
local numTable = tGetN(tbl)
local startingIndex = math.ceil(numTable / 2)
if startingIndex == 0 then
return 1
end
return FindSortedIndexImplementation(tbl, searchComparison, startingIndex, 1, numTable)
end
function TableIsEmpty(tbl)
return next(tbl) == nil
end
function TableHasAnyEntries(tbl)
return next(tbl) ~= nil
end
function CopyValuesAsKeys(tbl)
local output = {}
for k, v in ipairs(tbl) do
output[v] = v
end
return output
end
function CopyTransformedValuesAsKeys(tbl, transformOp)
local output = {}
for _, v in ipairs(tbl) do
output[transformOp(v)] = v
end
return output
end
function SafePack(...)
local tbl = {}
for i = 1, arg.n do tbl[i] = arg[i] end
tbl.n = arg.n
return tbl
end
function SafeUnpack(tbl)
return unpack(tbl, 1, tbl.n)
end
-- Returns the length of a table, accounting for the possibility of a table constructed using SafePack.
function SafeLength(tbl)
if not tbl then
return 0;
end
local operatorCount = tGetN(tbl);
local safePackCount = tbl.n;
if safePackCount and operatorCount ~= safePackCount then
return safePackCount;
end
return operatorCount;
end
function GetOrCreateTableEntry(table, key, defaultValue)
local currentValue = table[key]
local isNewValue = (currentValue == nil)
if isNewValue then
if defaultValue ~= nil then
currentValue = defaultValue
else
currentValue = {}
end
table[key] = currentValue
end
return currentValue, isNewValue
end
function GetOrCreateTableEntryByCallback(table, key, callback)
local currentValue = table[key]
local isNewValue = (currentValue == nil)
if isNewValue then
currentValue = callback(key)
table[key] = currentValue
end
return currentValue, isNewValue
end
function GetOrCreateTableEntryByMethod(table, key, method, owner)
local currentValue = table[key];
local isNewValue = (currentValue == nil);
if isNewValue then
currentValue = method(owner, key);
table[key] = currentValue;
end
return currentValue, isNewValue;
end
function GetRandomArrayEntry(array)
return array[math.random(1, tGetN(array))]
end
function GetRandomTableValue(tbl)
local value
local n = 0
for k, v in pairs(tbl) do
n = n + 1
local r = math.random()
if r <= (1 / n) then
value = v
end
end
return value
end
function GetKeysArray(tbl)
local keysArray = {}
for key in pairs(tbl) do
tInsert(keysArray, key)
end
return keysArray
end
function GetValuesArray(tbl)
local valuesArray = {}
for key, value in pairs(tbl) do
tInsert(valuesArray, value)
end
return valuesArray
end
function GetPairsArray(tbl)
local pairsArray = {}
for key, value in pairs(tbl) do
tInsert(pairsArray, { key = key, value = value, })
end
return pairsArray
end
function SwapTableEntries(lhsTable, rhsTable, key)
local lhsValue = lhsTable[key]
lhsTable[key] = rhsTable[key]
rhsTable[key] = lhsValue
end
function GetKeysArraySortedByValue(tbl)
local keysArray = GetKeysArray(tbl);
table.sort(keysArray, function(a, b)
return tbl[a] < tbl[b];
end);
return keysArray;
end
function TableUtil.GetTableValueListFromEnumeration(tableKey, ...)
local values = {}
for enumerationKey, tbl in arg[1] do
tInsert(values, tbl[tableKey])
end
return values
end
function TableUtil.GetHighestNumericalValueInTable(table)
local highestValue = nil;
for key, value in pairs(table) do
if type(value) == "number" and (not highestValue or value > highestValue) then
highestValue = value;
end
end
return highestValue;
end
--[[
This utility creates and returns a table of elements that are sorted by value "priority".
Arguments:
comparator - comparator(A, B) returns whether A has higher priority than B
isAssociative - whether the table should be associative (true) or array-like (false). Only values have priorities for associative tables, not keys.
Return usage:
t[k]/t:Get(k) - returns the value stored with key/index k
t[k] = v - (Associative only) stores the value v at key k, sorting accordingly
t:Insert(v) - (Array-like only) inserts the value v, sorting accordingly
t:Remove(k) - removes the element at key/index k
t:Iterate(cb) - calls function cb on each key/index value pair in sorted priority order
t:GetTop() - returns the highest priority element
t:Pop() - returns and removes the highest priority element
t:GetBottom() - returns the lowest priority element
t:Size() - returns the number of stored elements
t:Clear() - removes all elements
--]]
function TableUtil.CreatePriorityTable(comparator, isAssociative)
local sortedArray = {}
local ShiftPositionMap
local keyToPosMap
if isAssociative then
keyToPosMap = {}
ShiftPositionMap = function(position, shiftUp)
local mod = shiftUp and 1 or -1
for k, p in pairs(keyToPosMap) do
if p >= position then
keyToPosMap[k] = p + mod
end
end
end
end
local function SortedInsert(k, v)
if isAssociative then
local prevPos = keyToPosMap[k]
if prevPos then
tRemove(sortedArray, prevPos)
local shiftUp = false
ShiftPositionMap(prevPos, shiftUp)
end
end
local n = tGetN(sortedArray)
local top = (n > 0) and (n + 1) or 1
local bottom = 1
while top ~= bottom do
local mid = math.floor((top - bottom) / 2) + bottom
if not comparator(v, sortedArray[mid]) then
bottom = mid + 1
else
top = mid
end
end
local idx = bottom
tInsert(sortedArray, idx, v)
if isAssociative then
local shiftUp = true
ShiftPositionMap(idx, shiftUp)
keyToPosMap[k] = idx
end
end
local t = {}
function t:Get(k)
local key = isAssociative and keyToPosMap[k] or k
return sortedArray[key]
end
if not isAssociative then
function t:Insert(v)
SortedInsert(nil, v)
end
end
function t:Remove(k)
local key = isAssociative and keyToPosMap[k] or k
tRemove(sortedArray, key)
if isAssociative then
keyToPosMap[k] = nil
local shiftUp = false
ShiftPositionMap(key, shiftUp)
end
end
function t:GetTop()
return tGetN(sortedArray) > 0 and sortedArray[1]
end
function t:GetBottom()
local n = tGetN(sortedArray)
return n > 0 and sortedArray[n]
end
function t:Pop()
if t:Size() == 0 then
return nil
end
local top = t:GetTop()
local removalKey = isAssociative and tInvert(keyToPosMap)[1] or 1
t:Remove(removalKey)
return top
end
function t:Iterate(callback)
local posToKeyMap = isAssociative and tInvert(keyToPosMap) or nil
for pos, v in ipairs(sortedArray) do
local key = isAssociative and posToKeyMap[pos] or pos
local done = callback(key, v)
if done then
return
end
end
end
function t:Size()
return tGetN(sortedArray)
end
function t:Clear()
sortedArray = {}
if isAssociative then
keyToPosMap = {}
end
end
local mt =
{
__index = function(t, k)
return t:Get(k)
end,
}
if isAssociative then
mt.__newindex = function(t, k, v)
if v ~= nil then
SortedInsert(k, v)
else
t:Remove(k)
end
end
else
mt.__newindex = function(t, k, v)
error("Attempted to assign a value to an array-like priority queue index. Use Insert()/Remove() instead.")
end
end
setmetatable(t, mt)
return t
end
@@ -1,855 +0,0 @@
-- Trade-skill *list* links (`|Htrade:...|h`) — backport of the 2.x+ shareable
-- profession link. The link is built entirely in the DLL
-- (`GetTradeSkillListLink` / `GetCraftListLink`, see src/tradeskill/Link.cpp);
-- this file only intercepts clicks on received links and renders the linker's
-- recipe list in a scroll frame (the UI half).
--
-- link: |cffffd000|Htrade:<skillLineID>:<curRank>:<maxRank>:<linkerName>:<base64 bits>|h[Name]|h|r
--
-- "Which recipes are known" is a bitfield over the skill line's canonical
-- recipe list (deterministic per DBC). The viewer lists the recipes the linker
-- knows (with an "X of Y" summary of the whole skill line), regardless of what
-- the reader can craft themselves.
-- Frame geometry mirrors the real TradeSkillFrame. Turtle ships an HD
-- 768x512 two-column frame (TW-TradeSkill art); stock 1.12.1 only has the
-- vanilla 384x512 single-column art, so on that client we fall back to the
-- native Blizzard_TradeSkillUI geometry (list on top, detail below) rather
-- than stretch the wide art. LO holds every layout value that differs.
local TURTLE = (TURTLE_WOW_VERSION ~= nil);
local FRAME_W = TURTLE and 768 or 384;
local FRAME_H = 512;
local NUM_ROWS = TURTLE and 19 or 8;
local ROW_HEIGHT = 16;
local LO = TURTLE and {
hit = { 2, 82, 2, 73 },
quads = {
{ "Interface\\TradeSkillFrame\\TW-TradeSkill-TopLeft", 512, 256, "TOPLEFT" },
{ "Interface\\TradeSkillFrame\\TW-TradeSkill-TopRight", 256, 256, "TOPRIGHT" },
{ "Interface\\TradeSkillFrame\\TW-TradeSkill-BotLeft2", 512, 256, "BOTTOMLEFT" },
{ "Interface\\TradeSkillFrame\\TW-TradeSkill-BotRight2", 256, 256, "BOTTOMRIGHT" },
},
close = { -77, -8 },
bar = { 596, 15, 76, -44 },
barBdr = { 604, 22 },
summary = { "TOPRIGHT", -110, -70 },
drop = { 40, -60 },
scroll = { 296, 330, 37, -98 },
-- detail scroll frame: { x, y, width, height }. Tall enough that the
-- content fits (scrollbar auto-hides) — Turtle's right column is roomy.
detail = { 371, -110, 340, 290 },
exit = { "CENTER", "BOTTOMRIGHT", -128, 92 },
} or {
hit = { 0, 34, 0, 75 },
quads = {
{ "Interface\\ClassTrainerFrame\\UI-ClassTrainer-TopLeft", 256, 256, "TOPLEFT" },
{ "Interface\\ClassTrainerFrame\\UI-ClassTrainer-TopRight", 128, 256, "TOPRIGHT" },
{ "Interface\\TradeSkillFrame\\UI-TradeSkill-BotLeft", 256, 256, "BOTTOMLEFT" },
{ "Interface\\ClassTrainerFrame\\UI-ClassTrainer-BotRight", 128, 256, "BOTTOMRIGHT" },
},
close = { -29, -8 },
bar = { 268, 15, 73, -37 },
barBdr = { 278, 22 },
summary = { "TOPRIGHT", -40, -58 },
drop = { 12, -62 },
scroll = { 296, 130, 21, -96 },
-- detail scroll frame { x, y, width, height } — native TradeSkillFrame's
-- TradeSkillDetailScrollFrame values. Small enough that many-reagent
-- recipes scroll (clipping partial rows), like native.
detail = { 20, -234, 297, 176 },
exit = { "CENTER", "TOPLEFT", 305, -422 },
sep = { 15, -221, 331 },
};
-- Reagents render in a 2-column grid inside the detail scroll child (see
-- the detail pane below). The detail is a real ScrollFrame like the
-- native TradeSkillFrame, so the whole pane pixel-scrolls and clips
-- partial reagent rows — `REAGENT_ROW_HEIGHT` is just the vertical stride
-- of one reagent row.
local REAGENT_ROW_HEIGHT = 43;
-- Scroll-frame templates. Stock mimics the native TradeSkillFrame, whose
-- list/detail scrolls use the ClassTrainer templates (they add the
-- decorative UI-ClassTrainer-ScrollBar track). Turtle's HD frame art
-- doesn't want that groove, so it keeps the plain templates. Both detail
-- templates are real ScrollFrames (ClassTrainerDetail... inherits
-- UIPanelScrollFrameTemplate), so the pixel-scroll logic is identical.
local LIST_SCROLL_TEMPLATE = TURTLE and "FauxScrollFrameTemplate"
or "ClassTrainerListScrollFrameTemplate";
local DETAIL_SCROLL_TEMPLATE = TURTLE and "UIPanelScrollFrameTemplate"
or "ClassTrainerDetailScrollFrameTemplate";
local PROFESSION_ICONS = {
[171] = "Trade_Alchemy",
[164] = "Trade_BlackSmithing",
[185] = "INV_Misc_Food_15", -- Cooking
[333] = "Trade_Engraving", -- Enchanting
[202] = "Trade_Engineering",
[129] = "Spell_Holy_SealOfSacrifice", -- First Aid
[165] = "INV_Misc_ArmorKit_17", -- Leatherworking
[197] = "Trade_Tailoring",
[186] = "Trade_Mining",
[182] = "Trade_Herbalism",
[393] = "INV_Misc_Pelt_Wolf_01", -- Skinning
[356] = "Trade_Fishing",
};
if TURTLE then
PROFESSION_ICONS[142] = "Trade_Survival"
PROFESSION_ICONS[755] = "INV_Misc_Gem_01" -- Jewelcrafting
end
local function ProfessionIcon(skillLineID)
local icon = PROFESSION_ICONS[skillLineID];
return icon and ("Interface\\Icons\\" .. icon)
or "Interface\\Icons\\INV_Misc_QuestionMark";
end
local function DifficultyBand(skill, hi, lo)
if not hi or hi <= 0 then
return 3;
end
if not lo or lo == 0 then
lo = (hi ~= 25) and (hi - 25) or 0;
end
local yellow = (hi + lo) / 2;
if skill < lo then
return 0; -- orange (optimal)
elseif skill < yellow then
return 1; -- yellow (medium)
elseif skill < hi then
return 2; -- green (easy)
end
return 3; -- grey (trivial)
end
local BAND_COLOR = {
[0] = DIFFICULT_DIFFICULTY_COLOR, -- orange
[1] = FAIR_DIFFICULTY_COLOR, -- yellow
[2] = EASY_DIFFICULTY_COLOR, -- green
[3] = TRIVIAL_DIFFICULTY_COLOR, -- grey
};
local function CraftableCount(entry)
local reagents = entry.reagents;
if not reagents or table.getn(reagents) == 0 then
return nil;
end
local best;
for i = 1, table.getn(reagents) do
local r = reagents[i];
local need = r.count or 1;
local n = math.floor((C_Item.GetItemCount(r.itemID) or 0) / need);
if not best or n < best then
best = n;
end
end
return best;
end
local function ParseTradeLink(link)
-- Current format, with the linker's name: trade:id:cur:max:Name:bits
local _, _, id, cur, max, who, bits =
string.find(link, "^trade:(%d+):(%d+):(%d+):([^:]+):([%w%+/]*)$");
if not id then
-- Legacy format (no name): trade:id:cur:max:bits
who = nil;
_, _, id, cur, max, bits =
string.find(link, "^trade:(%d+):(%d+):(%d+):([%w%+/]*)$");
end
if not id then
return nil;
end
return tonumber(id), tonumber(cur), tonumber(max), who, bits or "";
end
------------------------------------------------------------------------------
-- Display frame (built lazily on first use)
------------------------------------------------------------------------------
local frame;
local function ResolveSubclasses(list, onLoaded)
local present, subs, anyItem = {}, {}, false;
for i = 1, table.getn(list) do
local r = list[i];
if r.createdItem and r.createdItem > 0 then
anyItem = true;
if not r.subclass then
-- GetItemInfoInstant's 3rd return is the localized subclass
-- name (or nil when uncached).
local _, _, subType = C_Item.GetItemInfoInstant(r.createdItem);
if subType and subType ~= "" then
r.subclass = subType;
elseif onLoaded then
-- Not cached — re-derive when the item loads.
Item:CreateFromItemID(r.createdItem):ContinueOnItemLoad(onLoaded);
end
end
if r.subclass and not present[r.subclass] then
present[r.subclass] = true;
table.insert(subs, r.subclass);
end
end
end
table.sort(subs);
return subs, anyItem;
end
local SUBCLASS_ALL = {};
local function SubClassButton_OnClick()
local v = this.value;
if v == SUBCLASS_ALL then
v = nil;
end
frame.subclassFilter = v;
UIDropDownMenu_SetText(v or ALL_SUBCLASSES, frame.dropdown);
frame:ApplyFilter();
end
local function SubClassDropDown_Initialize()
local info = {};
info.text = ALL_SUBCLASSES;
info.value = SUBCLASS_ALL;
info.checked = (frame.subclassFilter == nil);
info.func = SubClassButton_OnClick;
UIDropDownMenu_AddButton(info);
local subs = frame.subclasses or {};
for i = 1, table.getn(subs) do
local b = {};
b.text = subs[i];
b.value = subs[i];
b.checked = (frame.subclassFilter == subs[i]);
b.func = SubClassButton_OnClick;
UIDropDownMenu_AddButton(b);
end
end
local function RefreshSubclasses()
if not (frame and frame:IsShown() and frame.recipes) then
return;
end
local subs, anyItem = ResolveSubclasses(frame.recipes, RefreshSubclasses);
frame.subclasses = subs;
if anyItem then
UIDropDownMenu_Initialize(frame.dropdown, SubClassDropDown_Initialize);
UIDropDownMenu_SetWidth(120, frame.dropdown);
UIDropDownMenu_SetText(frame.subclassFilter or ALL_SUBCLASSES, frame.dropdown);
frame.dropdown:Show();
else
frame.dropdown:Hide();
end
if frame.subclassFilter then
frame:ApplyFilter();
end
end
local function CreateFrame_TradeSkillLink()
local f = CreateFrame("Frame", "ClassicAPITradeSkillLinkFrame", UIParent);
f:SetSize(FRAME_W, FRAME_H);
f:SetPoint("CENTER", 0, 0);
f:SetMovable(true);
f:EnableMouse(true);
f:SetHitRectInsets(LO.hit[1], LO.hit[2], LO.hit[3], LO.hit[4]);
f:RegisterForDrag("LeftButton");
f:SetScript("OnDragStart", function() this:StartMoving(); end);
f:SetScript("OnDragStop", function() this:StopMovingOrSizing(); end);
f:SetFrameStrata("DIALOG");
f:Hide();
tinsert(UISpecialFrames, f:GetName())
local portrait = f:CreateTexture(nil, "BACKGROUND");
portrait:SetSize(60, 60);
portrait:SetPoint("TOPLEFT", 7, -6);
f.portrait = portrait;
for i = 1, table.getn(LO.quads) do
local q = LO.quads[i];
local tx = f:CreateTexture(nil, "BORDER");
tx:SetTexture(q[1]);
tx:SetSize(q[2], q[3]);
tx:SetPoint(q[4]);
end
-- Horizontal divider between the recipe list and the detail pane.
-- Stock only (Turtle's HD frame art already has its own).
if LO.sep then
-- Decoded the BLP: it's a thin divider rod whose graphic lives in the
-- top quarter of the 256x64 texture (a 2nd rod fills the next quarter,
-- bottom half empty). So sample the top quarter, stretched to width —
-- the same region the native TradeSkillFrame uses for this divider.
local bar = f:CreateTexture(nil, "ARTWORK");
bar:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-HorizontalBar");
bar:SetTexCoord(0, 1, 0, 0.25);
bar:SetSize(LO.sep[3], 16);
bar:SetPoint("TOPLEFT", LO.sep[1], LO.sep[2]);
end
local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormal");
title:SetPoint("TOP", 0, -18);
f.title = title;
local close = CreateFrame("Button", nil, f, "UIPanelCloseButton");
close:SetPoint("TOPRIGHT", LO.close[1], LO.close[2]);
local exit = CreateFrame("Button", nil, f, "UIPanelButtonTemplate");
exit:SetSize(80, 22);
exit:SetPoint(LO.exit[1], f, LO.exit[2], LO.exit[3], LO.exit[4]);
exit:SetText(EXIT or "Exit");
exit:SetScript("OnClick", function() f:Hide(); end);
local bar = CreateFrame("StatusBar", nil, f);
bar:SetSize(LO.bar[1], LO.bar[2]);
bar:SetPoint("TOPLEFT", LO.bar[3], LO.bar[4]);
bar:SetStatusBarTexture("Interface\\PaperDollInfoFrame\\UI-Character-Skills-Bar");
bar:SetStatusBarColor(0.0, 0.0, 1.0, 0.5);
bar:SetMinMaxValues(0, 1);
local barBg = bar:CreateTexture(nil, "BACKGROUND");
barBg:SetAllPoints(bar);
barBg:SetTexture(1, 1, 1, 0.2);
barBg:SetVertexColor(0.0, 0.0, 0.75, 0.5);
-- Border: tooltip edge around the bar (TradeSkillRankFrameBorder).
local border = CreateFrame("Frame", nil, bar);
border:SetSize(LO.barBdr[1], LO.barBdr[2]);
border:SetPoint("LEFT", -5, 1);
border:SetBackdrop({
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 16,
});
border:SetBackdropBorderColor(0.4, 0.4, 0.4);
local barName = bar:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall");
barName:SetPoint("LEFT", 6, 1);
local barRank = bar:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall");
barRank:SetJustifyH("LEFT");
barRank:SetWidth(128);
barRank:SetPoint("LEFT", barName, "RIGHT", 13, 0);
f.bar = bar;
f.barName = barName;
f.barRank = barRank;
local summary = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall");
summary:SetPoint(LO.summary[1], LO.summary[2], LO.summary[3]);
f.summary = summary;
local dropdown = CreateFrame("Frame", "ClassicAPITradeSkillLinkSubClass", f,
"UIDropDownMenuTemplate");
dropdown:SetPoint("TOPLEFT", LO.drop[1], LO.drop[2]);
f.dropdown = dropdown;
f.subclassFilter = nil; -- nil = all subclasses
local scroll = CreateFrame("ScrollFrame", "ClassicAPITradeSkillLinkScroll",
f, LIST_SCROLL_TEMPLATE);
scroll:SetSize(LO.scroll[1], LO.scroll[2]);
scroll:SetPoint("TOPLEFT", LO.scroll[3], LO.scroll[4]);
scroll:SetScript("OnVerticalScroll", function()
FauxScrollFrame_OnVerticalScroll(ROW_HEIGHT, function() f:Refresh(); end)
end)
f.scroll = scroll;
f.rows = {};
for i = 1, NUM_ROWS do
local rowName = "ClassicAPITradeSkillLinkRow" .. i;
local row = CreateFrame("Button", rowName, f,
"ClassTrainerSkillButtonTemplate");
row:SetWidth(290); -- height (16) comes from the template
if i == 1 then
row:SetPoint("TOPLEFT", scroll, "TOPLEFT", 0, 0);
else
row:SetPoint("TOPLEFT", f.rows[i - 1], "BOTTOMLEFT", 0, 0);
end
row:SetNormalTexture("");
row:SetDisabledTexture("");
row:SetHighlightTexture("");
local txt = getglobal(rowName .. "Text");
if txt then
txt:ClearAllPoints();
txt:SetPoint("LEFT", row, "LEFT", 4, 0);
end
local sel = row:CreateTexture(nil, "BACKGROUND");
sel:SetTexture("Interface\\Buttons\\UI-Listbox-Highlight2");
sel:SetAllPoints(row);
sel:Hide();
row.select = sel;
-- Override the template's trainer scripts with ours.
row:SetScript("OnClick", function()
if this.entry then
f:SelectRecipe(this.entry);
end
end);
f.rows[i] = row;
end
-- Detail pane: a real ScrollFrame (like the native TradeSkillFrame's
-- TradeSkillDetailScrollFrame) whose scroll child holds the product
-- header + reagent grid, so the whole pane pixel-scrolls — clipping
-- partial reagent rows — with the standard UIPanelScrollBar. The bar
-- auto-hides when the content fits (scrollBarHideable).
local detailScroll = CreateFrame("ScrollFrame",
"ClassicAPITradeSkillLinkDetailScroll", f, DETAIL_SCROLL_TEMPLATE);
detailScroll:SetSize(LO.detail[3], LO.detail[4]);
detailScroll:SetPoint("TOPLEFT", LO.detail[1], LO.detail[2]);
detailScroll.scrollBarHideable = 1; -- template sets this too; belt-and-suspenders
f.detailScroll = detailScroll;
-- Off until a recipe overflows the pane (toggled in RenderDetail).
-- The template shows its slider and enables the wheel by default; on
-- the roomy Turtle pane that leaves a dead scrollbar that still eats
-- wheel events and over-scrolls a hair. Start both disabled.
detailScroll:EnableMouseWheel(false);
local detailSB = getglobal("ClassicAPITradeSkillLinkDetailScrollScrollBar");
if detailSB then
detailSB:Hide();
end
-- The template re-shows its slider when the frame transitions to shown
-- (on first open, before the auto-selected recipe's RenderDetail runs),
-- leaving a dead scrollbar until the first click. Re-assert the hidden
-- state on show unless the current recipe genuinely overflows.
detailScroll:SetScript("OnShow", function()
f:UpdateDetailScrollbar();
RunNextFrame(function()
if f:IsShown() then
f:UpdateDetailScrollbar();
end
end);
end);
local detailChild = CreateFrame("Frame",
"ClassicAPITradeSkillLinkDetailChild", detailScroll);
detailChild:SetSize(LO.detail[3], LO.detail[4]);
detailScroll:SetScrollChild(detailChild);
f.detailChild = detailChild;
local prodIcon = CreateFrame("Button", nil, detailChild);
prodIcon:SetSize(37, 37); -- native TradeSkillSkillIcon (37x37 @ 8,-3)
prodIcon:SetPoint("TOPLEFT", 8, -3);
prodIcon:SetNormalTexture("Interface\\Icons\\INV_Misc_QuestionMark");
local hdrLeft = detailChild:CreateTexture(nil, "BACKGROUND");
hdrLeft:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-DetailHeaderLeft");
hdrLeft:SetSize(256, 64); -- Blizzard's native fill width (+64 cap = 320 total)
hdrLeft:SetPoint("TOPLEFT", prodIcon, "TOPLEFT", -8, 6);
local hdrRight = detailChild:CreateTexture(nil, "BACKGROUND");
hdrRight:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-DetailHeaderRight");
hdrRight:SetSize(64, 64);
hdrRight:SetPoint("TOPLEFT", hdrLeft, "TOPRIGHT", 0, 0);
local prodCount = prodIcon:CreateFontString(nil, "ARTWORK", "NumberFontNormal");
prodCount:SetPoint("BOTTOMRIGHT", -5, 2);
prodIcon.count = prodCount;
f.prodIcon = prodIcon;
local prodName = detailChild:CreateFontString(nil, "ARTWORK", "GameFontNormal");
prodName:SetPoint("LEFT", prodIcon, "RIGHT", 5, 0);
prodName:SetWidth(LO.detail[3] - 60);
prodName:SetJustifyH("LEFT");
prodName:SetJustifyV("MIDDLE");
f.prodName = prodName;
local prodDesc = detailChild:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall");
prodDesc:SetPoint("TOPLEFT", prodIcon, "BOTTOMLEFT", 0, -6);
prodDesc:SetWidth(LO.detail[3] - 20);
prodDesc:SetJustifyH("LEFT");
prodDesc:SetJustifyV("TOP");
f.prodDesc = prodDesc;
local reagentLabel = detailChild:CreateFontString(nil, "ARTWORK", "GameFontNormalSmall");
reagentLabel:SetPoint("TOPLEFT", prodDesc, "BOTTOMLEFT", 0, -8);
reagentLabel:SetText(SPELL_REAGENTS or "Reagents:");
f.reagentLabel = reagentLabel;
prodIcon:SetScript("OnEnter", function()
GameTooltip:SetOwner(this, "ANCHOR_RIGHT");
if this.itemLink then
GameTooltip:SetHyperlink(this.itemLink);
elseif this.spellID then
GameTooltip:SetSpellByID(this.spellID);
end
GameTooltip:Show();
end);
prodIcon:SetScript("OnLeave", GameTooltip_Hide);
-- Reagent buttons live in the scroll child (2 per row), built on
-- demand so any reagent count is handled and they scroll/clip with
-- the child.
f.reagents = {};
local function AcquireReagent(i)
if f.reagents[i] then
return f.reagents[i];
end
local rowN = math.floor((i - 1) / 2);
local col = (i - 1) - rowN * 2;
local btn = CreateFrame("Button", nil, detailChild);
btn:SetSize(39, 39);
btn:SetPoint("TOPLEFT", reagentLabel, "BOTTOMLEFT",
col * 134 - 5, -3 - rowN * REAGENT_ROW_HEIGHT);
-- Extend the hit area rightward over the name plate so the tooltip
-- fires anywhere on the element, not just the icon. Stop short of the
-- next column (pitch 134 − icon 39) so hovers don't bleed across.
btn:SetHitRectInsets(0, -(134 - 39), 0, 0);
btn:SetNormalTexture("Interface\\Icons\\INV_Misc_QuestionMark");
local plate = btn:CreateTexture(nil, "BACKGROUND");
plate:SetTexture("Interface\\QuestFrame\\UI-QuestItemNameFrame");
plate:SetSize(114, 64);
plate:SetPoint("LEFT", btn, "RIGHT", -10, 0);
local cnt = btn:CreateFontString(nil, "ARTWORK", "NumberFontNormal");
cnt:SetPoint("BOTTOMRIGHT", -4, 1);
btn.count = cnt;
local nm = btn:CreateFontString(nil, "ARTWORK", "GameFontHighlight");
nm:SetPoint("LEFT", plate, "LEFT", 15, 0);
nm:SetSize(80, 36);
nm:SetJustifyH("LEFT");
nm:SetJustifyV("MIDDLE");
btn.nameText = nm;
btn:SetScript("OnEnter", function()
if this.itemLink then
GameTooltip:SetOwner(this, "ANCHOR_RIGHT");
GameTooltip:SetHyperlink(this.itemLink);
GameTooltip:Show();
end
end);
btn:SetScript("OnLeave", GameTooltip_Hide);
f.reagents[i] = btn;
return btn;
end
-- Show the detail slider + enable the wheel only when the current
-- recipe overflows the pane (tracked by `detailNeedScroll`).
function f:UpdateDetailScrollbar()
local need = self.detailNeedScroll and true or false;
self.detailScroll:EnableMouseWheel(need);
local base = "ClassicAPITradeSkillLinkDetailScroll";
local sb = getglobal(base .. "ScrollBar");
if sb then sb:SetShown(need) end
local top = getglobal(base .. "Top");
if top then top:SetShown(need) end
local bottom = getglobal(base .. "Bottom");
if bottom then bottom:SetShown(need) end
end
function f:RenderDetail(entry)
local function itemInfo(id)
local item = Item:CreateFromItemID(id);
if not item:IsItemDataCached() then
item:ContinueOnItemLoad(function()
if self:IsShown() and self.selectedSpellID == entry.spellID then
self:RenderDetail(entry);
end
end);
end
return item:GetItemName(), item:GetItemIcon(), item:GetItemLink();
end
local prodTex, prodText, prodLink;
local created = entry.createdItem or 0;
if created > 0 then
local name, tex, link = itemInfo(created);
prodText = name or entry.name;
prodTex = tex;
prodLink = link;
else
prodText = entry.name;
prodTex = C_Spell.GetSpellTexture(entry.spellID);
end
local descText = (created > 0) and ""
or (C_Spell.GetSpellDescription(entry.spellID) or "");
self.prodDesc:SetText(descText);
self.prodIcon:SetNormalTexture(prodTex or
"Interface\\Icons\\INV_Misc_QuestionMark");
self.prodName:SetText(prodText or "");
self.prodName:SetTextColor(NORMAL_FONT_COLOR:GetRGB());
self.prodIcon.itemLink = prodLink; -- item tooltip when created > 0
self.prodIcon.spellID = entry.spellID; -- else spell tooltip
local made = entry.numMade or 0;
self.prodIcon.count:SetText(made > 1 and tostring(made) or "");
self.prodIcon:Show();
-- Fill every reagent slot; the scroll child clips/scrolls the
-- overflow. Buttons past the count are hidden.
local reagents = entry.reagents or {};
local total = table.getn(reagents);
for i = 1, total do
local btn = AcquireReagent(i);
local r = reagents[i];
local name, tex, link = itemInfo(r.itemID);
btn:SetNormalTexture(tex or "Interface\\Icons\\INV_Misc_QuestionMark");
btn.itemLink = link;
btn.nameText:SetText(name or ("item:" .. r.itemID));
local need = r.count or 1;
local have = C_Item.GetItemCount(r.itemID) or 0;
if have >= need then
btn:GetNormalTexture():SetVertexColor(1, 1, 1);
btn.nameText:SetTextColor(HIGHLIGHT_FONT_COLOR:GetRGB());
else
btn:GetNormalTexture():SetVertexColor(0.5, 0.5, 0.5);
btn.nameText:SetTextColor(GRAY_FONT_COLOR:GetRGB());
end
local haveText = (have >= 100) and "*" or tostring(have);
btn.count:SetText(haveText .. " /" .. need);
btn:Show();
end
for i = total + 1, table.getn(self.reagents) do
self.reagents[i].itemLink = nil;
self.reagents[i]:Hide();
end
-- Grow the scroll child to the content height so the pane scrolls
-- once the header + reagent rows exceed the visible area. Reagent
-- row 0 sits ~67px below the child top (icon + label); add the
-- wrapped description height for spell recipes.
local descH = (descText ~= "") and self.prodDesc:GetHeight() or 0;
local rows = math.ceil(total / 2);
local contentH = 67 + descH + rows * REAGENT_ROW_HEIGHT + 8;
self.detailChild:SetHeight(math.max(contentH, LO.detail[4]));
-- Reset to the top and manage the slider explicitly: a range that
-- stays 0 (content fits, e.g. Turtle's roomy pane) never fires the
-- range-changed event that `scrollBarHideable` relies on, so the
-- slider would otherwise sit visible-but-useless. Show it only when
-- the content actually overflows.
self.detailNeedScroll = contentH > LO.detail[4];
local sb = getglobal("ClassicAPITradeSkillLinkDetailScrollScrollBar");
if sb then
sb:SetValue(0);
end
self.detailScroll:SetVerticalScroll(0);
self:UpdateDetailScrollbar();
RunNextFrame(function()
if self:IsShown() then
self:UpdateDetailScrollbar();
end
end)
end
function f:SelectRecipe(entry)
self.selectedSpellID = entry.spellID;
self.selectedEntry = entry;
self:RenderDetail(entry); -- also resets the detail scroll to top
self:Refresh();
end
function f:ClearDetail()
self.selectedSpellID = nil;
self.selectedEntry = nil;
self.prodIcon:Hide();
self.prodName:SetText("");
self.prodDesc:SetText("");
for i = 1, table.getn(self.reagents) do
self.reagents[i].itemLink = nil;
self.reagents[i]:Hide();
end
self.detailChild:SetHeight(LO.detail[4]);
self.detailNeedScroll = false;
self:UpdateDetailScrollbar();
self.detailScroll:SetVerticalScroll(0);
end
function f:Refresh()
local recipes = self.displayed or {};
local total = table.getn(recipes);
FauxScrollFrame_Update(self.scroll, total, NUM_ROWS, ROW_HEIGHT);
local offset = FauxScrollFrame_GetOffset(self.scroll);
for i = 1, NUM_ROWS do
local row = self.rows[i];
local entry = recipes[offset + i];
if entry then
-- Append " [N]" when the reader can craft any (Blizzard's list).
local craftable = CraftableCount(entry);
local label = entry.name or "";
if craftable and craftable > 0 then
label = label .. " [" .. craftable .. "]";
end
row:SetText(label);
local r, g, b = BAND_COLOR[entry.band or 3]:GetRGB();
if self.selectedSpellID and entry.spellID == self.selectedSpellID then
row.select:SetVertexColor(r, g, b);
row.select:Show();
row:SetTextColor(1, 1, 1);
else
row.select:Hide();
row:SetTextColor(r, g, b);
end
row.spellID = entry.spellID;
row.entry = entry;
row:Show();
else
row.spellID = nil;
row.entry = nil;
row.select:Hide();
row:Hide();
end
end
end
function f:ApplyFilter()
local src = self.recipes or {};
if not self.subclassFilter then
self.displayed = src;
else
local out = {};
for i = 1, table.getn(src) do
if src[i].subclass == self.subclassFilter then
table.insert(out, src[i]);
end
end
self.displayed = out;
end
local sb = getglobal("ClassicAPITradeSkillLinkScrollScrollBar");
if sb then
sb:SetValue(0);
end
self:Refresh();
end
f:RegisterEvent("BAG_UPDATE_DELAYED");
f:SetScript("OnEvent", function()
if not f:IsShown() then
return;
end
f:Refresh();
if f.selectedEntry then
f:RenderDetail(f.selectedEntry);
end
end);
return f;
end
local function ShowTradeSkillLink(link, text)
local id, cur, max, who, bits = ParseTradeLink(link);
if not id then
return false;
end
local recipes = C_TradeSkillUI.GetTradeSkillListRecipes(id, bits);
if not recipes then
return false;
end
local prof = text and string.match(text, "|h%[(.+)%]|h") or "Trade Skills";
local total = table.getn(recipes);
local knownList = {};
for i = 1, total do
local r = recipes[i];
if r.isKnown then
r.band = DifficultyBand(cur or 0, r.trivialLevel, r.greenLevel);
r.name = GetSpellInfo(r.spellID) or ("spell:" .. r.spellID);
table.insert(knownList, r);
end
end
table.sort(knownList, function(a, b)
if a.band ~= b.band then
return a.band < b.band;
end
return a.name < b.name;
end);
local known = table.getn(knownList);
if not frame then
frame = CreateFrame_TradeSkillLink();
end
frame.title:SetText(who and who ~= "" and (who .. " - " .. prof) or prof);
SetPortraitToTexture(frame.portrait, ProfessionIcon(id));
frame.bar:SetMinMaxValues(0, (max and max > 0) and max or 1);
frame.bar:SetValue(cur or 0);
frame.barName:SetText(prof);
frame.barRank:SetText(string.format("%d/%d", cur or 0, max or 0));
frame.summary:SetText(string.format("%d of %d recipes known", known, total));
frame.recipes = knownList;
frame.subclassFilter = nil;
frame:ClearDetail();
frame:Show();
RefreshSubclasses();
frame:ApplyFilter();
local first = frame.displayed and frame.displayed[1];
if first then
frame:SelectRecipe(first);
end
return true;
end
------------------------------------------------------------------------------
-- Click interception: handle `trade:` before the engine's SetHyperlink (which
-- in 1.12 only knows item:/enchant: and would reject the link).
------------------------------------------------------------------------------
local originalSetItemRef = SetItemRef;
function SetItemRef(link, text, button, chatFrame)
if type(link) == "string" and string.sub(link, 1, 6) == "trade:" then
if IsShiftKeyDown() and ChatFrameEditBox and ChatFrameEditBox:IsVisible() then
ChatFrameEditBox:Insert(text);
return;
end
if ShowTradeSkillLink(link, text) then
return;
end
end
return originalSetItemRef(link, text, button, chatFrame);
end
local function CreateProfessionLinkButton(parentName, getLink)
local parent = _G[parentName];
local btnName = parentName .. "LinkButton";
if _G[btnName] or not parent then
return;
end
local title = _G[parentName .. "TitleText"];
local btn = CreateFrame("Button", btnName, parent);
btn:SetSize(16, 16);
local function reposition()
if not title then
return;
end
btn:ClearAllPoints();
if title:GetJustifyH() == "LEFT" then
btn:SetPoint("LEFT", title, "LEFT", title:GetStringWidth() + 4, 0);
else
btn:SetPoint("LEFT", title, "CENTER", title:GetStringWidth() / 2 + 4, 0);
end
end
reposition()
btn:SetScript("OnShow", function() RunNextFrame(reposition) end)
hooksecurefunc(title, "SetText", function() RunNextFrame(reposition) end)
local icon = "Interface\\GossipFrame\\PetitionGossipIcon";
btn:SetNormalTexture(icon);
btn:SetHighlightTexture(icon, "ADD");
btn:SetScript("OnClick", function()
local link = getLink();
if not link then
return;
end
if not ChatFrameEditBox:IsVisible() then
ChatFrameEditBox:Show();
end
ChatFrameEditBox:Insert(link);
end);
btn:SetScript("OnEnter", function()
GameTooltip:SetOwner(this, "ANCHOR_TOPLEFT");
GameTooltip:SetText(LINK_TRADESKILL_TOOLTIP, nil, nil, nil, nil, 1);
GameTooltip:Show();
end);
btn:SetScript("OnLeave", GameTooltip_Hide);
end
EventUtil.ContinueOnAddOnLoaded("Blizzard_TradeSkillUI", function()
CreateProfessionLinkButton("TradeSkillFrame", C_TradeSkillUI.GetTradeSkillListLink);
end)
EventUtil.ContinueOnAddOnLoaded("Blizzard_CraftUI", function()
CreateProfessionLinkButton("CraftFrame", C_TradeSkillUI.GetCraftListLink)
end)
EventUtil.ContinueOnAddOnLoaded("AdvancedTradeSkillWindow", function()
CreateProfessionLinkButton("ATSWFrame", function()
return atsw_oldmode and C_TradeSkillUI.GetCraftListLink() or C_TradeSkillUI.GetTradeSkillListLink()
end)
end)
EventUtil.ContinueOnAddOnLoaded("AdvancedTradeSkillWindow2", function()
CreateProfessionLinkButton("ATSWFrame", function()
return ATSW_TradeSkill() and C_TradeSkillUI.GetTradeSkillListLink() or C_TradeSkillUI.GetCraftListLink()
end)
end)
-12
View File
@@ -1,12 +0,0 @@
if GetLocale() ~= "deDE" then return end
BINDING_NAME_FOCUSTARGET = "Fokus setzen";
BINDING_NAME_TARGETFOCUS = "Fokus anvisieren";
FOCUSTARGET = "Ziel als Fokus festlegen";
ITEMS_VARIABLE_QUANTITY = "%d |4IGegenstand:Gegenstände;";
ITEMS_EQUIPPED = "%d |4Gegenstand:Gegenstände; ausgerüstet";
ITEMS_IN_INVENTORY = "%d |4Gegenstand:Gegenstände; im Inventar";
ITEM_SLOTS_IGNORED = "%d |4Platz:Plätze; ignoriert";
ITEM_MISSING = "%s fehlt";
ITEMS_NOT_IN_INVENTORY = "%d |4Gegenstand fehlt:Gegenstände fehlen;";
TARGETFOCUS = "Fokussierte Einheit anvisieren";
-27
View File
@@ -1,27 +0,0 @@
BINDING_NAME_AOELOOT = "AoE Loot";
BINDING_NAME_FOCUSTARGET = "Focus Target";
BINDING_NAME_TARGETFOCUS = "Target Focus";
COPPER_AMOUNT_SYMBOL = "c";
FOCUSTARGET = "Focus Target";
GENERIC_FRACTION_STRING = "%d/%d";
GOLD_AMOUNT_SYMBOL = "g";
HOURS_MINUTES_SECONDS = "%.2d:%.2d:%.2d";
ITEM_DELTA_DESCRIPTION = "If you replace this item, the following stat changes will occur:";
ITEMS_EQUIPPED = "%d |4item:items; equipped";
ITEMS_IN_INVENTORY = "%d |4item:items; in inventory";
ITEMS_NOT_IN_INVENTORY = "%d |4item:items; missing";
ITEMS_VARIABLE_QUANTITY = "%d |4Item:Items;";
ITEM_MISSING = "%s missing";
ITEM_SLOTS_IGNORED = "%d |4slot:slots; ignored";
LARGE_NUMBER_SEPERATOR = ",";
MINUTES_SECONDS = "%.2d:%.2d";
PERCENTAGE_STRING = "%d%%";
SILVER_AMOUNT_SYMBOL = "s";
SLASH_CLEARFOCUS1 = "/clearfocus";
SLASH_CLEARFOCUS2 = "/clearfocus";
SLASH_EQUIP_SET1 = "/equipset";
SLASH_EQUIP_SET2 = "/equipset";
SLASH_FOCUS1 = "/focus";
SLASH_FOCUS2 = "/focus";
TARGETFOCUS = "Target Focus";
LINK_TRADESKILL_TOOLTIP = "Click here to create a link to your profession.";
-12
View File
@@ -1,12 +0,0 @@
if GetLocale() ~= "esES" then return end
BINDING_NAME_FOCUSTARGET = "Establecer objetivo";
BINDING_NAME_TARGETFOCUS = "Seleccionar enfocado";
FOCUSTARGET = "Establecer objetivo";
ITEMS_VARIABLE_QUANTITY = "%d |4objeto:objetos;";
ITEMS_EQUIPPED = "Equipado: %d |4objeto:objetos;";
ITEMS_IN_INVENTORY = "En inventario: %d |4objeto:objetos;";
ITEM_SLOTS_IGNORED = "Ignorado: %d |4casilla:casillas;";
ITEM_MISSING = "Falta: %s";
ITEMS_NOT_IN_INVENTORY = "Faltan: %d |4objeto:objetos;";
TARGETFOCUS = "Fijar unidad objetivo";
-12
View File
@@ -1,12 +0,0 @@
if GetLocale() ~= "frFR" then return end
BINDING_NAME_FOCUSTARGET = "Définir cible";
BINDING_NAME_TARGETFOCUS = "Reprendre cible";
FOCUSTARGET = "Définir la cible de focalisation";
ITEMS_VARIABLE_QUANTITY = "%d |4objet:objets;";
ITEMS_EQUIPPED = "%d |4objet:objets; équipés";
ITEMS_IN_INVENTORY = "%d |4objet:objets; dans l'inventaire";
ITEM_SLOTS_IGNORED = "%d |4emplacement ignoré:emplacements ignorés;";
ITEM_MISSING = "Objet manquant : %s";
ITEMS_NOT_IN_INVENTORY = "%d |4objet:objets; manquants";
TARGETFOCUS = "Cibler l'unité focalisée";
-12
View File
@@ -1,12 +0,0 @@
if GetLocale() ~= "ruRU" then return end
BINDING_NAME_FOCUSTARGET = "Запомненная цель";
BINDING_NAME_TARGETFOCUS = "Восстановить цель";
FOCUSTARGET = "Запомнить цель";
ITEMS_VARIABLE_QUANTITY = "%d |4предмет:предмета:предметов;";
ITEMS_EQUIPPED = "%d |4предмет экипирован:предмета экипировано:предметов экипировано;";
ITEMS_IN_INVENTORY = "%d |4предмет:предмета:предметов; в сумках";
ITEM_SLOTS_IGNORED = "%d |4ячейка пропущена:ячейки пропущены:ячейки пропущены;";
ITEM_MISSING = "Предмет для ячейки %s отсутствует";
ITEMS_NOT_IN_INVENTORY = "%d |4предмет отсутствует:предмета отсутствует:предметов отсутствуют;";
TARGETFOCUS = "Восстановить цель";
-12
View File
@@ -1,12 +0,0 @@
if GetLocale() ~= "zhCN" then return end
BINDING_NAME_FOCUSTARGET = "焦点目标";
BINDING_NAME_TARGETFOCUS = "目标焦点";
FOCUSTARGET = "设定焦点目标";
ITEMS_VARIABLE_QUANTITY = "%d件物品";
ITEMS_EQUIPPED = "已装备%d件物品";
ITEMS_IN_INVENTORY = "背包中有%d件物品";
ITEM_SLOTS_IGNORED = "忽略%d个栏位";
ITEM_MISSING = "%s缺失";
ITEMS_NOT_IN_INVENTORY = "缺少%d件物品";
TARGETFOCUS = "选中焦点目标";
-12
View File
@@ -1,12 +0,0 @@
if GetLocale() ~= "zhTW" then return end
BINDING_NAME_FOCUSTARGET = "鎖定目標";
BINDING_NAME_TARGETFOCUS = "選定鎖定目標";
FOCUSTARGET = "設定鎖定目標";
ITEMS_VARIABLE_QUANTITY = "%d件物品";
ITEMS_EQUIPPED = "裝備%d件物品";
ITEMS_IN_INVENTORY = "%d件物品在物品欄中";
ITEM_SLOTS_IGNORED = "忽略%d個欄位";
ITEM_MISSING = "缺少%s物品";
ITEMS_NOT_IN_INVENTORY = "缺少%d件物品";
TARGETFOCUS = "選定鎖定單位";
-217
View File
@@ -1,217 +0,0 @@
-- AoE Loot Test
--
-- /aoeloot opens a picker window listing every item in every lootable
-- corpse within click range. Clicking a row hands the (guid, itemID)
-- pair to C_Loot.LootUnitItem and re-scans so the picker refreshes
-- with whatever's left.
--
-- Known visual: each scan opens / closes loot windows in rapid
-- succession, so the Blizzard LootFrame flickers during the scan. This
-- addon intentionally doesn't suppress that — the goal is to exercise
-- the C++ surface, not to ship polished UI.
local MAX_ROWS = 24
local RESCAN_DELAY = 0.3 -- seconds; lets LootUnitItem complete before re-scan
-- ---------- UI scaffolding ----------
-- Frame geometry. Height is recomputed dynamically per scan so the
-- window only takes up as much screen real estate as the result count
-- needs — see `ResizeForRows`.
local FRAME_WIDTH = 320
local HEADER_HEIGHT = 64 -- title + status + insets; minimum frame height
local ROW_HEIGHT = 22
local frame = CreateFrame("Frame", "AoELootTestFrame", UIParent)
frame:SetWidth(FRAME_WIDTH)
frame:SetHeight(HEADER_HEIGHT)
frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
frame:SetBackdrop({
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
tile = true, tileSize = 32, edgeSize = 32,
insets = { left = 11, right = 12, top = 12, bottom = 11 },
})
frame:SetMovable(true)
frame:EnableMouse(true)
frame:RegisterForDrag("LeftButton")
-- Vanilla 1.12 fires script handlers with the frame set as the global
-- `this`, not as a `self` arg to the function. Passing `frame.StartMoving`
-- directly (the modern shortcut) breaks because the C method has no
-- `self` to operate on. Wrap in closures so `this:method()` resolves
-- correctly inside the handler.
frame:SetScript("OnDragStart", function() this:StartMoving() end)
frame:SetScript("OnDragStop", function() this:StopMovingOrSizing() end)
frame:Hide()
local title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
title:SetPoint("TOP", frame, "TOP", 0, -16)
title:SetText("AoE Loot")
local status = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
status:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -36)
status:SetText("")
local closeBtn = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
closeBtn:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -6, -6)
-- ---------- Row pool ----------
local rows = {}
local function CreateRow(parent, idx)
local row = CreateFrame("Button", nil, parent)
row:SetWidth(290)
row:SetHeight(20)
row:SetPoint("TOPLEFT", parent, "TOPLEFT", 15,
-54 - (idx - 1) * ROW_HEIGHT)
local icon = row:CreateTexture(nil, "ARTWORK")
icon:SetWidth(18); icon:SetHeight(18)
icon:SetPoint("LEFT", row, "LEFT", 0, 0)
row.icon = icon
local text = row:CreateFontString(nil, "OVERLAY", "GameFontNormal")
text:SetPoint("LEFT", icon, "RIGHT", 6, 0)
text:SetPoint("RIGHT", row, "RIGHT", 0, 0)
text:SetJustifyH("LEFT")
row.text = text
local hl = row:CreateTexture(nil, "HIGHLIGHT")
hl:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")
hl:SetBlendMode("ADD")
hl:SetAllPoints(row)
-- Tooltip on hover. The engine's native `SetHyperlink` does a
-- literal `SStrCmpI` of the input's first 5 chars against the
-- string `"item:"` at `.rdata` VA `0x00842D60` — anything that
-- starts with `|c...` (full link with color) or `|Hitem` (full
-- link without color) fails the prefix check with "Unknown link
-- type". Only the bare payload form survives.
--
-- We extract the payload from the engine's full link rather than
-- composing `item:ID:0:0:0` ourselves, so per-instance fields
-- (enchant / random-suffix / unique) survive round-trip and
-- "Stringy Wolf Meat of the Bear" tooltips correctly instead of
-- collapsing to the un-suffixed itemID.
row:SetScript("OnEnter", function()
if this.payload then
GameTooltip:SetOwner(this, "ANCHOR_RIGHT")
GameTooltip:SetHyperlink(this.payload)
GameTooltip:Show()
end
end)
row:SetScript("OnLeave", function() GameTooltip:Hide() end)
row:Hide()
return row
end
for i = 1, MAX_ROWS do
rows[i] = CreateRow(frame, i)
end
-- ---------- Render ----------
-- Tail of a GUID string — last 4 hex chars of the low dword. Lets the
-- user tell apart two rows of "Stringy Wolf Meat x1" coming from
-- different corpses, without occupying a whole column with the full
-- 16-digit GUID.
local function ShortGuidSuffix(guid)
return "[.." .. string.sub(guid, -4) .. "]"
end
-- Extract the `item:ID:enchant:suffix:unique` payload out of the
-- engine's full link string (`|cff...|Hitem:...|h[Name]|h|r`).
-- Vanilla `SetHyperlink` requires the input to start literally with
-- `"item:"` — so we can't pass the full link, but we also can't drop
-- the per-instance fields (random suffix is what distinguishes "of
-- the Bear" from "of the Eagle" on otherwise identical itemIDs).
-- Returns the payload, or nil if extraction fails.
local function PayloadFromLink(link)
if not link then return nil end
return string.match(link, "|H(item:[^|]+)|h")
end
local function ClearRows()
for i = 1, MAX_ROWS do
rows[i]:Hide()
rows[i]:SetScript("OnClick", nil)
rows[i].payload = nil
end
end
local function PopulateRows(results)
local idx = 0
for _, corpse in ipairs(results) do
for _, item in ipairs(corpse.items) do
idx = idx + 1
if idx > MAX_ROWS then break end
local row = rows[idx]
local name, _, _, _, _, _, _, _, icon = GetItemInfo(item.itemID)
row.icon:SetTexture(icon or "Interface\\Icons\\INV_Misc_QuestionMark")
local label = name or ("Item #" .. item.itemID)
if item.count and item.count > 1 then
label = label .. " x" .. item.count
end
label = label .. " " .. ShortGuidSuffix(corpse.guid)
row.text:SetText(label)
row.payload = PayloadFromLink(item.link) -- for OnEnter tooltip
local guid, itemID = corpse.guid, item.itemID
row:SetScript("OnClick", function()
C_Loot.LootUnitItem(guid, itemID)
C_Timer.After(RESCAN_DELAY, function()
if frame:IsShown() then C_Loot.ScanNearbyLoot() end
end)
end)
row:Show()
end
if idx > MAX_ROWS then break end
end
for i = idx + 1, MAX_ROWS do rows[i]:Hide() end
local shown
if idx == 0 then
status:SetText("Nothing lootable in range.")
shown = 0
elseif idx > MAX_ROWS then
status:SetText(MAX_ROWS .. "+ items (showing first " .. MAX_ROWS .. ")")
shown = MAX_ROWS
else
status:SetText(idx .. " item(s) available")
shown = idx
end
frame:SetHeight(HEADER_HEIGHT + shown * ROW_HEIGHT)
end
-- ---------- Scan trigger ----------
local function StartScan()
status:SetText("Scanning...")
ClearRows()
frame:SetHeight(HEADER_HEIGHT) -- collapse while we wait for results
if not C_Loot.ScanNearbyLoot() then
status:SetText("Scan busy or not in world.")
end
end
-- ---------- Event wiring ----------
local evt = CreateFrame("Frame")
evt:RegisterEvent("LOOT_SCAN_COMPLETED")
evt:SetScript("OnEvent", function()
-- Race guard: a delayed scan may complete after the user closed
-- the picker. Just drop the result rather than re-showing.
if not frame:IsShown() then return end
PopulateRows(C_Loot.GetLastScanResults())
end)
-- ---------- Slash command ----------
RegisterNewSlashCommand(function()
if frame:IsShown() then
StartScan() -- already open → just refresh
else
frame:Show()
StartScan()
end
end, "aoeloot", "aoe")
-7
View File
@@ -1,7 +0,0 @@
## Interface: 11200
## Title: AoE Loot Test
## Notes: Test bed for ClassicAPI's C_Loot.ScanNearbyLoot / LootUnitItem. /aoeloot
## Dependencies: !!!ClassicAPI
## Version: DEV
AoELootTest.lua
File diff suppressed because it is too large Load Diff
-11
View File
@@ -1,11 +0,0 @@
## Interface: 11200
## Title: UI Debug Tools
## Notes: Tools for developing addons (backport of Blizzard_DebugTools 3.3.5 to 1.12.1 / Lua 5.0)
## Author: Blizzard Entertainment, backported
## Special Thanks: Iriel, Kirov, Esamynn
## Version: 1.0
## SavedVariables: DebugToolsSavedVars
Dump.lua
DebugTools.lua
TableInspector.lua
DebugTools.xml
-571
View File
@@ -1,571 +0,0 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!-- ================================================================ -->
<!-- EventTrace -->
<!-- ================================================================ -->
<Button name="EventTraceEventTemplate" virtual="true">
<Size x="280" y="16"/>
<Layers>
<Layer level="ARTWORK">
<FontString name="$parentTime" inherits="NumberFontNormalSmall" justifyH="RIGHT">
<Anchors>
<Anchor point="TOPLEFT"/>
<Anchor point="TOPRIGHT" relativePoint="TOPLEFT">
<Offset x="62" y="0"/>
</Anchor>
<Anchor point="BOTTOM"/>
</Anchors>
</FontString>
<FontString name="$parentEvent" inherits="GameFontHighlightSmall" justifyH="LEFT">
<Anchors>
<Anchor point="TOPRIGHT"/>
<Anchor point="TOPLEFT">
<Offset x="70" y="0"/>
</Anchor>
<Anchor point="BOTTOM"/>
</Anchors>
</FontString>
</Layer>
</Layers>
<Scripts>
<OnLoad>
this:GetHighlightTexture():SetAlpha(.15);
</OnLoad>
<OnEnter>EventTraceFrameEvent_OnEnter(this);</OnEnter>
<OnLeave>EventTraceFrameEvent_OnLeave(this);</OnLeave>
<OnClick>EventTraceFrameEvent_OnClick(this);</OnClick>
</Scripts>
<HighlightTexture file="Interface\Buttons\UI-Common-MouseHilight" setAllPoints="true" alphaMode="ADD">
<Color r=".8" g=".8" b="1" a="1"/>
</HighlightTexture>
</Button>
<Frame name="EventTraceFrame" parent="UIParent" movable="true" hidden="true" frameStrata="MEDIUM" toplevel="true">
<Size x="306" y="484"/>
<Anchors>
<Anchor point="LEFT">
<Offset x="64" y="0"/>
</Anchor>
</Anchors>
<Backdrop bgFile="Interface\DialogFrame\UI-DialogBox-Background" edgeFile="Interface\Tooltips\UI-Tooltip-Border" tile="true">
<BackgroundInsets>
<AbsInset left="5" right="5" top="5" bottom="5"/>
</BackgroundInsets>
<TileSize>
<AbsValue val="16"/>
</TileSize>
<EdgeSize>
<AbsValue val="16"/>
</EdgeSize>
</Backdrop>
<Layers>
<Layer level="BACKGROUND">
<Texture name="$parentTitleBG" file="Interface\QuestFrame\UI-QuestLogTitleHighlight">
<Size x="280" y="20"/>
<Anchors>
<Anchor point="TOP">
<Offset x="0" y="-6"/>
</Anchor>
</Anchors>
<Color r=".6" g=".6" b=".6" a=".4"/>
</Texture>
</Layer>
<Layer level="OVERLAY">
<FontString name="$parentTitle" inherits="GameFontNormal" text="Events">
<Anchors>
<Anchor point="TOP">
<Offset x="0" y="-8"/>
</Anchor>
</Anchors>
</FontString>
</Layer>
</Layers>
<Frames>
<Button name="$parentCloseButton" inherits="UIPanelCloseButton">
<Anchors>
<Anchor point="TOPRIGHT">
<Offset x="-2" y="-2"/>
</Anchor>
</Anchors>
</Button>
<Frame name="$parentTitleButton">
<Size x="280" y="20"/>
<Anchors>
<Anchor point="TOP">
<Offset x="0" y="-6"/>
</Anchor>
</Anchors>
<Scripts>
<OnLoad>
this:RegisterForDrag("LeftButton");
</OnLoad>
<OnDragStart>
EventTraceFrame.moving = true;
EventTraceFrame:StartMoving();
</OnDragStart>
<OnDragStop>
EventTraceFrame.moving = nil;
EventTraceFrame:StopMovingOrSizing();
</OnDragStop>
</Scripts>
</Frame>
<!-- Pushed down 26px (was y=-28) to make room for the
toolbar row of Pause + Args/Time toggles + Search. -->
<Slider name="$parentScroll" orientation="VERTICAL">
<Size x="16" y="0"/>
<Anchors>
<Anchor point="TOPRIGHT">
<Offset x="-7" y="-54"/>
</Anchor>
<Anchor point="BOTTOMRIGHT">
<Offset x="-7" y="10"/>
</Anchor>
</Anchors>
<Layers>
<Layer level="BACKGROUND">
<Texture name="$parentBG" setAllPoints="true">
<Color r=".8" g=".8" b="1" a="0.1"/>
</Texture>
</Layer>
</Layers>
<Scripts>
<OnLoad>
this:SetFrameLevel(this:GetFrameLevel() + 1);
this:SetMinMaxValues(0, 1);
this:SetValue(0);
this:SetValueStep(1);
</OnLoad>
<OnValueChanged>
EventTraceFrame_Update();
</OnValueChanged>
</Scripts>
<ThumbTexture name="$parentThumb" file="Interface\Buttons\UI-ScrollBar-Knob">
<Size x="16" y="16"/>
<TexCoords left="0.25" right="0.75" top="0.25" bottom="0.75"/>
</ThumbTexture>
</Slider>
<!-- ===== Toolbar (Pause + Args/Time toggles + Search) ===== -->
<Button name="$parentPauseButton" inherits="UIPanelButtonTemplate" text="Pause">
<Size x="60" y="20"/>
<Anchors>
<Anchor point="TOPLEFT">
<Offset x="12" y="-30"/>
</Anchor>
</Anchors>
<Scripts>
<OnClick>EventTraceFrame_TogglePause();</OnClick>
</Scripts>
</Button>
<!-- `UICheckButtonTemplate`'s `$parentText` FontString is
auto-positioned at the right of the box. Vanilla 1.12
doesn't read a `text=` XML attribute (that came in
TBC); set it from OnLoad via the global lookup
instead. The earlier approach of separate sibling
FontStrings in the parent's `<Layers>` block fell
over because anchors that reference later-defined
siblings ($parentArgsCheck etc.) resolve to (0,0)
when the anchor is computed before the target exists. -->
<!-- Initial checked state is set here from defaults so the
first paint matches `_EventTraceFrame.showArguments`
/ `showTimestamp`. `_ApplySavedVars` later overrides
from `DebugToolsSavedVars` once ADDON_LOADED fires;
if the user toggled the box to a non-default value
in a prior session, the second SetChecked call wins. -->
<CheckButton name="$parentArgsCheck" inherits="UICheckButtonTemplate">
<Size x="20" y="20"/>
<Anchors>
<Anchor point="LEFT" relativeTo="$parentPauseButton" relativePoint="RIGHT">
<Offset x="4" y="0"/>
</Anchor>
</Anchors>
<Scripts>
<OnLoad>
getglobal(this:GetName() .. "Text"):SetText("Args");
this:SetChecked(nil); -- showArguments default = false
</OnLoad>
<OnClick>EventTraceFrame_ToggleArgs(this:GetChecked());</OnClick>
</Scripts>
</CheckButton>
<CheckButton name="$parentTimeCheck" inherits="UICheckButtonTemplate">
<Size x="20" y="20"/>
<Anchors>
<Anchor point="LEFT" relativeTo="$parentArgsCheck" relativePoint="RIGHT">
<Offset x="40" y="0"/>
</Anchor>
</Anchors>
<Scripts>
<OnLoad>
getglobal(this:GetName() .. "Text"):SetText("Time");
this:SetChecked(1); -- showTimestamp default = true
</OnLoad>
<OnClick>EventTraceFrame_ToggleTimestamp(this:GetChecked());</OnClick>
</Scripts>
</CheckButton>
<EditBox name="$parentSearch" inherits="InputBoxTemplate" autoFocus="false">
<Size x="100" y="20"/>
<Anchors>
<Anchor point="LEFT" relativeTo="$parentTimeCheck" relativePoint="RIGHT">
<Offset x="48" y="0"/>
</Anchor>
</Anchors>
<Scripts>
<OnTextChanged>EventTraceFrame_OnSearchChanged(this);</OnTextChanged>
<!-- Escape unfocuses but preserves text — clearing is
the X button's job. Modern WoW behaves the same. -->
<OnEscapePressed>this:ClearFocus();</OnEscapePressed>
</Scripts>
<Frames>
<!-- Embedded clear button: anchored inside the editbox
at the right edge, visible only while there's text.
Declared as a child so sibling z-order puts it
above the editbox's own backdrop textures. -->
<Button name="$parentClear" hidden="true">
<Size x="14" y="14"/>
<Anchors>
<Anchor point="RIGHT">
<Offset x="-4" y="0"/>
</Anchor>
</Anchors>
<Layers>
<Layer level="OVERLAY">
<FontString name="$parentLabel" inherits="GameFontNormalSmall" text="X">
<Anchors>
<Anchor point="CENTER"/>
</Anchors>
</FontString>
</Layer>
</Layers>
<Scripts>
<OnClick>
local eb = getglobal("EventTraceFrameSearch");
eb:SetText("");
eb:ClearFocus();
</OnClick>
</Scripts>
<HighlightTexture file="Interface\Buttons\UI-Common-MouseHilight" setAllPoints="true" alphaMode="ADD">
<Color r="1" g="1" b="1" a=".5"/>
</HighlightTexture>
</Button>
</Frames>
</EditBox>
</Frames>
<Scripts>
<OnLoad>EventTraceFrame_OnLoad(this);</OnLoad>
<OnEvent>EventTraceFrame_OnEvent(this, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);</OnEvent>
<OnUpdate>EventTraceFrame_OnUpdate(this, arg1);</OnUpdate>
</Scripts>
</Frame>
<!-- ================================================================ -->
<!-- ScriptErrorsFrame -->
<!-- ================================================================ -->
<Frame name="ScriptErrorsFrame" parent="UIParent" movable="true" hidden="true" toplevel="true" frameStrata="DIALOG" enableMouse="true">
<Size x="384" y="260"/>
<Anchors>
<Anchor point="CENTER"/>
</Anchors>
<Backdrop bgFile="Interface\DialogFrame\UI-DialogBox-Background" edgeFile="Interface\DialogFrame\UI-DialogBox-Border" tile="true">
<BackgroundInsets>
<AbsInset left="11" right="12" top="12" bottom="11"/>
</BackgroundInsets>
<TileSize>
<AbsValue val="32"/>
</TileSize>
<EdgeSize>
<AbsValue val="32"/>
</EdgeSize>
</Backdrop>
<Layers>
<Layer level="BACKGROUND">
<Texture name="$parentTitleBG" file="Interface\DialogFrame\UI-DialogBox-Header">
<Size x="256" y="64"/>
<Anchors>
<Anchor point="TOP">
<Offset x="0" y="12"/>
</Anchor>
</Anchors>
</Texture>
</Layer>
<Layer level="ARTWORK">
<FontString name="$parentTitle" inherits="GameFontNormal" text="Lua Error">
<Anchors>
<Anchor point="TOP">
<Offset x="0" y="-2"/>
</Anchor>
</Anchors>
</FontString>
<FontString name="$parentIndexLabel" inherits="GameFontNormal" justifyH="CENTER">
<Size x="70" y="16"/>
<Anchors>
<Anchor point="BOTTOM">
<Offset x="0" y="20"/>
</Anchor>
</Anchors>
</FontString>
</Layer>
</Layers>
<Frames>
<Frame name="$parentTitleButton">
<Size x="256" y="20"/>
<Anchors>
<Anchor point="TOP">
<Offset x="0" y="0"/>
</Anchor>
</Anchors>
<Scripts>
<OnLoad>
this:RegisterForDrag("LeftButton");
</OnLoad>
<OnDragStart>ScriptErrorsFrame_TitleButton_OnDragStart();</OnDragStart>
<OnDragStop>ScriptErrorsFrame_TitleButton_OnDragStop();</OnDragStop>
</Scripts>
</Frame>
<ScrollFrame name="$parentScrollFrame" inherits="UIPanelScrollFrameTemplate">
<Size x="343" y="170"/>
<Anchors>
<Anchor point="TOPLEFT">
<Offset x="16" y="-32"/>
</Anchor>
</Anchors>
<ScrollChild>
<EditBox name="$parentText" multiLine="true" letters="4000" autoFocus="false">
<Size x="343" y="170"/>
<Scripts>
<OnEscapePressed>this:ClearFocus();</OnEscapePressed>
<OnEditFocusGained>this:HighlightText(0);</OnEditFocusGained>
</Scripts>
<FontString inherits="GameFontHighlightSmall"/>
</EditBox>
</ScrollChild>
</ScrollFrame>
<Button name="$parentPrevious" inherits="UIPanelButtonTemplate" text="Previous" id="2">
<Size x="96" y="24"/>
<Anchors>
<Anchor point="BOTTOMLEFT">
<Offset x="16" y="16"/>
</Anchor>
</Anchors>
<Scripts>
<OnClick>ScriptErrorsFrameButton_OnClick(this);</OnClick>
</Scripts>
</Button>
<Button name="$parentNext" inherits="UIPanelButtonTemplate" text="Next" id="1">
<Size x="96" y="24"/>
<Anchors>
<Anchor point="BOTTOMLEFT">
<Offset x="116" y="16"/>
</Anchor>
</Anchors>
<Scripts>
<OnClick>ScriptErrorsFrameButton_OnClick(this);</OnClick>
</Scripts>
</Button>
<Button name="$parentClose" inherits="UIPanelButtonTemplate" text="Close">
<Size x="96" y="24"/>
<Anchors>
<Anchor point="BOTTOMRIGHT">
<Offset x="-16" y="16"/>
</Anchor>
</Anchors>
<Scripts>
<OnClick>ScriptErrorsFrame:Hide();</OnClick>
</Scripts>
</Button>
</Frames>
<Scripts>
<OnLoad>ScriptErrorsFrame_OnLoad(this);</OnLoad>
<OnShow>ScriptErrorsFrame_OnShow(this);</OnShow>
</Scripts>
</Frame>
<!-- ================================================================ -->
<!-- TableInspector -->
<!-- ================================================================ -->
<!-- Per-row button shared by every visible entry in the inspector.
Two FontStrings: key column on the left, value column on the
right. Highlight texture marks the hover row; click drills if
the value is a table. -->
<Button name="TableInspectorRowTemplate" virtual="true">
<Size x="440" y="16"/>
<Layers>
<Layer level="ARTWORK">
<FontString name="$parentKey" inherits="GameFontHighlightSmall" justifyH="LEFT">
<Size x="160" y="16"/>
<Anchors>
<Anchor point="TOPLEFT"/>
<Anchor point="BOTTOMLEFT"/>
</Anchors>
</FontString>
<FontString name="$parentValue" inherits="GameFontHighlightSmall" justifyH="LEFT">
<Anchors>
<Anchor point="TOPLEFT" relativeTo="$parentKey" relativePoint="TOPRIGHT">
<Offset x="6" y="0"/>
</Anchor>
<Anchor point="BOTTOMRIGHT"/>
</Anchors>
</FontString>
</Layer>
</Layers>
<Scripts>
<OnLoad>
this:GetHighlightTexture():SetAlpha(.15);
</OnLoad>
<OnClick>TableInspectorRow_OnClick(this);</OnClick>
</Scripts>
<HighlightTexture file="Interface\Buttons\UI-Common-MouseHilight" setAllPoints="true" alphaMode="ADD">
<Color r=".8" g=".8" b="1" a="1"/>
</HighlightTexture>
</Button>
<Frame name="TableInspectorFrame" parent="UIParent" movable="true" hidden="true" frameStrata="MEDIUM" toplevel="true">
<Size x="480" y="464"/>
<Anchors>
<Anchor point="CENTER"/>
</Anchors>
<Backdrop bgFile="Interface\DialogFrame\UI-DialogBox-Background" edgeFile="Interface\Tooltips\UI-Tooltip-Border" tile="true">
<BackgroundInsets>
<AbsInset left="5" right="5" top="5" bottom="5"/>
</BackgroundInsets>
<TileSize>
<AbsValue val="16"/>
</TileSize>
<EdgeSize>
<AbsValue val="16"/>
</EdgeSize>
</Backdrop>
<Layers>
<Layer level="BACKGROUND">
<Texture name="$parentTitleBG" file="Interface\QuestFrame\UI-QuestLogTitleHighlight">
<Size x="454" y="20"/>
<Anchors>
<Anchor point="TOP">
<Offset x="0" y="-6"/>
</Anchor>
</Anchors>
<Color r=".6" g=".6" b=".6" a=".4"/>
</Texture>
</Layer>
<Layer level="OVERLAY">
<FontString name="$parentTitle" inherits="GameFontNormal" text="Table Inspector">
<Anchors>
<Anchor point="TOP">
<Offset x="0" y="-8"/>
</Anchor>
</Anchors>
</FontString>
<!-- Breadcrumb showing the active navigation path,
e.g. "_G > MyFrame > backdrop". Updated each
`TableInspectorFrame_Update` tick. -->
<FontString name="$parentBreadcrumb" inherits="GameFontHighlightSmall" justifyH="LEFT">
<Size x="380" y="16"/>
<Anchors>
<Anchor point="TOPLEFT">
<Offset x="80" y="-34"/>
</Anchor>
</Anchors>
</FontString>
</Layer>
</Layers>
<Frames>
<Button name="$parentCloseButton" inherits="UIPanelCloseButton">
<Anchors>
<Anchor point="TOPRIGHT">
<Offset x="-2" y="-2"/>
</Anchor>
</Anchors>
<Scripts>
<OnClick>TableInspector_Close();</OnClick>
</Scripts>
</Button>
<Frame name="$parentTitleButton">
<Size x="280" y="20"/>
<Anchors>
<Anchor point="TOP">
<Offset x="0" y="-6"/>
</Anchor>
</Anchors>
<Scripts>
<OnLoad>
this:RegisterForDrag("LeftButton");
</OnLoad>
<OnDragStart>
TableInspectorFrame:StartMoving();
</OnDragStart>
<OnDragStop>
TableInspectorFrame:StopMovingOrSizing();
</OnDragStop>
</Scripts>
</Frame>
<Button name="$parentBackButton" inherits="UIPanelButtonTemplate" text="&lt; Back">
<Size x="60" y="20"/>
<Anchors>
<Anchor point="TOPLEFT">
<Offset x="12" y="-32"/>
</Anchor>
</Anchors>
<Scripts>
<OnClick>TableInspector_Back();</OnClick>
</Scripts>
</Button>
<Slider name="$parentScroll" orientation="VERTICAL">
<Size x="16" y="0"/>
<Anchors>
<Anchor point="TOPRIGHT">
<Offset x="-7" y="-56"/>
</Anchor>
<Anchor point="BOTTOMRIGHT">
<Offset x="-7" y="10"/>
</Anchor>
</Anchors>
<Layers>
<Layer level="BACKGROUND">
<Texture name="$parentBG" setAllPoints="true">
<Color r=".8" g=".8" b="1" a="0.1"/>
</Texture>
</Layer>
</Layers>
<Scripts>
<OnLoad>
this:SetFrameLevel(this:GetFrameLevel() + 1);
this:SetMinMaxValues(0, 1);
this:SetValue(0);
this:SetValueStep(1);
</OnLoad>
<OnValueChanged>
TableInspectorFrame_Update();
</OnValueChanged>
</Scripts>
<ThumbTexture name="$parentThumb" file="Interface\Buttons\UI-ScrollBar-Knob">
<Size x="16" y="16"/>
<TexCoords left="0.25" right="0.75" top="0.25" bottom="0.75"/>
</ThumbTexture>
</Slider>
</Frames>
<Scripts>
<OnLoad>TableInspectorFrame_OnLoad(this);</OnLoad>
</Scripts>
</Frame>
<!-- ================================================================ -->
<!-- Tooltips -->
<!-- ================================================================ -->
<GameTooltip name="FrameStackTooltip" frameStrata="TOOLTIP" hidden="true" parent="UIParent" inherits="GameTooltipTemplate">
<Scripts>
<OnLoad>DebugTooltip_OnLoad(this);</OnLoad>
<OnShow>FrameStackTooltip_OnShow(this);</OnShow>
<OnEnter>FrameStackTooltip_OnEnter(this);</OnEnter>
<OnUpdate>FrameStackTooltip_OnUpdate(this, arg1);</OnUpdate>
</Scripts>
</GameTooltip>
<GameTooltip name="EventTraceTooltip" frameStrata="TOOLTIP" hidden="true" parent="EventTraceFrame" inherits="GameTooltipTemplate">
<Scripts>
<OnLoad>DebugTooltip_OnLoad(this);</OnLoad>
</Scripts>
</GameTooltip>
</Ui>
-327
View File
@@ -1,327 +0,0 @@
------------------------------------------------------------------------------
-- TableInspector.lua
--
-- Vanilla 1.12 backport of the modern Blizzard_TableInspector UX,
-- scoped to the "minimal" feature set: one navigable window with a
-- breadcrumb showing the current path, a scrollable list of (key,
-- value) rows for the current table, and click-to-drill / Back-to-pop
-- navigation through sub-tables.
--
-- Trade-offs vs the modern source:
-- * No DataProvider / ScrollBox infrastructure — we use the same
-- fixed-row + slider pattern EventTraceFrame uses (vanilla
-- FauxScrollFrame works too but we already validated the slider
-- approach in this addon).
-- * No anchor / attribute providers, no live polling — open once
-- against the current snapshot.
-- * No multi-tab or pinning — one window, navigate via Back.
--
-- API:
-- TableInspector_Show(tbl, label) -- open with `tbl` as root, `label` shown in breadcrumb
-- TableInspector_Push(tbl, label) -- drill in (called by row click)
-- TableInspector_Back() -- pop one level
-- TableInspector_Close() -- hide the window
-- /tinspect <luaexpr> -- evaluate `<luaexpr>` as Lua and open if result is a table
------------------------------------------------------------------------------
TABLE_INSPECTOR_ROW_HEIGHT = 16;
TABLE_INSPECTOR_NUM_ROWS = 22;
local _TableInspectorFrame;
-- Navigation stack — `{ {tbl=..., label=...}, ... }`. The last entry
-- is the active view. Push when drilling in, pop on Back.
local _navStack = {};
------------------------------------------------------------------------------
-- Key + value formatting
------------------------------------------------------------------------------
-- Returns three lists: numeric keys (sorted ascending), string keys
-- (sorted), and other-type keys (booleans, tables-as-keys, etc.).
-- The other-type bucket stays unsorted — there's no canonical order
-- across types and these are rare in practice.
local function _SortedKeys(tbl)
local nums, strs, others = {}, {}, {};
for k in pairs(tbl) do
local t = type(k);
if (t == "number") then
table.insert(nums, k);
elseif (t == "string") then
table.insert(strs, k);
else
table.insert(others, k);
end
end
table.sort(nums);
table.sort(strs);
return nums, strs, others;
end
-- Returns (displayText, valueType, isDrillable). `isDrillable` is true
-- only for tables (the only type that can be navigated into).
local function _FormatValue(v)
local t = type(v);
if (t == "string") then
-- Truncate very long strings to keep rows scannable; user can
-- always tooltip-hover for the full content if needed.
if (string.len(v) > 80) then
return string.format('"%s..."', string.sub(v, 1, 77)), "string", false;
end
return string.format('"%s"', v), "string", false;
elseif (t == "number") then
return tostring(v), "number", false;
elseif (t == "boolean") then
return v and "true" or "false", "boolean", false;
elseif (t == "table") then
return tostring(v), "table", true;
elseif (t == "function") then
return tostring(v), "function", false;
elseif (t == "userdata") then
return tostring(v), "userdata", false;
end
return tostring(v), t, false;
end
local _TYPE_COLORS = {
["string"] = { 1.00, 0.75, 0.40 },
["number"] = { 0.60, 0.85, 1.00 },
["boolean"] = { 0.70, 0.70, 1.00 },
["table"] = { 0.60, 1.00, 0.60 },
["function"] = { 1.00, 0.60, 0.60 },
["userdata"] = { 1.00, 0.60, 0.60 },
};
local function _ValueColor(t)
local c = _TYPE_COLORS[t];
if (c) then return c[1], c[2], c[3]; end
return 1, 1, 1;
end
local function _FormatKey(k)
local t = type(k);
if (t == "string") then return k; end
if (t == "number") then return string.format("[%d]", k); end
return string.format("[%s]", tostring(k));
end
------------------------------------------------------------------------------
-- View state — manages the flattened (key, value) list for the active
-- table. Rebuilt on push / pop, not on every Update tick.
------------------------------------------------------------------------------
-- Cached array of (key, value) tuples for the active table, in the
-- sort order returned by _SortedKeys. Re-derived on every navigation
-- change so the rows can be rendered by simple `entries[scroll + i]`
-- indexing instead of walking `pairs()` mid-frame.
local _entries = {};
local function _RebuildEntries()
_entries = {};
local top = _navStack[table.getn(_navStack)];
if (not top or type(top.tbl) ~= "table") then return; end
local nums, strs, others = _SortedKeys(top.tbl);
for i = 1, table.getn(nums) do
local k = nums[i];
table.insert(_entries, { key = k, value = top.tbl[k] });
end
for i = 1, table.getn(strs) do
local k = strs[i];
table.insert(_entries, { key = k, value = top.tbl[k] });
end
for i = 1, table.getn(others) do
local k = others[i];
table.insert(_entries, { key = k, value = top.tbl[k] });
end
end
local function _Breadcrumb()
local parts = {};
for i = 1, table.getn(_navStack) do
table.insert(parts, _navStack[i].label or "?");
end
return table.concat(parts, " > ");
end
------------------------------------------------------------------------------
-- Public API
------------------------------------------------------------------------------
function TableInspector_Show(tbl, label)
if (type(tbl) ~= "table") then
DEFAULT_CHAT_FRAME:AddMessage(
"|cffff8888TableInspector: argument is not a table|r");
return;
end
_navStack = { { tbl = tbl, label = label or tostring(tbl) } };
_RebuildEntries();
if (_TableInspectorFrame) then
_TableInspectorFrame:Show();
TableInspectorFrame_Update();
end
end
function TableInspector_Push(tbl, label)
if (type(tbl) ~= "table") then return; end
table.insert(_navStack, { tbl = tbl, label = label or tostring(tbl) });
_RebuildEntries();
-- Reset scroll to top so the user starts at the beginning of the
-- newly-drilled table.
local scroll = getglobal("TableInspectorFrameScroll");
if (scroll) then scroll:SetValue(0); end
TableInspectorFrame_Update();
end
function TableInspector_Back()
if (table.getn(_navStack) <= 1) then
TableInspector_Close();
return;
end
table.remove(_navStack);
_RebuildEntries();
local scroll = getglobal("TableInspectorFrameScroll");
if (scroll) then scroll:SetValue(0); end
TableInspectorFrame_Update();
end
function TableInspector_Close()
if (_TableInspectorFrame) then _TableInspectorFrame:Hide(); end
_navStack = {};
_entries = {};
end
------------------------------------------------------------------------------
-- Frame scripts (called from TableInspector XML in DebugTools.xml)
------------------------------------------------------------------------------
function TableInspectorFrame_OnLoad(self)
self.rows = {};
_TableInspectorFrame = self;
self:EnableMouse(true);
self:EnableMouseWheel(true);
self:SetScript("OnMouseWheel", function()
TableInspectorFrame_OnMouseWheel(this, arg1);
end);
for i = 1, TABLE_INSPECTOR_NUM_ROWS do
local row = CreateFrame("Button", "TableInspectorFrameRow" .. i, self,
"TableInspectorRowTemplate");
row:SetPoint("TOPLEFT", 12, -(56 + (i - 1) * TABLE_INSPECTOR_ROW_HEIGHT));
row:SetPoint("RIGHT", -28, 0);
row.rowIndex = i;
table.insert(self.rows, row);
end
end
function TableInspectorFrame_Update()
if (not _TableInspectorFrame or not _TableInspectorFrame.rows) then return; end
local scroll = getglobal("TableInspectorFrameScroll");
if (not scroll) then return; end
local total = table.getn(_entries);
local visible = TABLE_INSPECTOR_NUM_ROWS;
local maxOffset = math.max(0, total - visible);
scroll:SetMinMaxValues(0, maxOffset);
local offset = math.floor(scroll:GetValue() + 0.5);
if (offset > maxOffset) then offset = maxOffset; end
if (offset < 0) then offset = 0; end
-- Update breadcrumb each tick — cheap (string concat over a tiny
-- nav stack) and avoids a separate "breadcrumb changed" signal.
local crumb = getglobal("TableInspectorFrameBreadcrumb");
if (crumb) then
crumb:SetText(_Breadcrumb() .. string.format(" (%d entries)", total));
end
for i = 1, visible do
local row = _TableInspectorFrame.rows[i];
local entry = _entries[offset + i];
if (entry) then
local keyFS = getglobal(row:GetName() .. "Key");
local valFS = getglobal(row:GetName() .. "Value");
keyFS:SetText(_FormatKey(entry.key));
local disp, vt, drillable = _FormatValue(entry.value);
valFS:SetText(disp);
valFS:SetTextColor(_ValueColor(vt));
row.entryKey = entry.key;
row.entryValue = entry.value;
row.drillable = drillable;
row:Show();
else
row.entryKey = nil;
row.entryValue = nil;
row.drillable = false;
row:Hide();
end
end
end
function TableInspectorFrame_OnMouseWheel(self, delta)
local scroll = getglobal("TableInspectorFrameScroll");
if (not scroll) then return; end
local mn, mx = scroll:GetMinMaxValues();
local v = scroll:GetValue() - delta * 3;
if (v < mn) then v = mn; end
if (v > mx) then v = mx; end
scroll:SetValue(v);
end
function TableInspectorRow_OnClick(self)
if (not self.drillable or type(self.entryValue) ~= "table") then return; end
TableInspector_Push(self.entryValue, _FormatKey(self.entryKey));
end
------------------------------------------------------------------------------
-- Slash command — /tinspect <luaexpr>
--
-- Evaluates `<luaexpr>` in a fresh chunk with `return ` prefixed, so
-- bare expressions (`_G`, `GameTooltip`, `MyAddOn.foo`) work without
-- the user having to write `return ...` themselves.
------------------------------------------------------------------------------
local function _ChatErr(msg)
DEFAULT_CHAT_FRAME:AddMessage("|cffff8888TableInspector:|r " .. msg);
end
function TableInspector_HandleSlashCmd(msg)
if (not msg) then msg = ""; end
msg = string.gsub(msg, "^%s*(.-)%s*$", "%1"); -- trim
if (msg == "" or msg == "help") then
DEFAULT_CHAT_FRAME:AddMessage(
"|cff88ff88/tinspect|r <expr> -- open inspector on the result of <expr>");
DEFAULT_CHAT_FRAME:AddMessage(" example: /tinspect _G");
DEFAULT_CHAT_FRAME:AddMessage(" example: /tinspect ChatTypeInfo");
return;
end
if (msg == "close") then
TableInspector_Close();
return;
end
local chunk, parseErr = loadstring("return " .. msg);
if (not chunk) then
_ChatErr("parse error: " .. tostring(parseErr));
return;
end
-- Run in the global environment so the user's expression sees
-- the usual addon globals. setfenv on the loadstring chunk
-- defaults to that already in vanilla, but be explicit.
setfenv(chunk, getfenv(0));
local ok, result = pcall(chunk);
if (not ok) then
_ChatErr("eval error: " .. tostring(result));
return;
end
if (type(result) ~= "table") then
_ChatErr(string.format(
"result is %s (%s), expected table",
type(result), tostring(result)));
return;
end
TableInspector_Show(result, msg);
end
SLASH_TINSPECT1 = "/tinspect";
SLASH_TINSPECT2 = "/tins";
SlashCmdList["TINSPECT"] = TableInspector_HandleSlashCmd;
+105 -60
View File
@@ -1,6 +1,21 @@
cmake_minimum_required(VERSION 3.10)
project(ClassicAPI LANGUAGES CXX)
project(ClassicAPI LANGUAGES CXX RC)
# WoW.exe is x86, so the injected DLL must be x86 too — there is no valid
# 64-bit configure of this project. Fail here rather than let one through:
# a 64-bit build's first visible symptom is a static_assert deep in a
# struct-layout check, which reads as an unrelated code fault. An IDE that
# configures on its own (VS Code's CMake Tools picks an architecture from a
# scanned kit) can flip an existing build directory this way, which is what
# CMakePresets.json's `win32` preset exists to prevent.
if(NOT CMAKE_SIZEOF_VOID_P EQUAL 4)
message(FATAL_ERROR
"ClassicAPI builds 32-bit only. This configure uses "
"${CMAKE_SIZEOF_VOID_P}-byte pointers. Delete the build directory, "
"because CMake cannot switch platform in place. Then configure with "
"`cmake --preset win32` or `cmake -B build -A Win32`.")
endif()
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -25,69 +40,32 @@ set(TINYCBOR_SOURCES
external/tinycbor/src/cborparser_float.c
external/tinycbor/src/cborerrorstrings.c)
# Bundle `AddOns/!!!ClassicAPI/` into a generated header so the DLL can
# surface the addon to the engine even when the user doesn't have it
# installed on disk. The file-read hook in `src/addons/Embedded.cpp`
# returns these buffers when the engine asks for paths under
# `Interface\AddOns\!!!ClassicAPI\`.
set(EMBEDDED_CLASSICAPI_SRC "${CMAKE_CURRENT_SOURCE_DIR}/AddOns/!!!ClassicAPI")
set(EMBEDDED_CLASSICAPI_HEADER "${CMAKE_BINARY_DIR}/generated/embedded_classicapi.h")
file(GLOB_RECURSE EMBEDDED_CLASSICAPI_FILES CONFIGURE_DEPENDS
"${EMBEDDED_CLASSICAPI_SRC}/*")
add_custom_command(
OUTPUT "${EMBEDDED_CLASSICAPI_HEADER}"
COMMAND ${CMAKE_COMMAND}
-DSRC_DIR=${EMBEDDED_CLASSICAPI_SRC}
-DOUT_HEADER=${EMBEDDED_CLASSICAPI_HEADER}
-DADDON_NAME=ClassicAPI
-P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed_addon.cmake"
DEPENDS
${EMBEDDED_CLASSICAPI_FILES}
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed_addon.cmake"
COMMENT "Embedding !!!ClassicAPI addon into ${EMBEDDED_CLASSICAPI_HEADER}"
VERBATIM)
# Bundle `src/bindings/Bindings.xml` (our TARGETING-group additions)
# into a generated header. `src/bindings/Inject.cpp` extracts the
# inner `<Binding>` elements from the embedded buffer and splices them
# into the engine's `Interface\FrameXML\Bindings.xml` at load time.
set(EMBEDDED_BINDINGS_SRC "${CMAKE_CURRENT_SOURCE_DIR}/src/bindings/Bindings.xml")
set(EMBEDDED_BINDINGS_HEADER "${CMAKE_BINARY_DIR}/generated/embedded_bindings.h")
add_custom_command(
OUTPUT "${EMBEDDED_BINDINGS_HEADER}"
COMMAND ${CMAKE_COMMAND}
-DINPUT_FILE=${EMBEDDED_BINDINGS_SRC}
-DOUT_HEADER=${EMBEDDED_BINDINGS_HEADER}
-DSYMBOL=kEmbeddedBindingsXml
-P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed_file.cmake"
DEPENDS
"${EMBEDDED_BINDINGS_SRC}"
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed_file.cmake"
COMMENT "Embedding bindings XML into ${EMBEDDED_BINDINGS_HEADER}"
VERBATIM)
add_library(${PROJECT_NAME} SHARED
${SOURCES} ${HEADERS} ${TINYCBOR_SOURCES}
${EMBEDDED_CLASSICAPI_HEADER}
${EMBEDDED_BINDINGS_HEADER})
# Dev-build sentinel — represents "newer than every plausible
# release". Encoded as v9999.99.99 = 9999 * 10000 + 99 * 100 + 99 =
# 99,999,999. Picked so addon-side feature gates of the form
# `CLASSIC_API_VERSION >= X` always pass during local development;
# CI release builds overwrite it via `-DCLASSICAPI_TAG=vX.Y.Z`.
# Version derivation. Dev builds use a sentinel "newer than every
# plausible release" so addon-side `CLASSIC_API_VERSION >= X` gates
# always pass locally. CI release builds pass `-DCLASSICAPI_TAG=vX.Y.Z`,
# which drives BOTH the compiled `CLASSIC_API_VERSION` int AND the
# embedded addon's `## Version:` toc line (substituted in
# embed_resources.cmake). The on-disk source toc stays `## Version: DEV`;
# only the embedded copy is stamped, so a release build needs nothing
# but the flag — no source edit.
set(CLASSICAPI_VERSION_VALUE 99999999)
set(CLASSICAPI_VER_MAJOR 9999)
set(CLASSICAPI_VER_MINOR 99)
set(CLASSICAPI_VER_PATCH 99)
set(CLASSICAPI_TOC_VERSION "DEV")
set(CLASSICAPI_TAG
""
CACHE STRING "Release tag like v1.2.3")
if(CLASSICAPI_TAG MATCHES "^v([0-9]+)\\.([0-9]+)\\.([0-9]+)$")
set(_MAJOR "${CMAKE_MATCH_1}")
set(_MINOR "${CMAKE_MATCH_2}")
set(_PATCH "${CMAKE_MATCH_3}")
set(CLASSICAPI_VER_MAJOR "${CMAKE_MATCH_1}")
set(CLASSICAPI_VER_MINOR "${CMAKE_MATCH_2}")
set(CLASSICAPI_VER_PATCH "${CMAKE_MATCH_3}")
math(EXPR CLASSICAPI_VERSION_VALUE
"${_MAJOR} * 10000 + ${_MINOR} * 100 + ${_PATCH}")
"${CLASSICAPI_VER_MAJOR} * 10000 + ${CLASSICAPI_VER_MINOR} * 100 + ${CLASSICAPI_VER_PATCH}")
set(CLASSICAPI_TOC_VERSION
"${CLASSICAPI_VER_MAJOR}.${CLASSICAPI_VER_MINOR}.${CLASSICAPI_VER_PATCH}")
elseif(CLASSICAPI_TAG)
message(
FATAL_ERROR
@@ -95,26 +73,93 @@ elseif(CLASSICAPI_TAG)
)
endif()
add_library(${PROJECT_NAME} SHARED
${SOURCES} ${HEADERS} ${TINYCBOR_SOURCES})
# Embed the addons under `src/embed/AddOns/`, `src/bindings/Bindings.xml` and
# the textures under `src/embed/Textures/` as RCDATA resources. The file-read
# hook in `src/addons/Embedded.cpp` serves the addon files when the engine
# asks for paths under `Interface\AddOns\<addon>\`, so the addons load even
# when the user doesn't have them on disk. `src/bindings/Inject.cpp` splices
# the bindings XML (our TARGETING-group additions) into the engine's
# `Interface\FrameXML\Bindings.xml` at load time. `src/texture/Builtin.cpp`
# serves each texture at its game path when no file has it.
include(cmake/embed_resources.cmake)
embed_resources(
TARGET ${PROJECT_NAME}
ADDONS_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/src/embed/AddOns"
ADDONS "!!!ClassicAPI" "ClassicAPI_DebugTools" "ClassicAPI_EventTrace"
ADDON_VERSION "${CLASSICAPI_TOC_VERSION}"
BINDINGS_XML "${CMAKE_CURRENT_SOURCE_DIR}/src/bindings/Bindings.xml"
TEXTURES_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/src/embed/Textures"
OUT_DIR "${CMAKE_BINARY_DIR}/generated")
target_compile_definitions(
${PROJECT_NAME}
PRIVATE CLASSICAPI_VERSION_VALUE=${CLASSICAPI_VERSION_VALUE})
# Stamp the PE VERSIONINFO resource from the same version components, so the
# DLL's file/product version (Explorer -> Properties -> Details) matches the
# CLASSIC_API_VERSION Lua global.
set(CLASSICAPI_VER_STRING
"${CLASSICAPI_VER_MAJOR}.${CLASSICAPI_VER_MINOR}.${CLASSICAPI_VER_PATCH}.0")
set(CLASSICAPI_VERSION_RC "${CMAKE_BINARY_DIR}/generated/version.rc")
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/version.rc.in"
"${CLASSICAPI_VERSION_RC}"
@ONLY)
target_sources(${PROJECT_NAME} PRIVATE "${CLASSICAPI_VERSION_RC}")
# The .def exports `Load` (VanillaFixes' post-injection entry point)
# undecorated so its GetProcAddress(module, "Load") resolves. See the
# loader-lock rationale in src/DllMain.cpp. Listed as a source so CMake emits
# a quoted /DEF: on every generator and relinks when the file changes.
target_sources(${PROJECT_NAME} PRIVATE src/ClassicAPI.def)
# ole32: COM (CoInitializeEx / CoCreateInstance / CoTaskMemFree) for the
# SAPI text-to-speech backend in src/voicechat/Tts.cpp. The SAPI GUIDs are
# instantiated in that TU via <initguid.h>, so no sapi.lib is needed.
target_link_libraries(${PROJECT_NAME} PRIVATE minhook advapi32 ole32)
# user32: Win32 clipboard API (OpenClipboard / SetClipboardData) for
# CopyToClipboard in src/clipboard/Copy.cpp.
target_link_libraries(${PROJECT_NAME} PRIVATE minhook advapi32 ole32 user32)
target_include_directories(
${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src
${CMAKE_BINARY_DIR}/generated
external/minhook/include
external
external/tinycbor/src)
external/tinycbor/src
external/unordered_dense/include)
set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME "ClassicAPI")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MT")
set(CMAKE_CXX_FLAGS_RELEASE "/MT /O2 /Ob2 /DNDEBUG")
# /O1 optimizes for size: the code is mostly short glue around engine calls,
# and /O1 made the DLL 280 KB smaller than /O2 /Ob2 (link-time code generation,
# /GL + /LTCG, made it larger again). /Zi retains full debug info (source file +
# line numbers, locals, types) in a separate PDB WITHOUT disabling
# optimization; the symbols just live in ClassicAPI.pdb on the side. Feeds the
# linker's /DEBUG below.
set(CMAKE_CXX_FLAGS_RELEASE "/MT /O1 /DNDEBUG /Zi")
set(CMAKE_SHARED_LINKER_FLAGS
"/OPT:REF /OPT:ICF /MERGE:.rdata=.text /MERGE:.pdata=.text /SECTION:.text,EWR /NODEFAULTLIB:MSVCRT"
# Two debug artifacts for triaging crashes from a SHIPPED DLL. Both are
# published as release artifacts, match this exact build, and have no effect
# on code layout:
# /MAP -> build/Release/ClassicAPI.map: a text symbol->address table
# that resolves the `0001:offset` addresses in WoW's ERROR #132
# crash log back to functions by hand (no debugger/dump needed).
# /DEBUG -> build/Release/ClassicAPI.pdb: full symbols (paired with the
# compiler's /Zi) so WinDbg/x64dbg/VS produce a line-level
# symbolicated call stack from a crash dump. A SEPARATE file —
# it is NOT embedded in the DLL, only a small signature record
# linking the two is.
# /DEBUG implicitly disables /OPT:REF and /OPT:ICF (dead-code strip +
# identical-COMDAT fold); they are listed explicitly below so they stay ON
# and the shipped DLL does not grow. (/OPT:ICF folds identical functions, so
# a few map symbols share an address — harmless.)
# The sections keep the standard layout: .text is read + execute only and
# constants stay in a read-only .rdata. Nothing writes into this DLL's own
# code; engine patches make their target writable themselves
# (Common::PatchBytes).
"/OPT:REF /OPT:ICF /NODEFAULTLIB:MSVCRT /MAP /DEBUG"
)
+25
View File
@@ -0,0 +1,25 @@
{
"version": 3,
"cmakeMinimumRequired": {
"major": 3,
"minor": 21,
"patch": 0
},
"configurePresets": [
{
"name": "win32",
"displayName": "Win32 (x86)",
"description": "The only supported configuration: WoW.exe is 32-bit, so the DLL must be 32-bit too. No generator is named, so CMake picks the newest installed Visual Studio, matching the documented command line.",
"binaryDir": "${sourceDir}/build",
"architecture": "Win32"
}
],
"buildPresets": [
{
"name": "release",
"displayName": "Release",
"configurePreset": "win32",
"configuration": "Release"
}
]
}
+392 -127
View File
@@ -1,79 +1,157 @@
# ClassicAPI
A small DLL for World of Warcraft 1.12.1 (Vanilla / Turtle WoW) that adds a
collection of Lua API calls Blizzard never exposed in 1.12 but which make
addon authoring noticeably less painful — primarily for backporting addons
written against later API versions (3.3.5+) where these calls do exist.
ClassicAPI is a DLL for World of Warcraft 1.12.1 (Vanilla / Turtle WoW). It
backports a large part of the modern WoW API — 950+ functions and 80+ events,
plus much of Lua 5.1 — into the 1.12 client, so addons written for later
versions (3.3.5+ or Classic Era) run with little or no change.
The DLL hooks the FrameScript engine after WoW boots and registers its
extensions through the same in-engine mechanisms WoW uses for its own Lua
functions. No companion addon is required.
It hooks the engine after WoW boots and registers everything the same way WoW
registers its own Lua functions. Nothing else to install — the DLL is
self-contained.
## What's added
## Highlights
Full per-function reference: **[docs/API.md](docs/API.md)**.
The headline features. Each one takes effect as soon as the DLL loads, so your
existing addons benefit without any code changes. The complete per-function
reference is in **[docs/API.md](docs/API.md)**.
### Calls
| Feature | Effect |
|---------|--------|
| Lua 5.1 code | Addon code written for Lua 5.1 runs on the 1.12 Lua 5.0 VM. It covers the [5.1 syntax](docs/API.md#lua-51-syntax) (`#`, `%`, `...` expressions, `0x` hex, `[=[ ]=]` long brackets), [method calls on strings](docs/API.md#string-methods-supper-sformat) (`msg:match("^!(%w+)")`), [up to 60 upvalues](docs/API.md#upvalue-limit) for each function, and [new `for` loop variables](docs/API.md#for-loop-variables-per-pass) on each pass. Each addon file also gets its `(name, table)` through `...`. |
| [Modern script handlers](docs/API.md#setmodernscriptargsenable--getmodernscriptargs) | Frame scripts get their values as arguments, for example `OnClick(self, button, down)` and `OnEvent(self, event, ...)`. [XML script bodies](docs/API.md#xml-script-bodies-see-self-and-their-arguments) such as `<OnLoad>self:Init()</OnLoad>` see `self` and their arguments by name. The `this` / `arg1` globals stay set. `SetModernScriptArgs(false)` restores the vanilla behavior. |
| Inline textures | Draws inline texture markup (`\|T…\|t`) and atlas markup (`\|A…\|a`) as icons in FontStrings, chat, and tooltips. This covers item and spell icons, raid-target markers, and the coin icons in money strings. `GetStringWidth` and `GetStringHeight` count the icons, so measured width and text wrapping stay correct. Done in pure C++ by hooking the engine's text pipeline — no addon. |
| [Soft targeting](docs/API.md#soft-interact-softinteract--anyinteract) | The Interact Key and soft targets. Bind **Interact With Target** to a key to interact with the nearest NPC, corpse, mailbox, chest or gathering node in front of you. The [`softenemy` and `softfriend`](docs/API.md#soft-enemy-and-soft-friend-softenemy--softfriend--anyenemy--anyfriend) tokens point at the nearest enemy and friendly unit without a change of target. With no target, harmful spells go to `softenemy` and helpful spells go to `softfriend`. `PLAYER_SOFT_*_CHANGED` events fire when the units change. |
| [Animations](docs/API.md#animation) | Animation groups on frames, textures and font strings, made in Lua or XML: `CreateAnimationGroup`, looping, smoothing, scripts and templates, with `Alpha`, `Translation`, `Scale`, `Rotation` and `Path` applied. |
| Tooltip line cap | Removes `GameTooltip`'s 30-line limit for every `GameTooltipTemplate` frame (`GameTooltip`, `ShoppingTooltip1/2`, `ItemRefTooltip`, AtlasLoot, …). A tooltip adds a new line pair when it needs one, so long tooltips and comparison blocks (for example, pfUI's eqcompare) keep all their lines. |
| [XML attributes](docs/API.md#parentkey-in-xml) | More XML attributes work: `parentKey="Name"` makes `parent.Name` point to a frame, texture or font string, `<OnLoad function="Name"/>` uses a global function as a script handler, `<OnLoad method="Name"/>` uses the frame's own function, `mixin="A, B"` copies mixins onto the object, `<KeyValues>` sets fields on the object, a button's `<NormalFont style="..."/>` sets its font, and `inherits="A, B"` applies more than one template. `parentArray="Name"` adds the object to a list on its parent. An `<Anchor>` takes `x` and `y` offsets and `relativeKey="$parent.Key"`. `<OnEnter inherit="prepend">` runs the template's handler and then its own, and `inherit="append"` runs them in the other order. A frame with `intrinsic="true"` makes a new frame type. Frames take `scale`, `registerForDrag`, `clipChildren`, `useParentLevel`, `dontSavePosition`, `propagateKeyboardInput`, `propagateMouseInput`, `enableMouseClicks`, `enableMouseMotion` and `motionScriptsWhileDisabled`, and buttons take `registerForClicks`. Textures take `alpha`, `atlas`, `useAtlasSize`, `mask`, `desaturated`, `rotation`, `horizTile`, `vertTile`, `hWrapMode` and `vWrapMode`. Font strings take `alpha`, `wordwrap`, `indented`, `degrees` and `radians`. Status bars take `reverseFill`, `rotatesTexture` and `fillStyle`, and edit boxes take `countInvisibleLetters`. |
| [Macro conditions](docs/API.md#more-commands-with-conditions) | `[conditions]` and `@unit` work on 38 slash commands, from `/cast` and `/use` to `/target`, `/follow`, `/cancelaura` and the `/pet` family. With `/cast [@mouseover,harm][] Fireball`, the spell goes to the mouseover unit. With no mouseover unit, it goes to your target. `@cursor` places a ground-target spell or item under the mouse and `@player` places it at your feet. A character name works where a unit token does (`[target=Feral]`). Addons read the same rules through `SecureCmdOptionParse`. |
| [`#showtooltip`](docs/API.md#showtooltip-and-show) | A macro button shows the spell or item that its directive resolves to, conditions included: icon, tooltip, cooldown, range, usable state and auto-repeat glow. Action-bar addons get this with no code of their own. Addons with their own macro parser can publish through `C_Macro.SetMacroDisplay`. |
| [Event-driven nameplates](docs/API.md#nameplate) | The modern `C_NamePlate` API, driven by real events. `NAME_PLATE_UNIT_ADDED` / `NAME_PLATE_UNIT_REMOVED` fire as plates appear and vanish, `nameplate1`..`nameplateN` tokens resolve with every `UnitX` function (and fire `UNIT_HEALTH`, `UNIT_AURA`, … as `arg1 == "nameplateN"`), and `C_NamePlate.GetNamePlateForUnit` / `GetNamePlates` hand back the live frames. |
| [Focus target](docs/API.md#focus) | A sticky focus unit. `FocusUnit("target")` pins it and `ClearFocus()` drops it, with `PLAYER_FOCUS_CHANGED` on every change. The `focus` / `focustarget` tokens resolve with every `UnitX` function and fire unit events (`UNIT_HEALTH`, `UNIT_AURA`, … as `arg1 == "focus"`), and the predefined `FOCUSTARGET` / `TARGETFOCUS` keybinds are ready to set. |
| [Combat log events](docs/API.md#combat_log_event_unfiltered--combat_log_event-events) | `COMBAT_LOG_EVENT_UNFILTERED` and `CombatLogGetCurrentEventInfo` give each combat event with GUIDs and `COMBATLOG_OBJECT_*` flags. The values do not depend on the client language, so damage meters do not need to parse chat text. `COMBAT_LOG_EVENT` fires for the events that pass the `CombatLogAddFilter` filters. |
| [Retail-like `/reload`](docs/API.md#reload-picks-up-new-addons-and-new-files) | `/reload` picks up addon changes made while the game runs. A new folder under `Interface\AddOns\` registers and loads as a normal addon, new files added to an existing addon's TOC load, a newly installed addon's first SavedVariables save survives `/reload`, `##` metadata edits (`## SavedVariables:`, `## Dependencies:`, `## Title:`, …) take effect, and a deleted addon folder drops from the addon list. |
| [Multi-flavor & conditional TOC](docs/API.md#conditional-and-multi-flavor-toc-loading) | Loads modern multi-flavor addons that ship one folder. Selects a version-specific TOC (`<Name>_ClassicAPI.toc` or `<Name>_Turtle.toc`) and the matching keybinding file (`Bindings_ClassicAPI.xml` / `Bindings_Turtle.xml`), accepts a comma-separated `## Interface:` version list (compatible when it includes the client version `11200`), and honors per-line `[AllowLoadGameType]` / `[AllowLoadTextLocale]` conditions and `[Family]` / `[Game]` / `[TextLocale]` path variables inside a TOC. |
| [Launch switches](docs/API.md#launch) | Options you add to the shortcut that starts the game. `-config <name>` reads and writes `WTF\<name>` in place of `WTF\Config.wtf`, so one install can hold several settings profiles. `-gluescript` and `-gluescriptFile` run Lua at the login and character-select screens, every time those screens appear. `-gamescript` and `-gamescriptFile` run it one time, after you enter the world. Each script runs after the interface has loaded, so it can call interface functions and use frames. |
| [Addon memory and CPU usage](docs/API.md#profiling) | Addon managers and performance tools can show how much Lua memory and CPU time each addon uses. `GetAddOnMemoryUsage` gives the memory of each addon. When `scriptProfile` is `1`, the CPU functions give the time of each addon, function, frame, and event. With profiling off, the CPU functions cost nothing. |
| [Any texture size](docs/API.md#texture-size-and-shape) | Textures load at any size and any shape. Width and height do not need to be powers of two, and there is no fixed upper limit. The only limit is the maximum texture size of your graphics card. This applies to every texture path: `SetTexture`, sprite sheets, inline textures, tooltips, and masks. The client allocates memory for a large texture only when an addon loads one, so small textures cost nothing extra. |
Smaller behavior fixes, such as frame alpha and `SetParent` frame levels, are
in **[docs/API.md](docs/API.md)** with the API that they change.
## Full API reference
Everything ClassicAPI adds, in full. Each section is collapsed — click a
heading to expand it. For signatures and return values, see the per-function
reference in **[docs/API.md](docs/API.md)**.
<details>
<summary><b>In-game Lua calls</b> — 950+ functions across ~75 namespaces</summary>
In the Frame rows, a name that starts with `:` is a method of the widget that the row names, for example `:SetShown` is `frame:SetShown`.
| Namespace | Calls |
|-----------|-------|
| [Action](docs/API.md#action) | `GetActionInfo` |
| [AddOns](docs/API.md#addons) | `C_AddOns.DoesAddOnExist`, `C_AddOns.GetAddOnName`, `C_AddOns.GetAddOnNotes`, `C_AddOns.GetAddOnOptionalDependencies`, `C_AddOns.GetAddOnSecurity`, `C_AddOns.GetAddOnTitle`, `C_AddOns.IsAddOnLoadable`, `C_AddOns.IsAddOnLoaded` |
| [Chat](docs/API.md#chat) | `GetCurrentChatGUID` |
| [Action](docs/API.md#action) | `GetActionInfo`, `IsItemAction`, `IsStackableAction`, `HasBonusActionBar`, `C_ActionBar.EnableActionRangeCheck`, `C_ActionBar.GetSpell`, `C_ActionBar.GetItemActionOnEquipSpellID`, `C_ActionBar.IsStackableAction`, `C_ActionBar.IsMacroActionWithShowTooltip`, `C_ActionBar.FindSpellActionButtons`, `C_ActionBar.HasSpellActionButtons`, `C_ActionBar.IsOnBarOrSpecialBar` |
| [AddOns](docs/API.md#addons) | `C_AddOns.DoesAddOnExist`, `C_AddOns.GetAddOnInterfaceVersion`, `C_AddOns.GetAddOnLocalTable`, `C_AddOns.GetAddOnName`, `C_AddOns.GetAddOnNotes`, `C_AddOns.GetAddOnOptionalDependencies`, `C_AddOns.GetAddOnSecurity`, `C_AddOns.GetAddOnTitle`, `C_AddOns.IsAddOnLoadable`, `C_AddOns.IsAddOnLoaded`, `C_AddOns.LoadAddOn` |
| [APIDocumentation](docs/API.md#apidocumentation) | `/classicapi` in-game browser, `C_APIDocumentation.GetSystem`, `C_APIDocumentation.GetSystems` |
| [Animation](docs/API.md#animation) | `region:CreateAnimationGroup`, `region:GetAnimationGroups`, `region:StopAnimating`, `SetMaxAnimFramerate`, `GetMaxAnimFramerate`, `AnimationGroup` and `Animation` / `Alpha` / `Translation` / `Scale` / `Rotation` / `Path` / `ControlPoint` methods |
| [AuctionHouse](docs/API.md#auctionhouse) | `C_AuctionHouse.PostItem`, `CanCancelAuction` |
| [AutoComplete](docs/API.md#autocomplete) | `C_AutoComplete.GetAutoCompleteResults`, `C_AutoComplete.IsRecognizedName`, `C_AutoComplete.GetAutoCompletePresenceID`, `C_AutoComplete.GetAutoCompleteRealms` |
| [Bindings](docs/API.md#bindings) | `SetBindingSpell`, `SetBindingItem`, `SetBindingMacro`, `SetBindingClick`, `SetOverrideBinding`, `SetOverrideBindingSpell`, `SetOverrideBindingItem`, `SetOverrideBindingMacro`, `SetOverrideBindingClick`, `ClearOverrideBindings`, `GetBindingAction` (`checkOverride`), `GetBindingByKey`, `IsModifiedClick`, `GetModifiedClick`, `SetModifiedClick`, `GetNumModifiedClickActions`, `GetModifiedClickAction` |
| [Chat](docs/API.md#chat) | `GetCurrentChatEvent`, `GetCurrentChatGUID`, `IsChatAFK`, `IsChatDND`, `SendSystemMessage` |
| [ChatBubbles](docs/API.md#chatbubbles) | `C_ChatBubbles.GetAllChatBubbles` |
| [Class](docs/API.md#class) | `FillLocalizedClassList` |
| [Combat](docs/API.md#combat) | `InCombatLockdown` |
| [CVar](docs/API.md#cvar) | `C_CVar.GetCVarBool` |
| [Cursor](docs/API.md#cursor) | `GetCursorInfo` |
| [Container](docs/API.md#container) | `C_Container.GetContainerItemCharges`, `C_Container.GetContainerItemDurability`, `C_Container.GetContainerItemID`, `C_Container.GetContainerItemRepairCost`, `C_Container.GetContainerNumFreeSlots`, `C_Container.GetItemCooldown`, `C_Container.IsContainerItemOpenable`, `C_Container.MoveItem`, `C_Container.PlayerHasHearthstone`, `C_Container.SwapItems`, `C_Container.UseHearthstone`, `GetItemCooldown` |
| [Coroutine](docs/API.md#coroutine) | `coroutine.create`, `coroutine.resume`, `coroutine.yield`, `coroutine.status`, `coroutine.wrap` |
| [Creature](docs/API.md#creature) | `C_CreatureInfo.GetCreatureID`, `C_CreatureInfo.GetCreatureInfoByID`, `C_CreatureInfo.RequestLoadCreatureByID` |
| [ClassColor](docs/API.md#classcolor) | `C_ClassColor.GetClassColor` |
| [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`, `StartAttack`, `StopAttack` |
| [CombatLog](docs/API.md#combatlog) | `CombatLogGetCurrentEventInfo`, `COMBATLOG_OBJECT_*` (constants) |
| [Console](docs/API.md#console) | `CalculateStringEditDistance`, `ConsoleAddMessage`, `ConsoleEcho`, `ConsoleExec`, `ConsoleGetAllCommands`, `ConsoleGetColorFromType`, `ConsoleGetFontHeight`, `ConsoleIsActive`, `ConsolePrintAllMatchingCommands`, `SetConsoleKey` |
| [CVar](docs/API.md#cvar) | `C_CVar.AreCVarsLoaded`, `C_CVar.DoesCVarExist`, `C_CVar.GetCVarBitfield`, `C_CVar.GetCVarBool`, `C_CVar.GetCVarInfo`, `C_CVar.RemoveTempCVar`, `C_CVar.SetCVar`, `C_CVar.SetCVarBitfield`, `C_CVar.SetTempCVar`, `GetCVar`, `GetCVarDefault` |
| [Cursor](docs/API.md#cursor) | `CursorHasMacro`, `GetCursorInfo` |
| [Container](docs/API.md#container) | `C_Container.AutoStoreItem`, `C_Container.CalculateTotalNumberOfFreeBagSlots`, `C_Container.GetContainerItemCharges`, `C_Container.GetContainerItemDurability`, `C_Container.GetContainerItemID`, `C_Container.GetContainerItemInfo`, `C_Container.GetContainerItemEquipmentSetInfo`, `C_Container.GetContainerItemQuestInfo`, `C_Container.GetContainerItemRepairCost`, `C_Container.GetContainerFreeSlots`, `C_Container.GetContainerNumFreeSlots`, `C_Container.GetBackpackAutosortDisabled`, `C_Container.GetBankAutosortDisabled`, `C_Container.GetItemCooldown`, `C_Container.GetSortBagsRightToLeft`, `C_Container.HasContainerItem`, `C_Container.IsContainerFiltered`, `C_Container.IsContainerItemOpenable`, `C_Container.MoveItem`, `C_Container.PlayerHasHearthstone`, `C_Container.SetBackpackAutosortDisabled`, `C_Container.SetBagPortraitTexture`, `C_Container.SetBankAutosortDisabled`, `C_Container.SetItemSearch`, `C_Container.SetSortBagsRightToLeft`, `C_Container.SortBags`, `C_Container.SortBankBags`, `C_Container.SwapItems`, `C_Container.UseHearthstone`, `GetItemCooldown`, `SetBagPortraitTexture` |
| [Creature](docs/API.md#creature) | `C_CreatureInfo.GetCreatureID`, `C_CreatureInfo.GetCreatureInfoByID`, `C_CreatureInfo.RequestLoadCreatureByID`, `C_CreatureInfo.GetRaceInfo`, `C_CreatureInfo.GetClassInfo`, `C_CreatureInfo.GetCreatureFamilyInfo`, `C_CreatureInfo.GetCreatureFamilyIDs`, `C_CreatureInfo.GetFactionInfo`, `C_CreatureInfo.GetCreatureTypeInfo`, `C_CreatureInfo.GetCreatureTypeIDs` |
| [Currency](docs/API.md#currency) | `GetCoinText`, `C_CurrencyInfo.GetCoinText`, `GetCoinTextureString`, `C_CurrencyInfo.GetCoinTextureString`, `Constants.MoneyFormattingConstants` |
| EncodingUtil | `C_EncodingUtil.CompressString`, `C_EncodingUtil.DecompressString`, `C_EncodingUtil.EncodeBase64`, `C_EncodingUtil.DecodeBase64`, `C_EncodingUtil.EncodeHex`, `C_EncodingUtil.DecodeHex`, `C_EncodingUtil.SerializeJSON`, `C_EncodingUtil.DeserializeJSON`, `C_EncodingUtil.SerializeCBOR`, `C_EncodingUtil.DeserializeCBOR` |
| [EquipmentSet](docs/API.md#equipmentset) | `C_EquipmentSet.CanUseEquipmentSets`, `C_EquipmentSet.ClearIgnoredSlotsForSave`, `C_EquipmentSet.CreateEquipmentSet`, `C_EquipmentSet.DeleteEquipmentSet`, `C_EquipmentSet.EquipmentSetContainsLockedItems`, `C_EquipmentSet.GetEquipmentSetID`, `C_EquipmentSet.GetEquipmentSetIDs`, `C_EquipmentSet.GetEquipmentSetInfo`, `C_EquipmentSet.GetIgnoredSlots`, `C_EquipmentSet.GetItemIDs`, `C_EquipmentSet.GetItemLocations`, `C_EquipmentSet.GetNumEquipmentSets`, `C_EquipmentSet.IgnoreSlotForSave`, `C_EquipmentSet.IsSlotIgnoredForSave`, `C_EquipmentSet.ModifyEquipmentSet`, `C_EquipmentSet.SaveEquipmentSet`, `C_EquipmentSet.UnignoreSlotForSave`, `C_EquipmentSet.UseEquipmentSet` |
| [Events](docs/API.md#events) | `C_EventUtils.IsEventValid` |
| [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` |
| [DeathInfo](docs/API.md#deathinfo) | `C_DeathInfo.GetSelfResurrectOptions`, `C_DeathInfo.UseSelfResurrectOption` |
| [DurationUtil](docs/API.md#durationutil) | `C_DurationUtil.CreateDuration`, `C_DurationUtil.CreateDurationTextBinding` |
| [EquipmentSet](docs/API.md#equipmentset) | `C_EquipmentSet.CanUseEquipmentSets`, `C_EquipmentSet.ClearIgnoredSlotsForSave`, `C_EquipmentSet.CreateEquipmentSet`, `C_EquipmentSet.DeleteEquipmentSet`, `C_EquipmentSet.EquipmentSetContainsLockedItems`, `C_EquipmentSet.GetEquipmentSetID`, `C_EquipmentSet.GetEquipmentSetIDs`, `C_EquipmentSet.GetEquipmentSetInfo`, `C_EquipmentSet.GetIgnoredSlots`, `C_EquipmentSet.GetItemIDs`, `C_EquipmentSet.GetItemLocations`, `C_EquipmentSet.GetNumEquipmentSets`, `C_EquipmentSet.IgnoreSlotForSave`, `C_EquipmentSet.IsSlotIgnoredForSave`, `C_EquipmentSet.ModifyEquipmentSet`, `C_EquipmentSet.PickupEquipmentSet`, `C_EquipmentSet.SaveEquipmentSet`, `C_EquipmentSet.UnignoreSlotForSave`, `C_EquipmentSet.UseEquipmentSet` |
| [Events](docs/API.md#events) | `C_EventUtils.IsEventValid`, `GetFramesRegisteredForEvent` |
| [Expansion](docs/API.md#expansion) | `ClassicExpansionAtLeast`, `ClassicExpansionAtMost`, `GetAccountExpansionLevel`, `GetClassicExpansionLevel`, `GetExpansionLevel`, `GetMaxPlayerLevel` |
| [Faction](docs/API.md#faction) | `C_Reputation.GetFactionDataByID`, `C_Reputation.GetFactionDataByIndex`, `C_Reputation.GetFactionStandings`, `C_Reputation.GetLastStandingChange`, `C_Reputation.GetWatchedFactionData`, `C_Reputation.IsFactionActive`, `C_Reputation.IsFactionActiveByID`, `C_Reputation.IsFactionInactive`, `C_Reputation.SetFactionActive`, `C_Reputation.SetFactionActiveByID`, `C_Reputation.SetFactionInactive`, `C_Reputation.SetFactionInactiveByID`, `C_Reputation.SetSelectedFaction`, `C_Reputation.SetSelectedFactionByID`, `C_Reputation.SetWatchedFactionByID`, `C_Reputation.ToggleFactionAtWar`, `C_Reputation.ToggleFactionAtWarByID`, `CollapseAllFactionHeaders`, `ExpandAllFactionHeaders`, `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`, `frame:SetShown`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered` |
| [FriendList](docs/API.md#friendlist) | `C_FriendList.IsWhoQueryPending`, `C_FriendList.SendWhoQueryByName` |
| [GameObject](docs/API.md#gameobject) | `C_GameObjectInfo.GetGameObjectInfoByID`, `C_GameObjectInfo.RequestLoadGameObjectByID` |
| [Gossip](docs/API.md#gossip) | `C_GossipInfo.CloseGossip`, `C_GossipInfo.GetActiveQuests`, `C_GossipInfo.GetAvailableQuests`, `C_GossipInfo.GetNumActiveQuests`, `C_GossipInfo.GetNumAvailableQuests`, `C_GossipInfo.GetNumOptions`, `C_GossipInfo.GetOptions`, `C_GossipInfo.GetText`, `C_GossipInfo.SelectActiveQuest`, `C_GossipInfo.SelectAvailableQuest`, `C_GossipInfo.SelectOption`, `C_GossipInfo.SelectOptionByIndex` |
| [GameTooltip](docs/API.md#gametooltip) | `GameTooltip:GetGameObject`, `GameTooltip:GetItem`, `GameTooltip:GetOwner`, `GameTooltip:GetSpell`, `GameTooltip:GetUnitGUID`, `GameTooltip:HasGameObject`, `GameTooltip:HasItem`, `GameTooltip:HasSpell`, `GameTooltip:HasUnit`, `GameTooltip:IsEquippedItem`, `GameTooltip:SetEquipmentSet`, `GameTooltip:SetHyperlinkCompareItem`, `GameTooltip:SetInventoryItemByID`, `GameTooltip:SetItemByGUID`, `GameTooltip:SetItemByID`, `GameTooltip:SetSpellByID`, `GameTooltip:SetTalentByID`, `GameTooltip:SetUnitAura`, `OnTooltipSetItem` (script) |
| [Frame: Region](docs/API.md#regionsetpointpoint-one-argument-form) | `:SetPoint("point")` (one-arg form), `:SetSize` / `:GetSize`, `ignoreRect` on `:GetSize` / `:GetWidth` / `:GetHeight`, `:GetUnscaledWidth` / `:GetUnscaledHeight` / `:GetUnscaledSize`, `:GetRect`, `:GetScaledRect`, `:IsRectValid`, `:GetPointByName`, `:ClearPoint`, `:GetScale` / `:GetEffectiveScale` (on textures and font strings), `:GetDebugName`, `:IsMouseOver`, `:IsDragging`, `:IsProtected` / `:CanChangeProtectedState` |
| [Frame: Frame](docs/API.md#createframeframetype--name-parent-template-id) | `CreateFrame` template lists and `id`, `GetMouseFoci`, `:SetShown`, `:SetClampRectInsets` / `:GetClampRectInsets`, `:SetResizeBounds`, `:SetClipsChildren` / `:DoesClipChildren`, `:GetBoundsRect`, `:GetEffectiveAlpha`, `:SetAlphaGradient` / `:ClearAlphaGradient` / `:HasAlphaGradient`, `:DesaturateHierarchy`, `:HookScript`, `:IsEventRegistered`, `:RegisterUnitEvent`, `:SetPropagateKeyboardInput` / `:GetPropagateKeyboardInput`, `:SetDontSavePosition` / `:GetDontSavePosition`, `:SetAttribute`, `:SetAttributeNoHandler`, `:ClearAttribute`, `:GetAttribute`, `:CanChangeAttribute`, `:AllowAttributeChanges` |
| [Frame: Button](docs/API.md#buttonsetnormalfontobjectfont--buttongetnormalfontobject) | `:SetEnabled`, `:SetFormattedText`, `:SetNormalFontObject` / `:GetNormalFontObject`, `:SetMotionScriptsWhileDisabled` / `:GetMotionScriptsWhileDisabled`, `:RegisterForClicks("AnyUp"/"AnyDown")`, `:RegisterForMouse`, `GetClickFrame` |
| [Frame: FontString](docs/API.md#fontstringgetstringheight) | `:GetStringHeight`, `:GetUnboundedStringWidth`, `:GetWrappedWidth`, `:GetNumLines`, `:GetLineHeight`, `:GetFontHeight` / `:SetFontHeight` (also on fonts), `:GetFieldSize`, `:IsTruncated`, `:SetMaxLines` / `:GetMaxLines`, `:SetWordWrap` / `:CanWordWrap`, `:SetIndentedWordWrap` / `:GetIndentedWordWrap` (also on fonts, edit boxes, message frames, and SimpleHTML), `:SetFormattedText`, `:SetRotation` / `:GetRotation` |
| [Frame: Texture](docs/API.md#texturesetrotationangle--cx-cy) | `:SetRotation` / `:GetRotation`, `:SetVertexOffset` / `:GetVertexOffset`, `:SetColorTexture`, `:SetAtlas` / `:GetAtlas`, `:ResetTexCoord`, `:SetSpriteSheetCell`, `:SetTexture` wrap modes, `:SetHorizTile` / `:GetHorizTile`, `:SetVertTile` / `:GetVertTile`, `:SetDesaturation` / `:GetDesaturation`, `IsDesaturateSupported`, `:SetMask`, `frame:CreateMaskTexture`, `:AddMaskTexture` / `:RemoveMaskTexture`, `:GetNumMaskTextures`, `:GetMaskTexture` |
| [Frame: EditBox](docs/API.md#editboxsetcursorpositionposition) | `:SetCursorPosition` / `:GetCursorPosition`, `:GetUTF8CursorPosition`, `:ClearHighlightText`, `:SetHighlightColor` / `:GetHighlightColor`, `:HasFocus`, `GetCurrentKeyBoardFocus`, `:HasText`, `:ClearHistory`, `:Enable` / `:Disable` / `:IsEnabled`, `:SetCountInvisibleLetters` / `:IsCountInvisibleLetters`, `:IsInIMECompositionMode` |
| [Frame: StatusBar](docs/API.md#statusbarsetreversefillisreversefill--statusbargetreversefill) | `:SetReverseFill` / `:GetReverseFill`, `:SetRotatesTexture` / `:GetRotatesTexture`, `:SetFillStyle` / `:GetFillStyle`, `:SetColorFill`, `:SetStatusBarDesaturated` / `:IsStatusBarDesaturated`, `:SetStatusBarDesaturation` / `:GetStatusBarDesaturation`, `:SetTimerDuration` / `:GetTimerDuration`, `:SetValue` / `:SetMinMaxValues` with `interpolation`, `:GetInterpolatedValue`, `:IsInterpolating`, `:SetToTargetValue` |
| [Frame: Slider](docs/API.md#sliderenable--sliderdisable--sliderisenabled) | `:Enable` / `:Disable` / `:IsEnabled` |
| [Frame: Cooldown](docs/API.md#createframecooldown--name-parent-template) | `CreateFrame("Cooldown")`, `:SetCooldown`, `:SetCooldownDuration`, `:SetCooldownFromExpirationTime`, `:Clear`, `:GetCooldownTimes`, `:GetCooldownDuration`, `:GetCooldownDisplayDuration`, `:Pause` / `:Resume`, `:SetPaused` / `:IsPaused`, `:SetReverse` / `:GetReverse`, `:SetDrawEdge` / `:GetDrawEdge`, `:SetDrawSwipe` / `:GetDrawSwipe`, `:SetDrawBling` / `:GetDrawBling`, `:SetSwipeColor`, `:SetEdgeColor`, `:SetSwipeTexture`, `:SetEdgeTexture`, `:SetBlingTexture`, `:SetRotation` / `:GetRotation`, `:SetHideCountdownNumbers` / `:GetHideCountdownNumbers`, `:GetCountdownFontString`, `:SetCountdownAbbrevThreshold` / `:GetCountdownAbbrevThreshold`, `:SetCountdownMillisecondsThreshold` / `:GetCountdownMillisecondsThreshold`, `:SetMinimumCountdownDuration` / `:GetMinimumCountdownDuration`, `OnCooldownDone`, `CooldownFrame_Set`, `CooldownFrame_Clear`, `CooldownFrame_SetDisplayAsPercentage` |
| [Frame: ScrollingMessageFrame](docs/API.md#smfsethyperlinksenabledenabled--smfgethyperlinksenabled) | `:SetHyperlinksEnabled` / `:GetHyperlinksEnabled`, `:GetMessageInfo` (with the extra `:AddMessage` values), `:BackFillMessage` (adds a message as the oldest), `:RemoveMessagesByPredicate`, `:SetScrollOffset` / `:GetScrollOffset`, `:GetMaxScrollRange`, `:ScrollByAmount`, `:SetInsertMode` / `:GetInsertMode`, `:AddOnDisplayRefreshedCallback` |
| [Frame: scripts](docs/API.md#onenable-and-ondisable-scripts) | `OnEnable`, `OnDisable`, `OnMinMaxChanged`, `OnAttributeChanged`, `OnCharComposition`, `OnTextChanged` (`userInput`), `PreClick`, `PostClick`, `SetModernScriptArgs` / `GetModernScriptArgs` |
| [FriendList](docs/API.md#friendlist) | `AddOrRemoveFriend`, `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` |
| [GameTooltip](docs/API.md#gametooltip) | `GameTooltip:AddSpellByID`, `GameTooltip:AddTexture`, `GameTooltip:GetGameObject`, `GameTooltip:GetItem`, `GameTooltip:GetMinimumWidth`, `GameTooltip:GetOwner`, `GameTooltip:GetPadding`, `GameTooltip:GetSpell`, `GameTooltip:GetUnit`, `GameTooltip:GetUnitGUID`, `GameTooltip:HasGameObject`, `GameTooltip:HasItem`, `GameTooltip:HasSpell`, `GameTooltip:HasUnit`, `GameTooltip:IsEquippedItem`, `GameTooltip:IsUnit`, `GameTooltip:SetAnchorType`, `GameTooltip:SetEquipmentSet`, `GameTooltip:SetFrameStack`, `GameTooltip:SetHyperlink` (full links, `spell:`, `quest:`), `GameTooltip:SetHyperlinkCompareItem`, `GameTooltip:SetInventoryItemByID`, `GameTooltip:SetItemByGUID`, `GameTooltip:SetItemByID`, `GameTooltip:SetSpellByID`, `GameTooltip:SetTalentByID`, `GameTooltip:SetTotem`, `GameTooltip:SetUnitAura`, `OnTooltipSetItem`, `OnTooltipSetSpell`, `OnTooltipSetUnit`, `OnTooltipSetGameObject`, `OnTooltipSetFrameStack` (scripts) |
| [Gossip](docs/API.md#gossip) | `C_GossipInfo.CloseGossip`, `C_GossipInfo.GetActiveQuests`, `C_GossipInfo.GetAvailableQuests`, `C_GossipInfo.GetNumActiveQuests`, `C_GossipInfo.GetNumAvailableQuests`, `C_GossipInfo.GetNumOptions`, `C_GossipInfo.GetOptions`, `C_GossipInfo.GetPoiForUiMapID`, `C_GossipInfo.GetPoiInfo`, `C_GossipInfo.GetText`, `C_GossipInfo.SelectActiveQuest`, `C_GossipInfo.SelectAvailableQuest`, `C_GossipInfo.SelectOption`, `C_GossipInfo.SelectOptionByIndex`, `GetNumGossipActiveQuests`, `GetNumGossipAvailableQuests`, `GetNumGossipOptions` |
| [Hooks](docs/API.md#hooks) | `hooksecurefunc` |
| [Input](docs/API.md#input) | `IsLeftAltKeyDown`, `IsLeftControlKeyDown`, `IsLeftShiftKeyDown`, `IsModifierKeyDown`, `IsMouseButtonDown`, `IsRightAltKeyDown`, `IsRightControlKeyDown`, `IsRightShiftKeyDown` |
| [Instance](docs/API.md#instance) | `GetInstanceInfo` |
| [Item](docs/API.md#item) | `C_Item.DoesItemExist`, `C_Item.DoesItemExistByID`, `C_Item.EquipItemByName`, `C_Item.GetCurrentItemLevel`, `C_Item.GetDetailedItemLevelInfo`, `C_Item.GetEnchantInfo`, `C_Item.GetItemCount`, `C_Item.GetItemFamily`, `C_Item.GetItemGUID`, `C_Item.GetItemIcon`, `C_Item.GetItemIconByID`, `C_Item.GetItemID`, `C_Item.GetItemInfoInstant`, `C_Item.GetItemInventorySlotInfo`, `C_Item.GetItemInventorySlotKey`, `C_Item.GetItemInventoryType`, `C_Item.GetItemInventoryTypeByID`, `C_Item.GetItemLink`, `C_Item.GetItemLocation`, `C_Item.GetItemMaxStackSize`, `C_Item.GetItemMaxStackSizeByID`, `C_Item.GetItemName`, `C_Item.GetItemNameByID`, `C_Item.GetItemQuality`, `C_Item.GetItemQualityByID`, `C_Item.GetItemSellPrice`, `C_Item.GetItemSellPriceByID`, `C_Item.GetItemSetID`, `C_Item.GetItemSetIDByID`, `C_Item.GetItemSetInfo`, `C_Item.GetItemSpell`, `C_Item.GetItemStatDelta`, `C_Item.GetItemStats`, `C_Item.GetItemSubClassInfo`, `C_Item.GetItemUniqueness`, `C_Item.GetItemUniquenessByID`, `C_Item.GetStackCount`, `C_Item.GetWeaponEnchantInfo`, `C_Item.IsBound`, `C_Item.IsEquippableItem`, `C_Item.IsEquippedItem`, `C_Item.IsItemDataCached`, `C_Item.IsItemDataCachedByID`, `C_Item.IsItemGUIDInInventory`, `C_Item.IsItemOpenable`, `C_Item.IsLocked`, `C_Item.LockItem`, `C_Item.LockItemByGUID`, `C_Item.UnlockAllItems`, `C_Item.UnlockItem`, `C_Item.RequestLoadItemData`, `C_Item.RequestLoadItemDataByID`, `C_Item.UseAtCursor`, `C_Item.UseAtUnit`, `C_Item.UseItemByName`, `GetAuctionItemID`, `GetAuctionSellItemID`, `GetAverageItemLevel`, `GetCraftReagentItemID`, `GetInboxItemID`, `GetInventoryItemDurability`, `GetInventoryItemID`, `GetInventoryItemsForSlot`, `GetInventoryItemRepairCost`, `GetItemIcon`, `GetLootRollItemID`, `GetLootSlotItemID`, `GetMerchantItemID`, `GetQuestItemID`, `GetQuestLogItemID`, `GetTradePlayerItemID`, `GetTradeSkillItemID`, `GetTradeSkillReagentItemID`, `GetTradeTargetItemID`, `OffhandHasWeapon` |
| [Loot](docs/API.md#loot) | `C_Loot.GetNearbyLootableUnits`, `C_Loot.GetLastScanResults`, `C_Loot.IsScanInProgress`, `C_Loot.LootUnit`, `C_Loot.LootUnitItem`, `C_Loot.ScanNearbyLoot` |
| [LootHistory](docs/API.md#loothistory) | `C_LootHistory.GetNumItems`, `C_LootHistory.GetItem`, `C_LootHistory.GetPlayerInfo` |
| [LossOfControl](docs/API.md#lossofcontrol) | `C_LossOfControl.GetActiveLossOfControlData`, `C_LossOfControl.GetActiveLossOfControlDataCount` |
| [Macros](docs/API.md#macros) | `GetLooseMacroIcons`, `GetLooseMacroItemIcons`, `GetMacroIcons`, `GetMacroItemIcons`, `GetMacroSpell` |
| [Input](docs/API.md#input) | `GetMouseButtonClicked`, `GetMouseButtonName`, `IsLeftAltKeyDown`, `IsLeftControlKeyDown`, `IsLeftShiftKeyDown`, `IsModifierKeyDown`, `IsMouseButtonDown`, `IsRightAltKeyDown`, `IsRightControlKeyDown`, `IsRightShiftKeyDown` |
| [Instance](docs/API.md#instance) | `GetInstanceInfo`, `IsActiveBattlefieldArena` |
| [Item: C_Item](docs/API.md#item) | `C_Item.DoesItemExist` / `C_Item.DoesItemExistByID`, `C_Item.EquipItemByName`, `C_Item.GetCurrentItemLevel`, `C_Item.GetDetailedItemLevelInfo`, `C_Item.GetEnchantInfo`, `C_Item.GetItemClassInfo`, `C_Item.GetItemCount`, `C_Item.GetItemData` / `C_Item.GetItemDataByID`, `C_Item.GetItemFamily`, `C_Item.GetItemGUID`, `C_Item.GetItemIcon` / `C_Item.GetItemIconByID`, `C_Item.GetItemID`, `C_Item.GetItemInfo`, `C_Item.GetItemInfoInstant`, `C_Item.GetItemInventorySlotInfo`, `C_Item.GetItemInventorySlotKey`, `C_Item.GetItemInventoryType` / `C_Item.GetItemInventoryTypeByID`, `C_Item.GetItemLink`, `C_Item.GetItemLocation`, `C_Item.GetItemMaxStackSize` / `C_Item.GetItemMaxStackSizeByID`, `C_Item.GetItemName` / `C_Item.GetItemNameByID`, `C_Item.GetItemQuality` / `C_Item.GetItemQualityByID`, `C_Item.GetItemSellPrice` / `C_Item.GetItemSellPriceByID`, `C_Item.GetItemSetID` / `C_Item.GetItemSetIDByID`, `C_Item.GetItemSetInfo`, `C_Item.GetItemSpell`, `C_Item.GetItemStatDelta`, `C_Item.GetItemStats`, `C_Item.GetItemSubClassInfo`, `C_Item.GetItemTempEnchantInfo`, `C_Item.GetItemUniqueness` / `C_Item.GetItemUniquenessByID`, `C_Item.GetStackCount`, `C_Item.GetWeaponEnchantInfo`, `C_Item.IsBound`, `C_Item.IsConsumableItem`, `C_Item.IsEquippableItem`, `C_Item.IsEquippedItem`, `C_Item.IsItemDataCached` / `C_Item.IsItemDataCachedByID`, `C_Item.IsItemGUIDInInventory`, `C_Item.IsItemInRange`, `C_Item.IsItemOpenable`, `C_Item.IsLocked`, `C_Item.IsUsableItem`, `C_Item.ItemHasRange`, `C_Item.LockItem`, `C_Item.LockItemByGUID`, `C_Item.UnlockItem`, `C_Item.UnlockAllItems`, `C_Item.PickupItem`, `C_Item.RequestLoadItemData` / `C_Item.RequestLoadItemDataByID`, `C_Item.UseAtCursor`, `C_Item.UseAtUnit`, `C_Item.UseItemByName` |
| [Item: info](docs/API.md#getitemclassinfoclassid) | `GetItemClassInfo`, `GetItemSubClassInfo`, `GetItemIcon`, `IsConsumableItem`, `IsCurrentItem`, `IsDressableItem`, `IsEquippedItemType`, `IsHarmfulItem`, `IsHelpfulItem`, `IsUsableItem` |
| [Item: inventory](docs/API.md#getaverageitemlevel) | `GetAverageItemLevel`, `GetInventoryItemID`, `GetInventoryItemDurability`, `GetInventoryItemRepairCost`, `GetInventoryItemsForSlot`, `IsDualWielding`, `SetInventoryPortraitTexture` |
| [Item: item IDs](docs/API.md#getitemid--companions-to-the-engines-getitemlink-family) | `GetAuctionItemID`, `GetAuctionSellItemID`, `GetCraftReagentItemID`, `GetInboxItemID`, `GetLootRollItemID`, `GetLootSlotItemID`, `GetMerchantItemID`, `GetQuestItemID`, `GetQuestLogItemID`, `GetTradePlayerItemID`, `GetTradeTargetItemID`, `GetTradeSkillItemID`, `GetTradeSkillReagentItemID` |
| [Localization](docs/API.md#localization) | `AbbreviateLargeNumbers`, `AbbreviateNumbers`, `BreakUpLargeNumbers`, `C_StringUtil.GetDefaultAbbreviationBreakpoints` |
| [Loot](docs/API.md#loot) | `C_Loot.GetNearbyLootableUnits`, `C_Loot.GetLastScanResults`, `C_Loot.IsScanInProgress`, `C_Loot.LootAllCorpses`, `C_Loot.LootUnit`, `C_Loot.LootUnitItem`, `C_Loot.ScanNearbyLoot` |
| [LootHistory](docs/API.md#loothistory) | `C_LootHistory.GetNumItems`, `C_LootHistory.GetItem`, `C_LootHistory.GetPlayerInfo`, `C_LootHistory.Clear` |
| [LossOfControl](docs/API.md#lossofcontrol) | `C_LossOfControl.GetActiveLossOfControlData`, `C_LossOfControl.GetActiveLossOfControlDataCount`, `C_LossOfControl.GetSchoolLockout` |
| [Lua](docs/API.md#lua) | `collectgarbage` (5.1 options), `coroutine.create`, `coroutine.resume`, `coroutine.running`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `CreateFromMixins`, `debuglocals`, `debugstack` (coroutine argument), `difftime`, `GetCallstackHeight`, `GetErrorCallstackHeight`, `gmatch`, `math.cosh`, `math.fmod`, `math.huge`, `math.modf`, `math.sinh`, `math.tanh`, `Mixin`, `newproxy`, `scrub`, `select`, `SetErrorCallstackHeight`, `strbyte` (range args), `strcmputf8i`, `strconcat`, `string.byte` (range args), `string.concat`, `string.format` (two-digit `%n$`), `string.gmatch`, `string.gsub` (table replacement, `%0`), `string.join`, `string.match`, `string.reverse`, `string.split`, `string.trim`, `strjoin`, `strlenutf8`, `strmatch`, `strreplace`, `strrev`, `strsplit`, `strsplittable`, `strtrim`, `table.count`, `table.maxn`, `table.removemulti`, `table.wipe`, `unpack` (range args), `wipe`, `xpcall` (argument forwarding) |
| [Macros](docs/API.md#macros) | `C_Macro.CreateMacro`, `C_Macro.EditMacro`, `C_Macro.SetMacroDisplay`, `DeleteMacro` / `EditMacro` / `GetMacroInfo` / `PickupMacro` by name, `GetLooseMacroIcons`, `GetLooseMacroItemIcons`, `GetMacroBody`, `GetMacroIcons`, `GetMacroItem`, `GetMacroItemIcons`, `GetMacroSpell`, `GetRunningMacro`, `GetRunningMacroButton`, `RunMacroText`, `SetMacroItem`, `SetMacroSpell`, `StopMacro` |
| [Mail](docs/API.md#mail) | `GetInboxItemLink`, `GetSendMailItemLink` |
| [Map](docs/API.md#map) | `C_Map.GetBestMapForUnit`, `C_Map.GetMapOverlays` |
| [MerchantFrame](docs/API.md#merchantframe) | `C_MerchantFrame.GetBuybackItemID`, `C_MerchantFrame.GetItemInfo`, `C_MerchantFrame.GetNumJunkItems`, `C_MerchantFrame.IsMerchantItemRefundable`, `C_MerchantFrame.IsSellAllJunkEnabled`, `C_MerchantFrame.SellAllJunkItems` |
| [Map](docs/API.md#map) | `C_Map.CanSetUserWaypointOnMap`, `C_Map.ClearUserWaypoint`, `C_Map.GetAreaInfo`, `C_Map.GetAreas`, `C_Map.GetAreaTriggerInfo`, `C_Map.GetAreaTriggers`, `C_Map.GetBestMapForUnit`, `C_Map.GetFallbackWorldMapID`, `C_Map.GetMapAreaIDs`, `C_Map.GetMapArtLayers`, `C_Map.GetMapArtLayerTextures`, `C_Map.GetMapChildrenInfo`, `C_Map.GetMapInfo`, `C_Map.GetMapInfoAtPosition`, `C_Map.GetMapOverlays`, `C_Map.GetMapPosFromWorldPos`, `C_Map.GetMapRectOnMap`, `C_Map.GetMapWorldSize`, `C_Map.GetPlayerMapPosition`, `C_Map.GetUserWaypoint`, `C_Map.GetUserWaypointFromHyperlink`, `C_Map.GetUserWaypointHyperlink`, `C_Map.GetUserWaypointPositionForMap`, `C_Map.GetWorldPosFromMapPos`, `C_Map.HasUserWaypoint`, `C_Map.MapHasArt`, `C_Map.SetUserWaypoint` |
| [MapExplorationInfo](docs/API.md#mapexplorationinfo) | `C_MapExplorationInfo.GetExploredAreaIDsAtPosition`, `C_MapExplorationInfo.GetExploredMapTextures`, `C_MapExplorationInfo.GetUnexploredMapTextures` |
| [MerchantFrame](docs/API.md#merchantframe) | `C_MerchantFrame.GetBuybackItemID`, `C_MerchantFrame.GetItemInfo`, `C_MerchantFrame.GetNumJunkItems`, `C_MerchantFrame.IsMerchantItemRefundable`, `C_MerchantFrame.IsSellAllJunkEnabled`, `C_MerchantFrame.SellAllJunkItems`, `GetBuybackItemLink` |
| [Model](docs/API.md#model) | `DressUpModel:TryOn` (links, recipes, names, hand, enchant glow, result), `DressUpModel:UndressSlot`, `DressUpModel:IsGeoReady`, `DressUpModel:SetSheathed` / `GetSheathed`, `DressUpModel:SetAutoDress` / `GetAutoDress`, `Model:SetGlow`, `PlayerModel:RefreshCamera`, `PlayerModel:SetCamDistanceScale`, `PlayerModel:SetCreature` (`displayID`), `PlayerModel:SetDisplayInfo`, `PlayerModel:SetItem`, `PlayerModel:SetPortraitZoom`, `PlayerModel:SetRotation` (`animate`), `PlayerModel:SetUnit` (result), `PlayerModel:CanSetUnit`, `PlayerModel:GetDisplayInfo`, `PlayerModel:SetAnimation`, `PlayerModel:FreezeAnimation`, `PlayerModel:HasAnimation`, `PlayerModel:SetDoBlend` / `GetDoBlend`, `PlayerModel:SetKeepModelOnHide` / `GetKeepModelOnHide`, `PlayerModel:ApplySpellVisualKit` |
| [NamePlate](docs/API.md#nameplate) | `C_NamePlate.GetNamePlateForGUID`, `C_NamePlate.GetNamePlateForUnit`, `C_NamePlate.GetNamePlateGUIDs`, `C_NamePlate.GetNamePlates` |
| [NameCache](docs/API.md#namecache) | `C_PlayerCache.GetPlayerInfoByName`, `C_PlayerCache.IsEnabled`, `C_PlayerCache.IsScanEnabled`, `C_PlayerCache.RememberPlayer`, `C_PlayerCache.SetEnabled`, `C_PlayerCache.SetScanEnabled`, `C_PlayerInfo.GUIDIsCreature`, `C_PlayerInfo.GUIDIsGameObject`, `C_PlayerInfo.GUIDIsPet`, `C_PlayerInfo.GUIDIsPlayer`, `GetPlayerInfoByGUID`, `UnitNameFromGUID` |
| [Quest](docs/API.md#quest) | `C_QuestLog.GetNumQuestObjectives`, `C_QuestLog.GetQuestDetails`, `C_QuestLog.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogLeaderBoardID` |
| [Screen](docs/API.md#screen) | `GetPhysicalScreenSize` |
| [Spell](docs/API.md#spell) | `C_Spell.CancelSpellByID`, `C_Spell.CastAtCursor`, `C_Spell.CastAtUnit`, `C_Spell.CastingInfo`, `C_Spell.ChannelInfo`, `C_Spell.DoesSpellExist`, `C_Spell.GetSchoolString`, `C_Spell.GetSpellCooldown`, `C_Spell.GetSpellDescription`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellMechanicByID`, `C_Spell.GetSpellName`, `C_Spell.GetSpellPowerCost`, `C_Spell.GetSpellRadius`, `C_Spell.GetSpellReagents`, `C_Spell.GetSpellSubtext`, `C_Spell.GetSpellTexture`, `C_Spell.IsAutoAttackSpell`, `C_Spell.IsCurrentSpell`, `C_Spell.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `CancelSpellByName`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellSchool`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange` |
| [SpellBook](docs/API.md#spellbook) | `C_SpellBook.GetCurrentLevelSpells`, `C_SpellBook.GetSpellLevelLearned`, `C_SpellBook.GetSpellSkillLine`, `C_SpellBook.IsAutoAttackSpellBookItem`, `C_SpellBook.IsRangedAutoAttackSpellBookItem`, `FindSpellBookSlotByID` |
| [State](docs/API.md#state) | `CancelShapeshiftForm`, `Dismount`, `GetMirrorTimerInfo`, `GetMirrorTimerProgress`, `GetShapeshiftFormID`, `IsAssistingRitual`, `IsFalling`, `IsInGroup`, `IsInRaid`, `IsLoggedIn`, `IsMounted`, `IsStealthed`, `IsSwimming` |
| [Table](docs/API.md#table) | `table.wipe` |
| [NameCache](docs/API.md#namecache) | `C_PlayerCache.GetPlayerInfoByName`, `C_PlayerCache.IsEnabled`, `C_PlayerCache.RememberPlayer`, `C_PlayerCache.SetEnabled`, `GetPlayerInfoByGUID`, `UnitNameFromGUID` |
| [NewItems](docs/API.md#newitems) | `C_NewItems.ClearAll`, `C_NewItems.IsNewItem`, `C_NewItems.RemoveNewItem` |
| [PartyInfo](docs/API.md#partyinfo) | `InviteUnit`, `PromoteToLeader`, `UninviteUnit` |
| [Pet](docs/API.md#pet) | `IsPetAttackAction`, `IsAtStableMaster` |
| [PlayerInfo](docs/API.md#playerinfo) | `C_PlayerInfo.CanUseItem`, `C_PlayerInfo.GetClass`, `C_PlayerInfo.GetName`, `C_PlayerInfo.GetRace`, `C_PlayerInfo.GetSex`, `C_PlayerInfo.GUIDIsCreature`, `C_PlayerInfo.GUIDIsGameObject`, `C_PlayerInfo.GUIDIsPet`, `C_PlayerInfo.GUIDIsPlayer`, `C_PlayerInfo.IsConnected` |
| [Profiling](docs/API.md#profiling) | `GetAddOnCPUUsage`, `GetAddOnMemoryUsage`, `GetEventCPUUsage`, `GetFrameCPUUsage`, `GetFunctionCPUUsage`, `GetScriptCPUUsage`, `ResetCPUUsage`, `UpdateAddOnCPUUsage`, `UpdateAddOnMemoryUsage` |
| [Quest](docs/API.md#quest) | `C_QuestLog.GetInfo`, `C_QuestLog.GetNumQuestObjectives`, `C_QuestLog.GetQuestDetails`, `C_QuestLog.GetQuestLogTitle`, `C_QuestLog.GetHeaderIndexForQuest`, `C_QuestLog.GetLogIndexForQuestID`, `C_QuestLog.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogCompletionText`, `GetQuestLogLeaderBoardID` (Turtle WoW only: `C_QuestLog.GetAllCompletedQuestIDs`, `C_QuestLog.IsQuestFlaggedCompleted`, `GetQuestsCompleted`, `QueryQuestsCompleted`) |
| [Sound](docs/API.md#sound) | `C_Sound.GetRecentSoundFiles`, `C_Sound.GetSoundScaledVolume`, `C_Sound.IsPlaying`, `C_Sound.PlayItemSound`, `C_Sound.PlaySound`, `C_Sound.PlaySoundWithOptions`, `C_Sound.PlayVocalErrorSound`, `MuteSoundFile`, `PlaySound`, `PlaySoundFile`, `StopSound`, `UnmuteSoundFile` |
| [Spell](docs/API.md#spell) | `C_Spell.CancelSpellByID`, `C_Spell.CastAtCursor`, `C_Spell.CastAtUnit`, `C_Spell.CastingInfo`, `C_Spell.ChannelInfo`, `C_Spell.DoesSpellExist`, `C_Spell.GetSchoolString`, `C_Spell.GetSpellCastCount`, `C_Spell.GetSpellCooldown`, `C_Spell.GetSpellDescription`, `C_Spell.GetSpellDispelType`, `C_Spell.GetSpellEffectInfo`, `C_Spell.GetSpellEffectMechanics`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLevelInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellLossOfControlCooldown`, `C_Spell.GetSpellMechanicByID`, `C_Spell.GetSpellName`, `C_Spell.GetSpellPowerCost`, `C_Spell.GetSpellRadius`, `C_Spell.GetSpellReagents`, `C_Spell.GetSpellRequiredTargetLevel`, `C_Spell.GetSpellSubtext`, `C_Spell.GetSpellTexture`, `C_Spell.IsAutoAttackSpell`, `C_Spell.IsCurrentSpell`, `C_Spell.IsNextMeleeSpell`, `C_Spell.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellInRange`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.ResetsMeleeSwing`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `CanDualWield`, `CancelSpellByName`, `CancelUnitBuff`, `CastSpellByID`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetCritChance`, `GetRangedCritChance`, `GetSpellBaseCooldown`, `GetSpellBonusDamage`, `GetSpellBonusHealing`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellRequiredTargetLevel`, `GetSpellSchool`, `IsAttackSpell`, `IsAutoRepeatSpell`, `IsConsumableSpell`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange`, `UnitCastingDuration`, `UnitChannelDuration` |
| [SpellActivationOverlay](docs/API.md#spellactivationoverlay) | `C_SpellActivationOverlay.IsSpellOverlayed`, `IsSpellOverlayed` |
| [SpellBook](docs/API.md#spellbook) | `C_SpellBook.ContainsAnyDisenchantSpell`, `C_SpellBook.GetCurrentLevelSpells`, `C_SpellBook.GetNumSpellBookSkillLines`, `C_SpellBook.GetPlayerSpellsByAura`, `C_SpellBook.GetSkillLineIndexByID`, `C_SpellBook.GetSkillLineName`, `C_SpellBook.GetSkillLineRank`, `C_SpellBook.GetSpellBookItemCastCount`, `C_SpellBook.GetSpellBookItemInfo`, `C_SpellBook.GetSpellBookItemLossOfControlCooldownDuration`, `C_SpellBook.GetSpellBookItemLossOfControlCooldownInfo`, `C_SpellBook.GetSpellBookItemSkillLineIndex`, `C_SpellBook.GetSpellBookSkillLineInfo`, `C_SpellBook.GetSpellLevelLearned`, `C_SpellBook.GetSpellSkillLine`, `C_SpellBook.IsAutoAttackSpellBookItem`, `C_SpellBook.IsClassTalentSpellBookItem`, `C_SpellBook.IsRangedAutoAttackSpellBookItem`, `FindSpellBookSlotByID` |
| [State](docs/API.md#state) | `CancelShapeshiftForm`, `Dismount`, `GetMirrorTimerInfo`, `GetMirrorTimerProgress`, `GetShapeshiftForm`, `GetShapeshiftFormID`, `GetSheathState`, `IsAssistingRitual`, `IsFalling`, `IsIndoors`, `IsInGroup`, `IsInRaid`, `IsLoggedIn`, `IsLoggingOut`, `IsMounted`, `IsOutdoors`, `IsPlayerInWorld`, `IsStealthed`, `IsSwimming` |
| [SwingTimer](docs/API.md#swingtimer) | `C_SwingTimer.EnableRangeCheck`, `C_SwingTimer.IsTargetWithinSwingRange` |
| [System](docs/API.md#system) | `CopyToClipboard`, `FlashClientIcon`, `GetPhysicalScreenSize` |
| [Talent](docs/API.md#talent) | `GetTalentIDByIndex`, `GetTalentSpellID` |
| [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` |
| [TradeSkillUI](docs/API.md#tradeskillui) | `C_TradeSkillUI.GetTradeSkillListLink`, `C_TradeSkillUI.GetCraftListLink`, `C_TradeSkillUI.GetTradeSkillListRecipes` |
| [Targeting](docs/API.md#targeting) | `GetPlayerFacing`, `TargetDirectionEnemy`, `TargetDirectionFriend`, `TargetDirectionFinished`, `TargetNearest`, `TargetNearestEnemyPlayer`, `TargetNearestFriendPlayer`, `InteractUnit`, `C_PlayerInteractionManager.InteractUnit`, `IsTargetLoose` |
| [TaxiMap](docs/API.md#taximap) | `C_TaxiMap.GetTaxiNodesForMap`, `C_TaxiMap.GetAllTaxiNodes`, `C_TaxiMap.GetTaxiPaths`, `C_TaxiMap.GetTaxiPathWaypoints`, `C_TaxiMap.GetTaxiRoute` |
| [Texture](docs/API.md#texture) | `C_Texture.GetAtlasElementID`, `C_Texture.GetAtlasElements`, `C_Texture.GetAtlasExists`, `C_Texture.GetAtlasID`, `C_Texture.GetAtlasInfo`, `C_Texture.RegisterAtlas`, `SetPortraitTextureFromCreatureDisplayID` |
| [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`, `GetTickTime`, `GetTimeCached` |
| [Totem](docs/API.md#totem) | `GetTotemInfo`, `GetTotemTimeLeft`, `GetTotemDuration`, `TargetTotem` |
| [Tracking](docs/API.md#tracking) | `GetNumTrackingTypes`, `GetTrackingInfo`, `SetTracking` |
| [TradeSkillUI](docs/API.md#tradeskillui) | `GetTradeSkillListLink`, `GetCraftListLink`, `GetTradeSkillDescription`, `GetTradeSkillRecipeLink`, `IsTradeSkillLinked`, `IsCraftLinked` |
| [Trainer](docs/API.md#trainer) | `GetTrainerServiceItemLink` |
| [UIColor](docs/API.md#uicolor) | `C_UIColor.GetColors` |
| [Unit](docs/API.md#unit) | `GetUnitSpeed`, `UnitClassBase`, `UnitGUID`, `UnitInRange`, `UnitIsAFK`, `UnitIsDND`, `UnitIsFeignDeath`, `UnitIsInMyGuild`, `UnitIsPossessed`, `UnitPower`, `UnitPowerMax`, `UnitPowerType`, `UnitRaceBase`, `UnitStandState`, `UnitSubName`, `UnitTokenFromGUID` |
| [UnitAuras](docs/API.md#unitauras) | `C_UnitAuras.GetAuraDataByIndex`, `C_UnitAuras.GetAuraDataBySpellName`, `C_UnitAuras.GetAuraDispelTypeColor`, `C_UnitAuras.GetBuffDataByIndex`, `C_UnitAuras.GetDebuffDataByIndex`, `C_UnitAuras.GetPlayerAuraBySpellID`, `C_UnitAuras.GetUnitAuraBySpellID`, `C_UnitAuras.GetUnitAuras`, `C_UnitAuras.RegisterComboDuration` |
| [Unit](docs/API.md#unit) | `CanBeRaidTarget`, `ClosestUnitPosition`, `GetUnitSpeed`, `IsUnitToken`, `SetUnitCursorTexture`, `UnitClassBase`, `UnitCreatedBySpell`, `UnitCreatureFamilyID`, `UnitCreatureID`, `UnitCreatureTypeID`, `UnitDistanceSquared`, `UnitFacing`, `UnitGUID`, `UnitHasIncomingResurrection`, `UnitHealthMissing`, `UnitInLineOfSight`, `UnitInRange`, `UnitIsAFK`, `UnitIsDND`, `UnitIsFeignDeath`, `UnitIsInMyGuild`, `UnitIsMinion`, `UnitIsOtherPlayersPet`, `UnitIsPet`, `UnitIsPossessed`, `UnitOwnerGUID`, `UnitPosition`, `UnitPower`, `UnitPowerMax`, `UnitPowerMissing`, `UnitPowerType`, `UnitRaceBase`, `UnitSelectionColor`, `UnitSelectionType`, `UnitSpellHaste`, `UnitSpellTargetName`, `UnitStandState`, `UnitSubName`, `UnitTokenFromGUID`, `UnitTokenFromName` |
| [UnitAuras](docs/API.md#unitauras) | `C_UnitAuras.GetAuraDataByAuraInstanceID`, `C_UnitAuras.GetAuraDataByIndex`, `C_UnitAuras.GetAuraDataBySlot`, `C_UnitAuras.GetAuraDataBySpellName`, `C_UnitAuras.GetAuraDispelTypeColor`, `C_UnitAuras.GetAuraSlots`, `C_UnitAuras.GetBuffDataByIndex`, `C_UnitAuras.GetDebuffDataByIndex`, `C_UnitAuras.GetPlayerAuraBySpellID`, `C_UnitAuras.GetUnitAuraBySpellID`, `C_UnitAuras.GetUnitAuras`, `C_UnitAuras.RegisterAuraDurationModifierByTrigger`, `C_UnitAuras.RegisterComboDuration`, `C_UnitAuras.UnitAura`, `C_UnitAuras.UnitAuraBySlot`, `C_UnitAuras.UnitBuff`, `C_UnitAuras.UnitDebuff` |
| [VoiceChat](docs/API.md#voicechat) | `C_VoiceChat.GetTtsVoices`, `C_VoiceChat.GetRemoteTtsVoices`, `C_VoiceChat.SpeakText`, `C_VoiceChat.StopSpeakingText`, `C_TTSSettings.GetSpeechRate`, `C_TTSSettings.GetSpeechVolume`, `C_TTSSettings.GetSpeechVoiceID`, `C_TTSSettings.GetVoiceOptionName`, `C_TTSSettings.SetSpeechRate`, `C_TTSSettings.SetSpeechVolume`, `C_TTSSettings.SetVoiceOption`, `C_TTSSettings.SetVoiceOptionByName`, `C_TTSSettings.SetDefaultSettings`, `C_TTSSettings.RefreshVoices` |
| [XMLUtil](docs/API.md#xmlutil) | `C_XMLUtil.DoesTemplateExist`, `C_XMLUtil.GetTemplateInfo`, `C_XMLUtil.GetTemplates` |
### GlueXML calls
</details>
<details>
<summary><b>GlueXML calls</b> — login / realm-select / character-select screens</summary>
Registered on the **glue** Lua state (the engine that runs the login,
realm-select, and character-select screens). The persistence entries
in the first row are *glue-only* — they exist to support GlueXML
patches that need a small persistence surface across sessions, since
vanilla 1.12 glue ships no general-purpose persistence API beyond
`GetSavedAccountName`/`SetSavedAccountName` (saturated by autologin).
patches that need a small persistence surface across sessions.
The rest of the table is in-game calls that we also mirror onto
the glue state because GlueXML had no way to reach them otherwise.
@@ -81,23 +159,106 @@ the glue state because GlueXML had no way to reach them otherwise.
|-------|-------|
| [Account](docs/API.md#account) | `SaveAccount`, `DeleteAccount`, `GetSavedAccounts`, `LoginWithSavedAccount` (passwords encrypted in Windows Credential Manager, scoped per realmlist; plaintext never returned to Lua) |
| [CharacterList](docs/API.md#characterlist) | `GetSavedCharacterOrder`, `SetSavedCharacterOrder` (persist to `WTF\Account\...\ClassicAPI.txt`) |
| CVar | `GetCVar`, `SetCVar`, `RegisterCVar`, `GetCVarDefault`, `C_CVar.GetCVarBool` (storage is process-global — writes from glue are visible in-world and vice versa) |
| CVar | `GetCVar`, `SetCVar`, `RegisterCVar`, `GetCVarDefault`, `C_CVar.GetCVarBool`, `C_CVar.SetTempCVar`, `C_CVar.RemoveTempCVar` (storage is process-global — writes from glue are visible in-world and vice versa) |
| [Glue](docs/API.md#glue) | `C_Glue.IsFirstLoadThisSession`, `C_Glue.IsOnGlueScreen` |
| Script | `RunScript` (compile and run a Lua chunk in the glue state's globals — useful for slash-command-style helpers in GlueXML) |
| State | `IsLoggedIn` |
### Macros
</details>
Engine-level extensions to macro parsing and dispatch — no new Lua
functions, just behavior the stock 1.12 engine didn't have. See the
[Macros section in the Lua reference](docs/API.md#macros) for details.
<details>
<summary><b>Macros</b> — forms a macro body accepts</summary>
The DLL parses these forms, so an action-bar addon needs no code for them.
See the [Macros section in the Lua reference](docs/API.md#macros) for
details.
| Form | What it does |
|------|--------------|
| `/cast <spellID>` | `/cast 5019` casts Shoot if known; macro slot tags correctly for action-bar UI |
| `CastSpellByName("<spellID>")` | Same — numeric strings resolve through the engine's name resolver |
| `CastSpellNoToggle("<name>")` in a macro | Engine's macro parser now recognizes it as a primary-spell line, so the macro slot in an addon like pfUI highlights when its spell is auto-repeating or its self-aura is active |
| `#showtooltip [conditions] Value` | First line of a macro. Sets what the button shows. Bare `#showtooltip` follows the first `/cast` or `/use` line instead. `#show` is the same form. |
| `[conditions]` and `@unit` | Accepted by 42 commands. The slash-command list below names them. |
| `!Name` | Starts an ability but never turns it off. Use it for auto-repeat shots and for the self-buffs (stance, aspect, seal, form, tracking). |
| A line that starts with `#` | A comment. The line never reaches chat. |
| `/cast <spellID>` | For a spell you know, `/cast 5019` casts it by ID. The macro slot also tags correctly for an action-bar addon. |
| `CastSpellByName("<spellID>")` | A numeric string resolves through the engine name resolver, the same as `/cast`. |
| `CastSpellNoToggle("<name>")` in a macro | The engine macro parser reads this as a primary-spell line. The macro slot in an addon such as pfUI then highlights while the spell is on auto-repeat or its self-aura is active. |
### Console commands
</details>
<details>
<summary><b>Slash commands</b> — <code>[conditions]</code> on 42 commands</summary>
The bundled addon registers these commands. Each one takes the same
`[conditions]` and `@unit` syntax as `/cast`. Each client language has its
own command names next to the English ones. See
[More commands with `[conditions]`](docs/API.md#more-commands-with-conditions)
for what each command does, and
[`/castsequence`](docs/API.md#castsequence) and
[`/castrandom`](docs/API.md#castrandom-and-userandom) for the list forms.
| Group | Commands |
|-------|----------|
| Casting | `/cast`, `/use`, `/castsequence`, `/castrandom`, `/userandom`, `/stopcasting`, `/stopmacro`, `/cancelaura`, `/cancelform`, `/dismount` |
| Targeting | `/target`, `/targetexact`, `/cleartarget`, `/targetlasttarget`, `/targetlastenemy`, `/targetenemy`, `/targetfriend`, `/targetenemyplayer`, `/targetfriendplayer`, `/targetparty`, `/targetraid`, `/assist`, `/follow`, `/focus`, `/clearfocus`, `/startattack`, `/stopattack` |
| Equipment | `/equip`, `/equipslot`, `/equipset` |
| Action bars | `/changeactionbar`, `/swapactionbar`, `/click` |
| Pet | `/petattack`, `/petfollow`, `/petstay`, `/petpassive`, `/petdefensive`, `/petaggressive`, `/petautocaston`, `/petautocastoff`, `/petautocasttoggle` |
</details>
<details>
<summary><b>CVars</b> — new settings, set with <code>/console name value</code></summary>
Each setting is saved in `WTF\Config.wtf`. Read and write them with `GetCVar`
/ `SetCVar` or `/console`. Click a group name for the full rules. To change
these settings, the player cache and the ClassicAPI key bindings in the game,
open the game menu and click AddOn Options, then ClassicAPI.
| Group | CVar | Default | What it does |
|-------|------|---------|--------------|
| [Bindings](docs/API.md#actionbuttonusekeydown) | `ActionButtonUseKeyDown` | `0` | `1` uses an action-bar key binding when you press the key. `0` uses it when you release the key. |
| [Combat](docs/API.md#stopautoattackontargetchange) | `stopAutoAttackOnTargetChange` | `0` | `1` stops melee auto-attack, Auto Shot and wand shots when you change target. |
| [Combat log](docs/API.md#kept-entries) | `combatLogRetentionTime` | `300` | The number of seconds that the combat log keeps an entry. |
| [Stand, dismount and form](docs/API.md#stand-dismount-and-form-settings-autostand-autodismount-autounshift) | `autoStand` | `0` | `1` makes you stand up when you cast, loot or open the flight map while you sit. |
| | `autoDismount` | `0` | `1` makes you dismount when you cast, use an object, loot, attack or open the flight map while you are mounted. |
| | `autoUnshift` | `0` | `1` makes you leave your form when you cast a spell that cannot be cast in it, use an item, or open the flight map. It also lets you talk to NPCs and use objects in druid forms and Ghost Wolf. |
| [Bag sorting](docs/API.md#c_containergetsortbagsrighttoleft--c_containersetsortbagsrighttoleftenable) | `sortBagsRightToLeft` | `0` | `1` makes a sort fill your bags from the last slot of the last bag. |
| | `backpackAutosortDisabled` | `0` | `1` keeps the items in your backpack in place when you sort your bags. |
| | `bankAutosortDisabled` | `0` | `1` keeps the items in the main bank slots in place when you sort your bank. |
| [Expanded cursors](docs/API.md#expanded-cursors-expandedcursors) | `expandedCursors` | `0` | `1` makes the cursor show what you can do with an NPC or an object: an anvil for repairs, a hearthstone for an inn, a horseshoe for a stable, `!` or `?` for quests, and a fish hook for your fishing bobber. |
| [Equipment sets](docs/API.md#equipment-sets-on-item-tooltips) | `dontShowEquipmentSetsOnItems` | `0` | `1` removes the Equipment Sets line from item tooltips. |
| [Name completion](docs/API.md#name-completion-settings) | `autoCompleteResortNamesOnRecency` | `1` | `1` puts the players that you whispered first in `C_AutoComplete` results, the most recent first. `0` uses alphabetical order. |
| | `autoCompleteWhenEditingFromCenter` | `1` | `1` also matches the text after the cursor when you type inside a name. |
| | `autoCompleteUseContext` | `1` | `0` makes `C_AutoComplete` ignore `includeFlags` and `excludeFlags`. |
| [Profiling](docs/API.md#scriptprofile) | `scriptProfile` | `0` | `1` turns on CPU profiling for the `*CPUUsage` functions. The change starts after `/reload`. |
| [Soft interact](docs/API.md#soft-interact-softinteract--anyinteract) | `SoftTargetInteract` | `3` | Turns `softinteract` on: `2` keyboard and mouse, `3` always, `0` / `1` off. |
| | `SoftTargetInteractArc` | `0` | Where the object can be: `0` straight ahead of the camera, `1` within 30° of it, `2` any direction. |
| | `SoftTargetInteractRange` | `10` | Maximum distance in yards. |
| | `SoftTargetInteractRangeIsHard` | `0` | `1` always applies the range. `0` also picks an object past it that you can use now. |
| | `SoftTargetIconInteract` | `0` | `1` shows an icon over the soft-interact object. |
| | `SoftTargetIconGameObject` | `0` | `1` also shows that icon over game objects. |
| [Soft enemy / friend](docs/API.md#soft-enemy-and-soft-friend-softenemy--softfriend--anyenemy--anyfriend) | `SoftTargetEnemy` / `SoftTargetFriend` | `1` / `0` | Turns `softenemy` / `softfriend` on: `2` keyboard and mouse, `3` always, `0` / `1` off. |
| | `SoftTargetEnemyArc` / `SoftTargetFriendArc` | `0` | The same values as `SoftTargetInteractArc`. |
| | `SoftTargetEnemyRange` / `SoftTargetFriendRange` | `45` | Maximum distance in yards. |
| | `SoftTargetMatchLocked` | `1` | `1` uses your target as the soft unit when it qualifies. `0` always uses the nearest unit. |
| | `SoftTargetWithLocked` | `1` | `0` turns soft enemy and soft friend off while you have a locked target. |
| | `SoftTargetForce` | `1` | A loose target follows `softenemy` (`1`) or `softfriend` (`2`). `0` keeps it. |
| | `SoftTargetIconEnemy` / `SoftTargetIconFriend` | `0` | `1` shows an icon over `softenemy` / `softfriend`. |
| | `SoftTargetLowPriorityIcons` | `0` | `1` also shows the normal pointer as an icon. |
| | `SoftTargetNameplateSize` | `19` | Size of all soft-target icons. |
| [Localization](docs/API.md#breakuplargenumbers-cvar) | `breakUpLargeNumbers` | `1` | `1` puts a separator between each group of three digits in `BreakUpLargeNumbers`. `0` writes no separator. |
| [Cooldown](docs/API.md#createframecooldown--name-parent-template) | `countdownForCooldowns` | `0` | `1` shows the time left as numbers on cooldown frames. |
| `ScriptAnimationUtil` | `ShakeStrengthUI` | `1` | Scales how far `ScriptAnimationUtil.ShakeFrame` moves a frame. `0` turns the shake off. |
| [NamePlate](docs/API.md#nameplate) | `nameplateNotSelectedAlpha` | `0.5` | Alpha of a non-target default nameplate, `0` to `1`. |
| | `nameplateSelectedAlpha` | `1` | Alpha of the target's default nameplate, `0` to `1`. |
| [Text to speech](docs/API.md#tts-cvars) | `ttsVoice` | `0` | The voice that `C_VoiceChat.SpeakText` uses. |
| | `ttsSpeed` | `0` | Speech rate, `-10` to `10`. |
| | `ttsVolume` | `100` | Speech volume, `0` to `100`. |
</details>
<details>
<summary><b>Console commands</b> — developer console (<code>-console</code>)</summary>
Registered on the engine's developer console (the `~` console available
when launching with `-console`), not as Lua functions. See the
@@ -108,12 +269,27 @@ when launching with `-console`), not as Lua functions. See the
| `ExportInterfaceFiles code` | Extracts Blizzard's UI source (`.lua`/`.xml`/`.toc`/`.xsd`) from the MPQs to `BlizzardInterfaceCode\` |
| `ExportInterfaceFiles art` | Extracts Blizzard's UI art (`.blp`/`.tga`) from the MPQs to `BlizzardInterfaceArt\` |
| `ExportDBCFiles` | Extracts the client's `.dbc` tables from the MPQs to `DBFilesClient\` |
| `ExportSoundFiles [subpath]` | Extracts the client's sound files from the MPQs to `BlizzardSound\`; the optional subpath narrows it (the full tree is ~1 GB) |
| `pitchLimit degrees` | Sets how far the camera can tilt up and down (default 89) |
| `AppendLogToFile [filename] [numLines]` | Writes the console output to a text file (default `ConsoleLogs\Log<Timestamp>.txt`) |
| Tab / Ctrl+Tab | Tab completes CVar names after `set`, `cvar_reset` and `cvar_default`; Ctrl+Tab lists every command that contains the typed text |
### Events
</details>
<details>
<summary><b>Events</b> — new events fired to addons</summary>
| Event | Payload |
|-------|---------|
| `ACTION_RANGE_CHECK_UPDATE` | `slot, isInRange, checksRange` (slots with `C_ActionBar.EnableActionRangeCheck` on) |
| `ACTION_USABLE_CHANGED` | `changes` (a `{ slot, usable, noMana }` table for each slot that changed) |
| `BAG_NEW_ITEMS_UPDATED` | *(none)* |
| `BAG_UPDATE_DELAYED` | *(none)* |
| `CHAT_MSG_*` | adds `lineID, guid` as `arg11, arg12` after the existing ten ([details](docs/API.md#chat_msg_-arguments-lineid-arg11-and-guid-arg12)) |
| `COMBAT_LOG_EVENT` | `timestamp, subevent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...` ([details](docs/API.md#combat_log_event_unfiltered--combat_log_event-events)) |
| `COMBAT_LOG_EVENT_UNFILTERED` | same as `COMBAT_LOG_EVENT` |
| `CURSOR_CHANGED` | `isDefault, newCursorType, oldCursorType, oldCursorVirtualID` |
| `DYNAMIC_GOSSIP_POI_UPDATED` | *(none)* |
| `EQUIPMENT_SETS_CHANGED` | *(none)* |
| `EQUIPMENT_SWAP_PENDING` | `setID` |
| `EQUIPMENT_SWAP_FINISHED` | `success, setID` |
@@ -121,74 +297,150 @@ when launching with `-console`), not as Lua functions. See the
| `GLOBAL_MOUSE_DOWN` | `button` |
| `GLOBAL_MOUSE_UP` | `button` |
| `HEARTHSTONE_BOUND` | *(none)* |
| `INCOMING_RESURRECT_CHANGED` | `unitTarget` |
| `INVENTORY_SEARCH_UPDATE` | *(none)* |
| `ITEM_DATA_LOAD_RESULT` | `itemID, success` |
| `LEARNED_SPELL_IN_SKILL_LINE` | `spellID, skillLineIndex, isGuildPerkSpell` |
| `LOOT_HISTORY_ROLL_CHANGED` | `itemIndex, playerIndex` |
| `LOOT_HISTORY_ROLL_COMPLETE` | `itemIndex` |
| `LOOT_SCAN_COMPLETED` | *(none)* |
| `LOSS_OF_CONTROL_ADDED` | `eventIndex` |
| `LOSS_OF_CONTROL_UPDATE` | `unitToken` (always `"player"`) |
| `MAP_EXPLORATION_UPDATED` | *(none)* |
| `MODIFIER_STATE_CHANGED` | `keyName, down` |
| `NAME_PLATE_CREATED` | `nameplateFrame` |
| `NAME_PLATE_UNIT_ADDED` | `unitToken` ("nameplateN") |
| `NAME_PLATE_UNIT_REMOVED` | `unitToken` ("nameplateN") |
| `PLAYER_AVG_ITEM_LEVEL_READY` | *(none)* |
| `PLAYER_EQUIPMENT_CHANGED` | `equipmentSlot, hasCurrent` |
| `PLAYER_FOCUS_CHANGED` | *(none)* |
| `PLAYER_MOUNT_DISPLAY_CHANGED` | *(none)* |
| `PLAYER_SOFT_ENEMY_CHANGED` | *(none)* |
| `PLAYER_SOFT_FRIEND_CHANGED` | *(none)* |
| `PLAYER_SOFT_INTERACT_CHANGED` | `oldTarget, newTarget` |
| `PLAYER_STARTED_LOOKING` | *(none)* |
| `PLAYER_STOPPED_LOOKING` | *(none)* |
| `PLAYER_STARTED_MOVING` | *(none)* |
| `PLAYER_STOPPED_MOVING` | *(none)* |
| `PLAYER_STARTED_TURNING` | *(none)* |
| `PLAYER_STOPPED_TURNING` | *(none)* |
| `PLAYER_SWING` | `swingDuration, swingType` |
| `PLAYER_SWING_RANGE_UPDATE` | `swingType, isInRange, checksRange` |
| `PLAYER_TOTEM_UPDATE` | `totemSlot` |
| `QUEST_ACCEPTED` | `questLogIndex, questID` |
| `QUEST_DATA_LOAD_RESULT` | `questID, success` |
| `QUEST_QUERY_COMPLETE` | *(none)* (Turtle WoW only) |
| `QUEST_REMOVED` | `questID` |
| `QUEST_TURNED_IN` | `questID, xpReward, moneyReward` |
| `SELF_RES_SPELL_CHANGED` | *(none)* |
| `SOUNDKIT_FINISHED` | `soundHandle` (only for sounds played with `runFinishCallback`) |
| `SPELL_ACTIVATION_OVERLAY_SHOW` | `spellID, texture, locationType, scale, r, g, b` ([details](docs/API.md#spell_activation_overlay_show--spell_activation_overlay_hide-events)) |
| `SPELL_ACTIVATION_OVERLAY_HIDE` | `spellID` (`nil` hides every alert) |
| `SPELL_ACTIVATION_OVERLAY_GLOW_SHOW` | `spellID` ([details](docs/API.md#spell_activation_overlay_glow_show--spell_activation_overlay_glow_hide-events)) |
| `SPELL_ACTIVATION_OVERLAY_GLOW_HIDE` | `spellID` |
| `UI_SCALE_CHANGED` | *(none)* |
| `UNIT_AREA_CHANGED` | `unitTarget` |
| `UNIT_AURA_DELTA` | `unitTarget, updateInfo` (the instance IDs of the auras added, updated, and removed) |
| `UNIT_CONNECTION` | `unitTarget, isConnected` |
| `UNIT_DISTANCE_CHECK_UPDATE` | `unitTarget, isInDistance` |
| `UNIT_IN_RANGE_UPDATE` | `unitTarget, isInRange` |
| `UNIT_SPELLCAST_SENT` | `"player", target, castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_START` | `unit, castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_STOP` | `unit, castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_DELAYED` | `"player", castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_SUCCEEDED` | `unit, castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_INTERRUPTED` | `unit, castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_FAILED` | `"player", castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_FAILED_QUIET` | `"player", castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_CHANNEL_START` | `unit, castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_CHANNEL_UPDATE` | `"player", castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_CHANNEL_STOP` | `unit, castGUID, spellID, spellName, rank` |
| `UNIT_SPELLCAST_RETICLE_TARGET` | `"player", "", spellID, spellName, rank` |
| `UNIT_SPELLCAST_RETICLE_CLEAR` | `"player", "", spellID, spellName, rank` |
| `UNIT_SPELLCAST_INTERRUPTIBLE` | `unit` |
| `UNIT_SPELLCAST_NOT_INTERRUPTIBLE` | `unit` |
| `UNIT_MAXPOWER` | `unitTarget, powerType` |
| `UNIT_POWER_FREQUENT` | `unitTarget, powerType` |
| `UNIT_POWER_UPDATE` | `unitTarget, powerType` |
| `UNIT_SPELL_HASTE` | `unitTarget` |
| `UNIT_TARGET` | `unitTarget` |
| `UNIT_TARGETABLE_CHANGED` | `unitTarget` |
| `UPDATE_INVENTORY_DURABILITY` | *(none)* |
| `UPDATE_SHAPESHIFT_FORM` | *(none)* |
| `USER_WAYPOINT_UPDATED` | *(none)* |
| `VOICE_CHAT_TTS_PLAYBACK_STARTED` | `numConsumers, utteranceID, durationMS, destination` |
| `VOICE_CHAT_TTS_PLAYBACK_FINISHED` | `numConsumers, utteranceID, destination` |
| `VOICE_CHAT_TTS_PLAYBACK_FAILED` | `status, utteranceID, destination` |
| `VOICE_CHAT_TTS_VOICES_UPDATE` | *(none)* |
| `WEAPON_SLOT_CHANGED` | *(none)* |
| `WEAR_EQUIPMENT_SET` | `setID` |
### Globals
</details>
<details>
<summary><b>Globals & enums</b></summary>
| Group | Constants |
|-------|-----------|
| Version | `CLASSIC_API_VERSION` |
| Version | `CLASSIC_API_VERSION`, `INTERFACE_VERSION` |
| Expansion | `LE_EXPANSION_LEVEL_CURRENT`, `LE_EXPANSION_CLASSIC` … `LE_EXPANSION_MIDNIGHT` |
| Item quality | `LE_ITEM_QUALITY_POOR` … `LE_ITEM_QUALITY_WOWTOKEN` |
| Unit stat | `LE_UNIT_STAT_STRENGTH` … `LE_UNIT_STAT_SPIRIT` |
| Addon security | `Enum.AddOnSecurityStatus.{Secure,Insecure,Banned,NotAvailable}` |
| Power type | `Enum.PowerType.{HealthCost,None,Mana,Rage,Focus,Energy,Happiness}` |
| Inventory type | `Enum.InventoryType.Index*Type` (0–34, e.g. `IndexHeadType`=1 … `IndexRelicType`=28) |
| Item class | `Enum.ItemClass.{Consumable,Container,Weapon,Gem,Armor,Reagent,Projectile,Tradegoods,ItemEnhancement,Recipe,Quiver,Questitem,Key,Miscellaneous,…}` (0–19) |
| Item quality | `Enum.ItemQuality.{Poor,Common,Uncommon,Rare,Epic,Legendary,Artifact}` (0–6) |
| Cursor type | `Enum.UICursorType.{Default,Item,Money,Spell,PetAction,Merchant,Macro,Pet,…}` (0–20; this client yields 0–5, 7 and 9) |
| Spellbook bank | `Enum.SpellBookSpellBank.{Player,Pet}` (0–1) |
| Spellbook item type | `Enum.SpellBookItemType.{None,Spell,FutureSpell,PetAction,Flyout}` (0–4; 1.12 only yields `Spell`/`PetAction`) |
| Player swing type | `Enum.PlayerSwingType.{MainHand,OffHand,Ranged}` (0–2) |
| Screen location type | `Enum.ScreenLocationType.{Center,Left,Right,Top,Bottom,TopLeft,TopRight,LeftOutside,RightOutside,LeftRight,TopBottom,LeftRightOutside}` (0–11) |
| Self-resurrect option type | `Enum.SelfResurrectOptionType.{Spell,Item}` (0–1) |
| Autocomplete entry flag | `Enum.AutoCompleteEntryFlag.{InGroup,InGuild,Friend,Bnet,InteractedWith,Online,InAOI,AccountCharacter,RecentPlayer}` (bits 1–256) |
| Autocomplete priority | `Enum.AutoCompletePriority.{Other,Interacted,InGroup,Guild,Friend,AccountCharacter,AccountCharacterSameRealm}` (0–6) |
### Unit tokens
</details>
<details>
<summary><b>Unit tokens</b> — <code>nameplateN</code>, <code>focus</code>, <code>markN</code>, <code>softinteract</code>, <code>softenemy</code>, <code>softfriend</code>, <code>anyinteract</code>, <code>anyenemy</code>, <code>anyfriend</code></summary>
| Token | Resolves to |
|-------|-------------|
| `nameplate1`..`nameplateN` | Unit behind the Nth visible nameplate, in creation-order. Works with every `UnitX` function — `UnitName`, `UnitGUID`, `UnitClass`, `UnitHealth`, etc. Suffix chains (`nameplate1target`, `nameplate1targettarget`) compose. See [NamePlate / Unit tokens](docs/API.md#unit-tokens-nameplaten). |
| `focus` / `focustarget` | Sticky target set via [`FocusUnit`](docs/API.md#focusunitunit), cleared via [`ClearFocus`](docs/API.md#clearfocus). Same `UnitX` coverage as `nameplateN`. Fires [`PLAYER_FOCUS_CHANGED`](docs/API.md#player_focus_changed-event) on transition. See [Focus](docs/API.md#focus). |
| `mark1`..`mark8` | Unit currently wearing the Nth raid-target marker (`mark1` = star … `mark8` = skull). Same `UnitX` coverage as `nameplateN`, and fires unit events (`UNIT_HEALTH`, `UNIT_AURA`, …) with `arg1 == "markN"`. `UnitExists("markN")` is `false` when the marker is unset, out of range, or on a non-unit. Suffix chains (`mark1target`) compose. See [Unit tokens (`markN`)](docs/API.md#unit-tokens-markn). |
| `softinteract` / `anyinteract` / `anyleftinteract` | The object that the Interact Key uses. `softinteract` is the nearest object in front of you that you can interact with. `anyinteract` is your target when you can interact with it, else `softinteract`. Both can be a game object or a corpse, which only `UnitGUID` reads. See [Soft interact](docs/API.md#soft-interact-softinteract--anyinteract). |
| `softenemy` / `softfriend` / `anyenemy` / `anyfriend` | The nearest enemy and the nearest friendly unit, or your target when it qualifies. `anyenemy` and `anyfriend` use your target first. See [Soft enemy and soft friend](docs/API.md#soft-enemy-and-soft-friend-softenemy--softfriend--anyenemy--anyfriend). |
### Bindings
</details>
Injected into the engine's **Targeting Functions** group at FrameXML
Bindings.xml load time, so they appear in the keybind UI alongside
native targeting bindings instead of orphaned at the bottom.
<details>
<summary><b>Bindings</b> — direct-action and override binding families</summary>
ClassicAPI backports the direct-action and temporary override
binding families. Permanent bindings use the standard `SPELL`, `ITEM`,
`MACRO`, and `CLICK` command strings and can be saved normally. Overrides are
session-only, frame-owned, and support the usual priority flag.
See the [Bindings API reference](docs/API.md#bindings) for signatures,
precedence, execution behavior, macro-text usage, and 1.12 compatibility
notes.
**Predefined focus bindings.** Injected into the engine's **Targeting
Functions** group at FrameXML Bindings.xml load time, so they appear in the
keybind UI alongside native targeting bindings instead of orphaned at the
bottom.
| Binding | Action |
|---------|--------|
| `FOCUSTARGET` | `FocusUnit("target")` — pin current target as focus |
| `TARGETFOCUS` | `TargetUnit("focus")` — switch target to the focus |
See [Focus / Bindings](docs/API.md#bindings-focustarget--targetfocus) for the implementation note.
See [Predefined focus bindings](docs/API.md#predefined-focus-bindings-focustarget--targetfocus)
for the implementation note.
### Behaviors
Transparent engine tweaks — no API to call, they just fix a vanilla limitation:
| Tweak | Effect |
|-------|--------|
| Tooltip line cap | Lifts `GameTooltip`'s hard 30-line limit to 60 for every `GameTooltipTemplate` frame (`GameTooltip`, `ShoppingTooltip1/2`, `ItemRefTooltip`, AtlasLoot, …). Stat-heavy tooltips and comparison blocks (e.g. pfUI's eqcompare) no longer have their extra lines silently dropped. Done in pure C++ by growing the engine's FontString pool at tooltip-creation time. |
</details>
## Installation
@@ -202,75 +454,88 @@ Download the prebuilt `ClassicAPI.dll` from the
3. Add `ClassicAPI.dll` to `dlls.txt`.
4. Launch the game with `VanillaFixes.exe`.
The bundled `!!!ClassicAPI` addon ships *inside* the DLL — no separate
addon download or install step needed.
The `!!!ClassicAPI`, `ClassicAPI_DebugTools` and `ClassicAPI_EventTrace`
addons are *inside* the DLL. You do not download or install them. The
`src/embed/AddOns/` folder in this repository is source code for the DLL.
Do not copy it into your game.
## Bundled addon: !!!ClassicAPI
The Lua-side companion library lives in
[`AddOns/!!!ClassicAPI/`](AddOns/!!!ClassicAPI/). It's a 1.12.1 /
[`src/embed/AddOns/!!!ClassicAPI/`](src/embed/AddOns/!!!ClassicAPI/). It's a 1.12.1 /
Lua 5.0 backport of the modern Blizzard helpers that aren't engine
functions but that consumer code still expects to find as globals —
`Mixin` / `CreateFromMixins`, `CallbackRegistryMixin`, `EventRegistry`,
`ColorMixin` + `CreateColor`, `Item` / `ItemLocation`, `MathUtil`
(`Lerp` / `Clamp` / `CreateCounter`), `TableUtil` (`tCompare`,
`MergeTable`, `SafePack`, etc.), and `EventUtil`
(`ContinueOnAddOnLoaded` etc.).
Some of the addon's surface depends on engine functions ClassicAPI
provides (`C_UIColor.GetColors` populates the modern color globals,
`C_Item.GetItemInfoInstant` powers `ItemMixin`, the
`ITEM_DATA_LOAD_RESULT` event drives `ContinueOnItemLoad`); the rest
is pure Lua and would work standalone. Without the DLL the addon
still loads, but those features no-op.
The triple-`!` prefix is **load-order-significant** — WoW loads
addons alphabetically, so `!!!ClassicAPI` is guaranteed to run before
any consumer that depends on its globals. Don't rename the folder.
`CallbackRegistryMixin`, `EventRegistry`, `ColorMixin` + `CreateColor`,
`Item` / `ItemLocation`, `MathUtil`(`Lerp` / `Clamp` / `CreateCounter`),
`TableUtil` (`tCompare`, `MergeTable`, `SafePack`, etc.), `EventUtil`
(`ContinueOnAddOnLoaded` and more), `FormattingUtil` (`GetMoneyString`,
`FormatLargeNumber` and more), `FrameUtil`, `DataProvider`, `CircularBuffer`,
`EasingUtil`, `ScriptAnimationUtil`, `Interpolator`, `EnumUtil`, `StringUtil`, `AnchorUtil`,
`GridLayoutUtil`, and the layout frame templates (`VerticalLayoutFrame`,
`HorizontalLayoutFrame`, `ResizeLayoutFrame`, `GridLayoutFrame`,
`StaticGridLayoutFrame`). It also holds the conditional slash
commands and `SecureCmdOptionParse`, the parser that reads `[conditions]`
and `@unit` for them.
**You don't have to install the addon manually** — the DLL embeds
the contents of [`AddOns/!!!ClassicAPI/`](AddOns/!!!ClassicAPI/) and
the contents of [`src/embed/AddOns/!!!ClassicAPI/`](src/embed/AddOns/!!!ClassicAPI/) and
registers them with the engine as a synthetic addon on startup, so
the library is always available when the DLL is loaded. The engine
sees it as a normal addon: it appears in `GetAddOnInfo`, fires
`ADDON_LOADED`, supports `SavedVariables`, the works.
the library is always available when the DLL is loaded. It fires
`ADDON_LOADED`, supports `SavedVariables`, and is resolvable by name —
`IsAddOnLoaded("!!!ClassicAPI")`, `GetAddOnInfo("!!!ClassicAPI")`, and
`## Dependencies: !!!ClassicAPI` all work as usual.
If you do drop the folder into your `Interface/AddOns/` directory,
**that copy wins** — the DLL's embedded version is only registered
when the engine's normal scan doesn't already have an entry under
that name. Useful for editing the Lua locally without rebuilding the
DLL. The dispatch is transparent: addons consuming `Mixin`,
`ColorMixin`, `TableUtil`, etc. behave identically in both cases.
**It is intentionally always-on and cannot be disabled.** The library
provides FrameXML-compat fixes that other addons and the DLL's own
features rely on, so leaving it toggleable would let a user (or a
one-off character-select uncheck) silently break them. The DLL
therefore hides it from the character-select AddOns list and
force-enables it every login — so it never appears as a checkbox and
can't be switched off. Being hidden means it's omitted from the
index-based `GetNumAddOns()` / `GetAddOnInfo(i)` enumeration, but every
by-name lookup and dependency reference still resolves normally.
## Bundled addon: DebugTools
For development, you can put a copy of the addon folder in
`Interface/AddOns/` and add an empty `.classicapi-dev` file to it. The
game then reads the Lua files from that copy, so you can edit them
without a DLL rebuild. Without this file, the game uses the copy with the
newer `## Version:`. The copy is hidden and always enabled, the same as
the embedded addon.
A 1.12.1 / Lua 5.0 backport of Blizzard's `Blizzard_DebugTools` addon
(originally shipped with the 3.0 client) lives in [`AddOns/DebugTools/`](AddOns/DebugTools/).
It's an independent addon — it doesn't use anything ClassicAPI adds, and
ClassicAPI works fine without it. It's bundled here because it's the
natural companion for testing and debugging anything written against the
1.12 Lua surface (with or without the ClassicAPI extensions).
## Lua errors
Slash commands provided:
ClassicAPI replaces the game's Lua error box with a Lua error window. The
window opens when an error occurs. It shows the message, the time, the count,
the stack and the local variables of each error. You can select and copy the
text. The arrow buttons show the previous and the next error. The
**Reload UI** button reloads the interface.
If you use `!BugGrabber` (with BugSack), BugGrabber gets the errors and the
window does not open. If an addon sets its own error handler, the window also
does not open.
| Command | Purpose |
|---------|---------|
| `/dump <expr>` | Pretty-print any Lua value, including tables and multi-return tuples. The right tool for inspecting return values from `GetSpellInfo`, `C_Item.GetItemInfoInstant`, etc. |
| `/etrace` | Event tracer window. `/etrace start`, `/etrace stop`, `/etrace add EVENT`, etc. |
| `/framestack` (or `/fstack`) | Tooltip showing the frame hierarchy under the mouse cursor. |
| `/luaerrors` (or `/scripterrors`) | Lua error display window. |
| `/luaerrors` (or `/scripterrors`) | Opens or closes the Lua error window. |
| `/luaerrors clear` | Removes all errors from the window. |
Lua globals provided (backports of 3.3.5 helpers that don't exist in
1.12):
## Debug tools
| Global | Purpose |
|--------|---------|
| `print(...)` | Backport of the 3.3.5 `print` — concats varargs with `" "` and pushes to `DEFAULT_CHAT_FRAME`. Routes through `setprinthandler`'s handler; falls back via `geterrorhandler` if the handler errors. |
| `setprinthandler(func)` / `getprinthandler()` | Install / query a custom print handler. Useful for redirecting print output in tests. |
| `tostringall(...)` | Apply `tostring()` to every vararg, preserving the count. Lua 5.0-compatible (uses `arg.n` since `select` doesn't exist in 5.0). |
ClassicAPI contains backports of two Blizzard addons: `Blizzard_DebugTools`,
with the name `ClassicAPI_DebugTools`, and `Blizzard_EventTrace`, with the
name `ClassicAPI_EventTrace`. The DLL contains these addons, so you do not
install them. They are not in the AddOns list, and you cannot disable them.
To install: copy [`AddOns/DebugTools/`](AddOns/DebugTools/) into your
`Interface/AddOns/` directory like any other addon.
The slash commands are always available. Each addon loads the first time
that you use one of its commands:
| Command | Purpose |
|---------|---------|
| `/dump <expr>` | Shows a Lua value in the chat frame. It shows tables and all return values. Use it to examine the return values of `GetSpellInfo`, `C_Item.GetItemInfoInstant`, and other functions. |
| `/etrace` (or `/eventtrace`) | Opens or closes the event trace window. The window logs each event with its time and its arguments. Move the mouse over an event to see its arguments, and the contents of each table argument. You can search the log, hide events with the filter, and pause the log. `/etrace mark <text>` adds a line of text to the log. |
| `/framestack [showHidden [showRegions]]` (or `/fstack`) | Shows a tooltip with a list of the frames under the cursor. A `-->` mark shows one frame, with its anchors and the file and line that made it. Left Alt and Right Alt move the mark. Ctrl opens the marked frame in the table inspector. Shift shows its texture files. The tooltip also shows the addon that made the marked frame. When `scriptProfile` is `1`, it shows the CPU time of the frame scripts. |
| `/tinspect [expr]` (or `/tins`) | Opens a table inspector on the result of `expr`. With no table, it opens on the frame under the cursor. The window shows the anchors and the fields of the table, grouped by type. You can edit numbers, strings and booleans, filter the lines, and open a child table or frame. |
| `/profiler` (or `/prof`) | Opens the profiler. The profiler shows the Lua memory, the allocations and the CPU time of each addon, frame, event and global function. `/profiler widget` shows a small window with the Lua memory, the frame rate and the addons that use the most. `/profiler reset` sets the counters to zero. CPU times need `scriptProfile` `1`. `/profiler profile on` sets it and reloads the UI. |
## Building
+675 -155
View File
@@ -5,23 +5,25 @@ Candidates for new DLL functions, prioritized. All are things the
addon polyfills badly, hackily, or not at all, and where engine access is the
right answer.
## ~~1. `C_QuestLog.IsQuestFlaggedCompleted(questID)`~~ — NOT FEASIBLE in 1.12
## ~~1. `C_QuestLog.IsQuestFlaggedCompleted(questID)`~~ — DONE (Turtle-lineage servers)
The original TODO note ("engine maintains a completed-quests bitfield in
client memory") was based on 3.3.5 / WotLK semantics. Vanilla 1.12 has no
equivalent: neither `QueryQuestsCompleted` nor `GetQuestsCompleted`
exists, the protocol has no `CMSG_QUERY_QUESTS_COMPLETED`, and the
client doesn't track historical completions. The polyfill at
`Util/C_QuestLog.lua:5-8` works on Frostmourne (3.3.5a) where those
functions exist; on the 1.12 Octo client they're absent.
Stock 1.12 has no completed-quests query and keeps no quest history, so
this exists only where the server offers the list another way. Turtle WoW
and its forks answer the player command `.queststatuses` with `TWQUEST`
guild addon messages from the player, split at 2000 characters, the last
message always shorter (probed: 2003, 2004, 0) - an exact end marker.
Servers that want to expose this in 1.12 (notably Turtle WoW) do it
via the `CHAT_MSG_ADDON` channel — the addon sends `.queststatus` over
guild/whisper chat and the server replies with addon-channel messages
the addon parses. Fundamentally async, server-specific, and requires
SavedVariables-style persistence across sessions to amortize the
round-trip — all of which belong on the Lua side, not in this DLL.
There's nothing the DLL can usefully add here.
[src/quest/Completed.cpp](src/quest/Completed.cpp) does it all in the DLL,
Turtle clients only: it sends the request itself (on
SMSG_LOGIN_VERIFY_WORLD, after each turn-in, and from
`QueryQuestsCompleted`), reads every answer at the packet funnel (sender
must be the player), and keeps the live list behind `GetQuestsCompleted`,
`C_QuestLog.IsQuestFlaggedCompleted` and
`C_QuestLog.GetAllCompletedQuestIDs`; `QUEST_QUERY_COMPLETE` fires per
answer. No disk cache: the first answer lands one round trip after
PLAYER_ENTERING_WORLD, because the server sends the player object (which
fires PLAYER_LOGIN) before it reads any request. Replaces the closed Lua
collector of PR #86.
## ~~2. `C_Spell.GetSpellDescription(spellID)`~~ — DONE
@@ -147,7 +149,7 @@ on a frame timer" goal landed as the request/event pair below:
cache (or synchronously if it was already loaded).
Together those replace the polyfill's 180-second polling frame
(`ItemEventListener` in `Util/ItemUtil.lua:254-372`) — addons can now
(`ItemEventListener`, now in `Util/AsyncCallbackSystem.lua`) — addons can now
fire `RequestLoadItemDataByID(id)` and listen for
`ITEM_DATA_LOAD_RESULT` instead.
@@ -455,8 +457,7 @@ the other spell registrations in [src/spell/Info.cpp](src/spell/Info.cpp).
## ~~26. `C_Item.IsEquippableItem(item)`~~ — DONE
Cache-record read of `m_inventoryType` at `OFF_ITEMSTATS_INVENTORY_TYPE`.
Non-zero = equippable. Lives in `item/Equipment.cpp` alongside
`OffhandHasWeapon` (which uses the same field) and `IsEquippedItem`.
Non-zero = equippable. Lives in `item/Equipment.cpp` alongside `IsEquippedItem`.
Synchronous; returns `false` on cache miss without firing a load.
Namespaced under `C_Item` to match Classic Era 1.15.x.
@@ -951,88 +952,15 @@ See [src/unit/Tooltip.cpp](src/unit/Tooltip.cpp) and the
`FUN_SCRIPT_GAMETOOLTIP_SET_UNIT_*` block in
[src/Offsets.h](src/Offsets.h).
## 46. `GameTooltip:SetFrameStack([showHidden])` — deferred (Lua-side fix in place)
## ~~46. `GameTooltip:SetFrameStack([showHidden])`~~ — DONE
Renders a tooltip listing the chain of frames at the mouse cursor,
sorted by strata + level. The 3.0+ debug-tooling primitive used by
Blizzard's `Blizzard_DebugTools` and every layout-debugging addon.
### Current state in this project
Our bundled `DebugTools/` backport ships its own `FrameStackTooltip`
in [DebugTools/DebugTools.lua](DebugTools/DebugTools.lua), driven
by `_CollectFramesUnderMouse`. As of the EnumerateFrames switch,
the iterator walks the engine's own frame list — fast (typically
~hundreds of entries) and includes anonymous frames the engine
sees but a `_G` walk would miss.
What's still missing relative to the real engine `SetFrameStack`:
- **Anonymous-frame display name.** We currently show
`<anonymous>` for frames where `frame:GetName()` returns nil.
The engine's method shows the frame's pointer + the Lua-side
registry-table address. To get there we'd need a Lua-callable
shim that exposes a numeric handle per frame (vftable + Lua-ref
lookup), which is non-trivial.
- **Single-tooltip semantics.** Modern addons can call
`GameTooltip:SetFrameStack(...)` directly on any tooltip;
ours requires the `FrameStackTooltip` we ship in `DebugTools/`.
Most consumers (`Blizzard_DebugTools` ports, layout addons via
`/framestack`) don't care, but a strict polyfill would.
### C++ port from 3.3.5 — kept as a research note
What `Script_GameTooltip_SetFrameStack`
actually does in 3.3.5 (Frostmourne client, registration entry at
VA 0x00AD2CF0 → function VA 0x00626560 → inner builder
`FUN_006230d0`):
- Pulls cursor (in frame space) via `FUN_0047BFF0` from a render-
state global at `[DAT_00B499A8 + 0x1224 / +0x1228]`.
- Walks an intrusive linked list at `[DAT_00B499A8 + 0xCD4]`. Each
frame node reads:
- `[+0x00]` — vftable; `vftable[+0x10]` = "is the frame visible
enough to hit-test" predicate.
- `[+0x0E0]` (`node[0x38]`) = strata; gates `(strata != 0 ||
showHidden)`.
- `[+0x0D0]..[+0x0DC]` (`node[0x34..0x37]`) = frame rect for
hit-test.
- `[+0x0D8]` (`node[0x36]`) flags, bit 2 → visible.
- `[+0x288]` (`node[0xA2]`) = next pointer.
- Per-frame name via `vftable[+0x04]` (a `GetDebugName()`-style
virtual). If the frame is Lua-side (`vftable[+0x10]` returns
type code 5), an extra `lua_rawgeti(L, REGISTRY, frame->luaRef)`
pulls the Lua-table reference for the `"%s: %p (%s)"` format;
otherwise it's `"%s: %p"`.
- Builds into a scratch sort array at `DAT_00C5D370` (entry stride
`0x410`), `qsort` against comparator `FUN_0061A5B0`.
- Header line via `FUN_00819D40("DEBUG_FRAMESTACK", ...)` (Lua
`GetGlobalString`) then per-entry `FUN_0061FEC0` (tooltip
`AddLine` equivalent, takes color codes from a 4-byte-stride
table at `0xAD2DC0` / `0xAD2DB8` / `0xAD2DB0` for
visible/hidden/special states).
For a 1.12 port we'd need to derive:
- The frame-manager global (3.3.5's `DAT_00B499A8` — different VA
in 1.12, different field offsets likely).
- Frame struct offsets for rect, strata, flags, next, name vftable
slot — the layout shifted between 1.12 and 3.3.5 (same way unit
field offsets did, per the `OFF_UNIT_FIELD_HEALTH` discovery in
CLAUDE.md).
- AddTooltipLine engine address (1.12 has it — every
`GameTooltip:SetX` method calls it internally).
- Lua-side reference lookup helper (whatever 1.12 uses to map
frame → Lua table; the `FrameScript_GetObject` chain at
`0x6F3740` is part of this).
### Recommendation
The Lua-side iterator switch is done. The C++ port stays deferred
unless we need the engine frame list for something else
(`GetMouseFocus` polyfill, anonymous-frame inspector with extra
fields beyond what Lua exposes, single-tooltip strict polyfill,
etc.) that would amortize the RE cost.
A mirror of 4.3.4's CGTooltip::SetFrameStack in
[src/tooltip/FrameStack.cpp](src/tooltip/FrameStack.cpp), plus the
`OnTooltipSetFrameStack` script in Tooltip::SetEvents. Every input exists in
1.12: the CSimpleTop frame list, the NDC cursor + NDCToDDC, CLayoutFrame
GetRect, the frame's visible / enabled-input / strata / level fields,
FrameStrataToString and the two default tooltip colors (all in Offsets.h).
The `/fstack` UI itself is addon Lua and can now call the method.
## ~~47. `IsPlayerSpell(spellID)`~~ — DONE
@@ -1120,51 +1048,50 @@ spell-API functions use. Returns `(1, nil)` / `(nil, 1)` /
`(nil, nil)` per legacy convention. `C_Spell.IsSpellUsable` is the
modern shape — same logic, returns proper booleans.
**Two engine-cache approaches investigated and discarded:**
**Reworked for issue #51 (2026-09-12) — it now IS the engine's
verdict.** `IsUsableAction` reads the per-slot cache
(`0x00BC6B60` usable / `0x00BC67A0` noMana, reader `FUN_004E5230`),
which the recompute `FUN_004E5050` fills per slot. For a player spell
slot that recompute is one call: `FUN_SPELL_IS_USABLE(record,
&noMana)` (`0x006E3D60`). For a pet spell slot it is `FUN_PET_ACTIONS_
USABLE()` then the pet's power vs `FUN_GET_SPELL_COST(spellID, 0)`.
`Spell::Usable` now runs exactly those two paths live (plus a
knowledge gate on `VAR_PLAYER_SPELL_BITMAP`, since the helper is also
fed item on-use spells and never checks knowledge). Verified check
list of the helper is on `FUN_SPELL_IS_USABLE` in `Offsets.h`.
**The first version hand-rolled five checks instead** (known, alive,
off cooldown, power, reagents) and diverged from `IsUsableAction`
exactly where the helper does more or less — the issue #51 repro
(Warrior, Whirlwind):
| State | `IsUsableAction` | old `IsUsableSpell` |
|---|---|---|
| Berserker, 0 rage, on CD | `nil, 1` | `nil, nil` (we tested cooldown first — the engine never does) |
| Battle Stance, 25 rage | `nil, nil` | `1, nil` (we never tested stance) |
Cooldown is deliberately NOT part of usability: FrameXML greys
(`IsUsableAction`) and swipes (`GetActionCooldown`) as two separate
states, and the engine helper has no cooldown branch. Rule #1 case:
`Item::Usable` had been calling the helper all along.
**Two engine-cache approaches investigated and discarded before the
first version** (still true, kept for the record):
1. **Per-spell cache at `0x004F0F40` returning fields at +0x564
/ +0x568** — initially looked promising (the action-bar
dispatcher at `0x004E5BA0` reads these), but the writers
(`0x004EFF17` cluster) showed they're parsed config integers,
not real-time usability bools. False trail.
not real-time usability bools. False trail. (Later identified as
the macro entry's cached primary spell — see the `#showtooltip`
notes.)
2. **Action-bar per-slot caches at `0x00BC67A0` (noMana) and
`0x00BC6B60` (usable)** — these ARE real-time, but only updated
for the 120 action-bar slots. Spells off the bar stay
uninitialized. Action-bar-only is the wrong abstraction since
modern `IsUsableSpell(spellID)` is action-bar-agnostic.
Settled on a **manual five-check approach**:
1. Player knows the spell (`VAR_PLAYER_SPELL_BITMAP` lookup —
covers profession recipes, talents, racials, etc.).
2. Player is alive (`HEALTH > 0`).
3. Spell is not on cooldown (`FUN_SPELL_QUERY_COOLDOWN` —
the engine helper `Script_GetSpellCooldown` calls internally
after slot resolution, queried with `bookType=0` for player).
4. Player has ≥ `ManaCost` of the spell's `PowerType` —
only this failure flips `noMana=true`.
5. Player has all required reagents in bags
(`Spell.dbc` Reagent[8] / ReagentCount[8] at `+0x110` /
`+0x130`, walked via `Item::Location::ResolveBag`).
**Not checked** (deliberate, different concerns): silence, GCD,
stance/form, range, target type, line-of-sight, casting state.
**Verified on Turtle WoW:**
- Mana check: Renew rank 3 (cost 105) reports usable at 144 mana
and unusable at 39 mana, transitioning exactly at the cost
boundary.
- Reagent check: SHIPPED BUT UNVERIFIED — the Reagent[8] /
ReagentCount[8] offsets at `+0x110` / `+0x130` are the
CMaNGOS-documented vanilla layout, and we know spell records
match CMaNGOS docs (PowerType=+0x7C and ManaCost=+0x80 both
match), so high confidence — but no in-game verification yet.
Should test with a reagent spell (e.g., Mage Teleport spell 3565
needs Rune of Teleportation 17031). Failure mode if offsets are
wrong: reagent check becomes a no-op (always passes).
- Cooldown check: SHIPPED BUT UNVERIFIED in this implementation —
the helper signature was traced via `Script_GetSpellCooldown` at
`0x004B40A0` but not exercised in-game. Should test with a
cooldown'd spell.
modern `IsUsableSpell(spellID)` is action-bar-agnostic. The fix
above sidesteps this by calling what FILLS the cache, not the
cache.
**Important offset correction along the way.** Initial implementation
read POWER1 at descriptor `+0x5C` based on the CMaNGOS-documented
@@ -1539,20 +1466,12 @@ it on a struct pointer to scan layouts, or from Lua via
`_classicapi_HexDump(label, addr, len)` to inspect engine
globals without a per-investigation probe module.
## ~~56. `OffhandHasWeapon()`~~ — DONE
## ~~56. `OffhandHasWeapon()`~~ — DROPPED
Shipped as `src/item/Equipment.cpp`. Resolves the off-hand
equipment slot (slot 17) via `Item::Location::ResolveEquipmentSlot`,
reads the cached `ItemStats_C` record's `m_inventoryType` at
`+0x2C`, and returns true iff it's `INVTYPE_WEAPON` (13) or
`INVTYPE_WEAPONOFFHAND` (22). Shields, holdables (tomes/orbs),
empty slots, and uncached items all return false.
No async load is fired — modern API behavior matches; if the
off-hand item isn't cached the function silently returns false
until something else warms the cache. Typically only matters on
first login before the player's own gear is in the cache, which
in practice is loaded eagerly anyway.
Vanilla already ships it (`0x004C9570`, same body as 3.3.5/4.3.4:
off-hand slot item class 2 → `1`, else `nil`). Our override returned
booleans and tested inventory type instead; removed so the engine's
own global stands.
## 57. `IsFlying()` — TESTED, DROPPED
@@ -1741,7 +1660,14 @@ is a thin wrapper. If they're inlined, we'd either need to skip
the clear ourselves (call after some no-op state setup) or
manually call the line-emission primitives.
## ~~61. `GameTooltip:GetItem()` / `GetSpell()` / `GetUnit()`~~ — `GetItem` + `GetSpell` DONE; `GetUnit` skipped
## ~~61. `GameTooltip:GetItem()` / `GetSpell()` / `GetUnit()`~~ — DONE
`GetUnit` shipped later in [src/unit/Tooltip.cpp](src/unit/Tooltip.cpp):
`SetUnit` is re-registered in front of the engine's (no MinHook) to
stage the token, and the token binds in the unit-builder co-hook that
`Tooltip::SetEvents` already owned. The builder has three callers:
SetUnit, the world-mouseover setter (→ `"mouseover"`), and an in-place
refresh (keeps the token). The notes below are the original skip.
Modern query methods that return what the tooltip is currently
showing:
@@ -1847,10 +1773,17 @@ are supported.
### Unhookable globals
Modern WoW rejects `hooksecurefunc("<core lua/secure fn>", ...)` outright
to keep callers from clobbering language primitives or breaking taint
propagation. We mirror that with a name blacklist in `Script_HookSecureFunc`
that fires `lua_error` with `"hooksecurefunc: function is unhookable"`
Patch 11.0.0 (The War Within, 2024-07-23) made `hooksecurefunc` refuse a
fixed set of names with a "Cannot hook function" error, to keep callers
from clobbering language primitives or breaking taint propagation. No
earlier client has the restriction (3.3.5, 4.3.4 and 5.4.8 carry no such
string), so 11.0's published list is the reference — and it is NOT the
engine's base-library table (`0x00811E28`, 36 entries, catalogued in
`BlizzardScriptAPI.md` §3): 11.0 leaves `tostring`/`error`/`loadstring`
hookable and includes secure-family names that are not base functions. We
mirror the 11.0 list verbatim with a name blacklist in
`Script_HookSecureFunc` that fires `lua_error` with
`"hooksecurefunc: function is unhookable"`
when the two-arg form targets one of: `getfenv`, `getmetatable`,
`hooksecurefunc`, `ipairs`, `issecurevalue`, `issecurevariable`, `next`,
`pairs`, `pcall`, `pcallwithenv`, `rawget`, `rawset`, `scrub`,
@@ -2012,8 +1945,8 @@ current item/spell/unit. Approach:
4. Each match reveals the offset for that state field.
Once located, `GetItem()`, `GetSpell()`, `GetUnit()` are trivial
deref+push. Implementation roughly the same as `OffhandHasWeapon`
or `IsEquippedItem` patterns.
deref+push. Implementation roughly the same as the `IsEquippedItem`
pattern.
### Risks
@@ -3615,3 +3548,590 @@ vs. any hidden fixed-30 assumption elsewhere; and that the Lua-created
lines inherit height/spacing identical to the template's 1..30 so the
tooltip grows seamlessly. Both are observable on the first >30-line
hover.
## 98. `UnitThreatSituation` / `UnitDetailedThreatSituation` / `GetThreatStatusColor` — NOT FEASIBLE in a client DLL
Modern (WotLK+) exposes three threat APIs:
[`UnitThreatSituation`](https://warcraft.wiki.gg/wiki/API_UnitThreatSituation)
(unit → 0..3 aggro status),
[`UnitDetailedThreatSituation`](https://warcraft.wiki.gg/wiki/API_UnitDetailedThreatSituation)
(isTanking, status, threatPct, rawThreatPct, threatValue), and
[`GetThreatStatusColor`](https://warcraft.wiki.gg/wiki/API_GetThreatStatusColor)
(status → RGB). None of them can be backed by ClassicAPI, because
**the underlying data does not exist on the 1.12 client** — not in a
form a DLL can read, and not by any amount of RE.
### Threat is 100% server-authoritative in vanilla; no threat opcode exists
Vanilla 1.12's threat lives entirely inside the server's
`ThreatManager` (per-creature `ThreatList` of `HostileReference`s —
see Turtle's
[`src/game/Threat/ThreatManager.cpp`](C:\Git\turtle-wow\Dumps\Source%20Code\16%20-%20Development_server\patch_1172\src\game\Threat\ThreatManager.cpp)).
The 3.3.5 client can show a threat meter because WotLK added
`SMSG_THREAT_UPDATE` / `SMSG_HIGHEST_THREAT_UPDATE` (and the client
keeps a per-unit threat table those packets feed). **1.12 has no such
opcode** — the protocol never transmits per-unit threat values, so
there is nothing in client memory to read. This is the same class of
limitation as `C_QuestLog.IsQuestFlaggedCompleted` (TODO #1): the
client simply isn't told. Unlike cast timing (TODO #91, recoverable
from `SMSG_SPELL_START`) or aura casters (recoverable from
`SMSG_SPELL_GO`), there is **no incidental packet** that leaks threat
either — the server computes tanking/aggro decisions internally and
broadcasts none of the numbers.
### How Turtle actually does it — a *server-side* addon-channel protocol
TWThreat (`C:\WoW\Octo\Interface\Addons\TWThreat`) is not reading
client memory; it round-trips through a **custom server patch**:
1. Client → server: the addon `SendAddonMessage("TWT_UDTSv4"[.._TM],
"limit=NN", "PARTY"/"RAID")` — a normal `CMSG_MESSAGECHAT` addon
message (`TWThreat.lua:1207` `TWT.UnitDetailedThreatSituation`).
2. Server intercepts the prefix in
[`ChatHandler.cpp:1051`](turtle-wow\Dumps\Source%20Code\16%20-%20Development_server\patch_1172\src\game\Handlers\ChatHandler.cpp)
(`strstr(msg, "TWT_UDTSv4")`), validates
`GetSelectedCreature()->CanHaveThreatList()`, and calls
`ThreatManager::UnitDetailedThreatSituation(creature, player, limit,
tankMode)`.
3. That serializer (`ThreatManager.cpp:441`) walks the real
`getThreatList()` and builds a `TWTv4=name:pct:threat;…` string,
then `SendAddonMessage`s it back.
4. Client parses it in `CHAT_MSG_ADDON` → `TWT.handleThreatPacket`
(`TWThreat.lua:790`).
Every threat number the meter shows originated on the server and was
put on the wire by a server-side code change ClassicAPI has no
counterpart to. A client DLL cannot manufacture data the server never
sends.
### Even where a server *does* expose it, the transport is async
The Turtle path is a request/response over the addon chat channel —
fundamentally asynchronous (poll on `OnUpdate`, handle the reply on a
later frame). It cannot back a **synchronous** `UnitThreatSituation()`
that returns a value in the same call, which is exactly why TWThreat is
structured around events and a cached `TWT.threats` table rather than a
blocking query. A ClassicAPI shim would at best have to fake a
synchronous return from a stale cache, and the cache only exists if a
Turtle-style server is feeding it — i.e. the shim would add nothing the
addon isn't already doing in Lua.
### `GetThreatStatusColor` is the only client-pure piece — and it's trivial Lua
`GetThreatStatusColor(status)` is just a fixed 0..3 → RGB map (grey /
yellow / orange / red); no engine data involved. But it's meaningless
without a real `status` to feed it, and it's a two-line Lua table
lookup — no reason to spend a DLL global on it. If we ever ship a
threat polyfill it belongs beside the (Lua, server-dependent) status
source, not in the DLL.
**Verdict:** skip all three. The data is server-only with no vanilla
opcode, the only working implementation (Turtle) is a server patch plus
an async addon-channel protocol that lives correctly in Lua, and the
one client-pure function is a trivial color table. Nothing here is a
client-DLL problem.
### If we synthesized it anyway
"Can't read it" and "can't estimate it" are separate claims. We can't
read threat (above); *estimating* it is possible, but it splits into two
tiers, and neither one is a DLL feature.
**Tier 1 — client-only proxy from the mob's target (small, honest,
nearly useless).** The one threat-correlated fact vanilla *does* sync to
the client is the creature's current target (`UNIT_FIELD_TARGET` in the
descriptor — the same field `"<mob>target"` / `targettarget` reads). A
mob attacks its highest-threat valid target, so `mobTarget == unit` ≈
"unit is tanking". That yields:
- `UnitThreatSituation(unit, mob)` → `3` when the mob targets `unit`,
else `nil`. It **cannot** produce `1` ("higher than tank, about to
pull") or distinguish `2` from `3` — those are numeric comparisons and
we have no numbers.
- `UnitDetailedThreatSituation` → `isTanking` only; `status` degenerate,
`threatpct` / `rawthreatpct` / `threatvalue` all unavailable.
- Laggy: it changes only when the mob switches target (a descriptor
update), so it *trails* real threat and gives zero predictive warning
— the entire reason a threat meter exists.
This needs no DLL: `UnitIsUnit("<mob>target", unit)` already does it in
pure Lua. Shipping it under the real API names would be actively
misleading (callers expect the 0–3 gradient plus percentages), so it's
not worth it even as a stub.
**Tier 2 — a real threat model (accurate-ish, huge, cooperative, ~95%
Lua).** This is what KTM / KLHThreatMeter / vanilla-Omen actually do, and
the only synthesis that fills the percentage/prediction dimensions the
API is *for*:
1. **Model your own threat.** Parse your outgoing combat events and
convert them to threat via a per-spell coefficient database (damage ≈
1 threat per point, healing ≈ 0.5/HP applied to *every* mob in combat,
flat-threat abilities like Sunder Armor / Demo Shout, per-spell
bonus/penalty coefficients), then apply your active multipliers —
stance/form (Defensive 1.3×, Berserker 0.8×, Bear/Cat), Righteous Fury
(+Holy threat), Blessing of Salvation (0.7×), threat-reduction
trinkets — and handle the sets/wipes: taunt (sets you to current top),
Feign Death, Vanish, Fade, Cower.
2. **Broadcast** your per-mob estimate over `SendAddonMessage` and
**aggregate** everyone else's broadcasts into a per-mob table.
3. Derive `isTanking` / `status` / the percentages by comparing each
member to the current tank against the **110% melee / 130% ranged**
pull threshold — the exact constants both Turtle's server serializer
(`ThreatManager.cpp:494`, `threatValue*100 / (tankThreat * (isMelee ?
1.1 : 1.3))`) and TWThreat's client fallback (`TWThreat.lua:932`)
use. Worth stealing verbatim so a synthesized `threatpct` lines up
with what real-threat clients show.
Why it isn't ours to build:
- The coefficient DB is **game-knowledge, not in the binary** — you
cannot RE it out of the client; it's the classic hand-maintained
Threat-1.0/KTM data. The parsing, broadcast, and aggregation are all
Lua. The talent/aura/stance *inputs* are already exposed by existing
ClassicAPI functions (`GetTalentInfo`, the aura APIs, `IsPlayerSpell`,
the spell-mod reads). **None of it is a client-DLL problem.**
- **Cooperative-only.** You can precisely model only members running the
same addon and broadcasting; a non-participating tank is invisible (the
original KTM caveat). The intuitive objection — "I can see everyone's
damage in the combat log, why can't I model them from one client?" —
fails for three compounding reasons, none liftable by the DLL:
1. **You don't actually see everyone's events.** Vanilla's combat log
is visibility/range-gated — the server only broadcasts combat events
for units near you, not the whole raid. A stacked 5-man logs most of
it (so a single-observer model degrades *gracefully* in dungeons); a
spread 40-man leaves you blind to the ranged camp, the back-line
healers, anyone outside your bubble. The DLL can't recover these —
the server never sends the packets, so there's nothing to hook.
2. **Threat ≠ damage, and the missing factor is hidden.** Threat is
`damage × stance × talents × buffs`, not 1:1. The talent factor
(Defiance, Subtlety, Feral Instinct, Shadow Affinity, Frost
Channeling — the passive threat-mod talents) is **unreadable for
other players in vanilla**; there's no inspect path to it. Stance /
Blessing of Salvation / Fade are at least observable auras when the
unit is in range, but talents are pure hidden state, so an observer
can't derive a stranger's coefficient from their damage.
3. **Much threat has no attributable log line.** In-combat healing
generates threat on *every* mob the healer is engaged with (not the
mob the heal touched); buffs / HoTs / PW:Fortitude, flat-threat
abilities, and pet threat either don't appear in the log or can't be
pinned to the right mob from a single line.
Broadcasting sidesteps all three because each client computes threat
from *private, authoritative* knowledge — its own exact casts, its own
talents, its own active stance/buffs — then shares the finished number.
The Tier-1 mob-target read is worth keeping here *only* as a cross-check
— it reveals who actually holds aggro regardless of who's broadcasting.
- **It's an estimate that drifts.** Addon threat models desync from the
server's true numbers (rounding, unmodeled effects, out-of-range or
missed events). That drift is precisely why Blizzard later added
`SMSG_THREAT_UPDATE` and why Turtle chose a server serializer over
blessing an addon guess.
**The only DLL-shaped angle — and it's an *input*, not threat.** The one
place a DLL beats Lua is the feed: vanilla's combat log is localized text
keyed by unit *name* (ambiguous with duplicate names, breaks per-locale).
Hooking the damage/heal packet handlers (`SMSG_SPELLNONMELEEDAMAGELOG`,
`SMSG_ATTACKERSTATEUPDATE`, `SMSG_PERIODICAURALOG`) to emit precise,
GUID-keyed, unlocalized damage/heal events would make any Lua threat
model far more robust. But (a) that's a **separate feature** — a
`COMBAT_LOG_EVENT`-style feed, useful well beyond threat — that should be
filed on its own merits; (b) it still only *feeds* the Lua model — threat
stays an estimate, computed cooperatively in Lua; and (c) on the actual
target environment SuperWoW already exposes GUID-keyed combat info +
`UNIT_CASTEVENT`, so even this niche is largely pre-filled.
**Bottom line on synthesis:** Tier 1 is a Lua one-liner too degenerate to
wear the API's name; Tier 2 is a full KTM/Omen reimplementation that is
almost entirely Lua data + logic, cooperative-only, and inherently an
estimate. Anyone who wants vanilla threat should run an existing threat
addon. ClassicAPI's only worthwhile contribution in this space is an
unrelated precise-combat-log event feed — filed as its own thing, not as
"threat".
## 99. `C_AddOns.GetAddOnLocalTable(name)` — gate on loaded + opt-in TOC flag — DONE
Shipped gated (branch `feat/lua-syntax-transpile`,
[src/addons/LocalTable.cpp](src/addons/LocalTable.cpp)). Returns the addon's
private namespace table **only** when BOTH hold, else `nil`:
1. the addon `name` is **loaded** (`FUN_ADDON_IS_LOADED`, by-name), and
2. its `.toc` declares `## AllowAddOnTableAccess: <nonzero>` (scanned via
`FUN_FILE_READ` on `Interface\AddOns\<name>\<name>.toc`, read as a TOC
boolean flag; approach (a) from the notes below — no parser hook).
The two paths stay separate, as required:
- **Internal**: each addon file is called with `(name, ns)` as real
arguments, as 4.3.4 does (`Script_RunAddonFile` in
`luasyntax/Transpile.cpp`) — **ungated**, an addon always gets its own
namespace. (Replaced the `__addonns` global preamble.)
- **Public** `C_AddOns.GetAddOnLocalTable` carries the gate, in
`addons/LocalTable.cpp`.
Both resolve to the SAME table per addon via `LuaSyntax::PushAddonNamespace`
(the one owner of the registry-backed name→table map, exposed by
[src/luasyntax/AddonNamespace.h](src/luasyntax/AddonNamespace.h)) — so an addon
reads back exactly what it (or its files' `...`) stored.
Directive spelling + function name verified present in the 1.15.8 Classic Era
binary (`AllowAddOnTableAccess:` TOC key, `GetAddOnLocalTable`).
Deliberate scope choices (revisit only if an addon needs otherwise):
- **Name (string) input only.** A numeric index returns `nil` — cross-addon
table access is by name, and the map is name-keyed. Every other `C_AddOns.*`
wrapper accepts name-or-index; this one does not.
- **`nil` on denial, not a Lua error.** Matches the project's modern-API
convention (nil over `lua_error`). Retail may raise instead; switch the
denial branches to `Game::Lua::Error` if strict parity is wanted.
- **No per-name cache** on the TOC scan — GetAddOnLocalTable is not a hot path.
Not shipped by default: no addon opts in yet. The embedded `!!!ClassicAPI`
addon could add `## AllowAddOnTableAccess: 1` to its `.toc` to expose its own
namespace as a worked example, but that's a product/security decision left to
the maintainer.
## 100. Self-documenting API + `/classicapi` browser — SHIPPED (first slice)
`docs/API.md` is 18.7k lines and its anchors are signature slugs, so a
signature edit breaks the 281 internal + 88 README links into it. Blizzard
solved the same problem by shipping the API as DATA
(`Blizzard_APIDocumentationGenerated`: one table per system with typed
`Functions` / `Events` / `Tables`) plus a browser addon
(`Blizzard_APIDocumentation`, the `/api` command). warcraft.wiki.gg's
Arguments/Returns blocks are those same tables rendered by a bot — so one set
of descriptors feeds the in-game browser, a page generator, and a drift check.
**Shipped in this round**
- `namespace Game::Doc` in [src/Game.h](src/Game.h) — `Field` +
`Req`/`Opt`/`Vararg`, `FieldList`, `Function`, `Method`, `Structure`,
`Event`. Constant-initialized `const` objects; no heap, no dynamic init.
- A trailing descriptor argument on all six `Game::Lua::Register*`, and on
`Event::Custom::AutoReserve`. Zero changes inside any `Script_*`.
- [src/api/Documentation.cpp](src/api/Documentation.cpp) — records every
registration on the first pass of each Lua state, derives systems, and
exports `C_APIDocumentation.GetSystems()` / `GetSystem(name)` lazily in
Blizzard's exact table shape, plus `_classicapi_UndocumentedAPI()`.
- `src/embed/AddOns/!!!ClassicAPI/APIDocumentation/` — the 8-file port of
`Blizzard_APIDocumentation`, driven by `/classicapi` (short `/capi`).
Named for what it documents: the browser holds only ClassicAPI's own
surface, so `/api` would have over-promised.
- `Util/LinkUtil.lua` — the `SetItemRef` → `LinkUtil.ProcessLink` dispatch,
wiring up a `RegisterLinkHandler` registry that had been dead code. Any
future link type now registers a handler instead of stacking another
`SetItemRef` override. Also fixed `assertsafe` being undefined there.
- Documented: the whole `C_Spell` / `C_SpellBook` surface, the spell globals
(`SpellGlobals`), the two SpellBook enums, the 13 `UNIT_SPELLCAST_*`
events, `GameTooltipAPI` (frame-method example), and `C_Glue` (glue and
mixed-environment example).
**The remaining sweep.** `_classicapi_UndocumentedAPI()` is the worklist —
~700 registrations across ~46 namespaces. Do it a namespace at a time; the
descriptor goes beside the registration and must be written against the
`Script_*` BODY, not against `docs/API.md` (which is already stale in
places — `IsHarmfulSpell` / `IsHelpfulSpell` describe an `AttributesEx` bit
read that the code does not do; it walks the effects' implicit targets).
`tools/New-ApiDocSkeletons.ps1` emits paste-ready skeletons from the 207
single-line `Usage:` strings + the API.md headings, with `// TODO` on every
guess — a starting point to verify, never to paste blind.
When the sweep finishes, delete the `= nullptr` / `= 0` defaults from the six
registrar parameters: a registration without a descriptor then fails to
compile, which is the whole point of putting the descriptor at the call site.
**Then, not before:** an `ExportAPIDocumentation` console command (glue-
registered like `ExportInterfaceFiles`, writing one Blizzard-format `.lua`
per system plus `Undocumented.txt`), a CI diff of the committed copies to
catch descriptor drift, and a Markdown/wiki generator to replace the
hand-maintained `docs/API.md` — the reason the descriptors exist at all.
## 101. `Frame:SetOnUpdateMode(mode)` + `Enum.OnUpdateMode` — medium
```
Frame:SetOnUpdateMode(onUpdateMode) -- Enum.OnUpdateMode
0 Disabled no OnUpdate, visible or not
1 RunWhenVisible the vanilla behaviour (default)
2 RunWhenVisibleOnce run once while visible; resets to Disabled BEFORE running
3 RunOnce run once regardless of visibility; resets to Disabled BEFORE running
4 RunAlways run regardless of visibility
```
"Resets before running" is load-bearing: the handler re-arms by calling
`SetOnUpdateMode` again from inside itself.
**Engine (verified 2026-09-15).** The per-frame dispatcher is `FUN_0076B2C0`,
`__thiscall(frame, float elapsed)` at vtable `+0x38`, present in every frame
vtable with subclass overrides chaining into it (same shape as the click
vmethod `FUN_00779540`):
```c
if (frame[0x128] != 0) // the OnUpdate slot
FUN_007026F0(frame, frame + 0x128, "%f", elapsed); // fmt @0x00835160
```
The walk is `FUN_00765650`: nine strata buckets of an intrusive list
(`frame+0x310` = next, saved into the bucket before each call so a handler may
unlink itself), calling `vtable+0x38` per node — with **no visibility check in
the loop and none in the dispatcher**. Visibility is therefore *list
membership*, not a test, and that list is the per-strata render list, so a
hidden frame is simply absent. Contention: a literal scan of every DLL in
`dll\` + `dll_local\` finds no reference to `FUN_0076B2C0` or `FUN_00765650`.
**Design.** Modes 0/1/2 need only a co-hook on `FUN_0076B2C0` — mode 0 returns
without calling the original, mode 2 sets Disabled then calls it, mode 1 is the
engine unchanged. Guard the detour on an empty mode map so non-users pay a
compare.
Modes 3/4 cannot come from that hook: the frame is not in the walk's list while
hidden, and forcing membership would put it in the RENDER list (it would try to
draw). Drive them from `Tick::WorldTick` instead — an already-owned hook, so no
second MinHook — calling the engine's own `FUN_0076B2C0(frame, elapsed)` so the
handler sees exactly the fire it normally would, with a per-tick mark set by the
hook so a *visible* `RunAlways` frame is not dispatched twice.
**Open question before writing it:** the `elapsed` for the self-driven modes.
The walk receives it from its caller; cleanest is to capture it in the hook (one
value per pass, shared by every frame) and reuse it, falling back to a
`Time::Clock` delta when nothing visible ran that frame. Needs checking whether
`Tick::WorldTick` (`FUN_0066FD50`, the world subsystem) runs before or after the
UI pass, which decides whether the captured value is this frame's or last
frame's.
**Cost:** one new MinHook (uncontended, guarded to ~zero when unused), one
WorldTick subscriber, a frame-keyed mode map, `Enum.OnUpdateMode`, and
`SetOnUpdateMode` / `GetOnUpdateMode`.
**Value, honestly.** `RunAlways` is the only genuinely new capability — a hidden
frame currently cannot run OnUpdate at all, which is why addons keep a
permanently-shown dummy frame for their tickers. `Disabled` duplicates
`SetScript("OnUpdate", nil)` and `RunOnce` overlaps `C_Timer.After(0, …)`, so
the rest is API parity. Worth it for the one capability plus a clean enum, not
as a performance feature.
## 102. Texture tiling: `SetHorizTile` / `SetVertTile` (+ `SetNonBlocking`) — medium
The only texture methods 4.3.4 has that 1.12 + ClassicAPI lack
(`wowdecomp15595/Engine/Source/Frame/CSimpleTexture_Scripts.cpp`): six
setter/getter pairs on `m_textureFlags`. Getters answer 1 or nil.
| Methods | 4.3.4 flag | Effect |
|---|---|---|
| `SetHorizTile` / `GetHorizTile` | `0x4` | repeat on U |
| `SetVertTile` / `GetVertTile` | `0x8` | repeat on V |
| `SetNonBlocking` / `GetNonBlocking` | `0x1` | skip drawing an unloaded image this frame instead of force-loading it |
**How 4.3.4 tiles.** `CRenderBatch::QueueTexture` (`CRenderBatch.cpp:164`):
while the dirty flag `0x2` is set, every non-zero U texcoord becomes
`rectWidthInPixels / gxTex->m_width` (V likewise with height), using
`DDCToNDCWidth(aspect × 1024 × (right − left)) / m_layoutScale` from the drawn
corners. A layout change (`CSimpleRender.cpp:2391`) sets `0x2` again when either
tile flag is on. Repeat only shows if the image was loaded with wrap.
**Wrap on 1.12.** `CSimpleTexture::SetTexture` `0x770200` already takes
`(name, wrap, filter, shader)` (benilla-re `ui/texture#settexture`); the Lua
`SetTexture` always passes wrap 0. 4.3.4's Lua `SetTexture(file, tile)` reads
arg 3 as wrap for both axes — add that. To verify: vanilla has one wrap flag,
4.3.4 has `wrapU`/`wrapV`; check whether `CGxTexFlags` `0x58A980` can wrap one
axis alone.
**Where to hook.** The rescale belongs where the drawn corners are built — the
texture `OnFrameSizeChanged` co-hook `0x770670` the animation system already
owns (`src/animation/Region.cpp`).
**XML.** `<Texture horizTile= vertTile= nonBlocking=>`; 4.3.4's loader also
turns wrap on when `<TexCoords>` leave 0..1 and errors
`Texture %s: Invalid TexCoords value (horizTile is on)` (`CSimpleRender.cpp:3024`).
**NonBlocking.** Only meaningful if 1.12 has a lazy texture-load path (4.3.4:
`TextureForceLoadForDiskOnly` vs `NotifyDelayedLoad`). Not checked — if 1.12
always loads synchronously it is a stored flag with no effect.
## ~~103. FontString `SetWordWrap` / `CanWordWrap` / `GetFieldSize`~~ — DONE
The only FontString methods 4.3.4 has that 1.12 + ClassicAPI lacked
(`CSimpleFontString_Scripts.cpp`). Code: `src/fontstring/WordWrap.cpp`,
`GetFieldSize` in `src/fontstring/Metrics.cpp`.
- **SetWordWrap / CanWordWrap.** 4.3.4 style bit `0x40` (set = no wrap). The
setter is 1.12's own `SetNonSpaceWrap` (`0x79E9F0`, identical body on bit
`0x1000`) with `0x40` inverted. `TextBlockCreate` `0x44D420` already maps
`0x40` to text flag `0x2` exactly as 4.3.4's `ConvertStringFlags`, and 1.12's
layout `0x5CDC20` / line count `0x5C2070` stop after one line on it.
Verified in-game: one line, `...` at the width (the fit `0x771EC0`), lines
after `\n` dropped, no width = the whole line. A change must lay the string
out again (`FontString::Layout::Invalidate`, as `SetText`), not only rebuild
it: a text-sized string kept its two-line height and the fit cut at a whole
word with no `...`.
- **GetFieldSize.** 4.3.4 returns a constant 8191. 1.12's truth: a string with a
fixed text size `+0xE8` (XML `bytes="n"`) keeps `n − 1` bytes (`SetText`'s
`SStrCopy(text, src, n)`, `0x771E0F`); without one the buffer grows to any
length, so it returns infinity.
## ~~104. XML `<KeyValues>`~~ — DONE
Shipped in a2e3eed (`mixin=` and `method=` followed in 2cab0dc). Code:
`src/xml/KeyValues.cpp`; the texture / font string hooks in
`src/xml/ParentKey.cpp` call it directly (no `RegionLoad` fan-out), and
`src/animation/Xml.cpp` reads it for groups and animations. Notes below
are the original plan.
Not in 4.3.4 (no decomp); the contract comes from retail's `UI.xsd`
(`_classic_era_/BlizzardInterfaceCode/.../Blizzard_SharedXML/UI.xsd`) and
`XMLUtilDocumentation.lua`. Blizzard's classic-era UI uses it in 356 files.
- `<KeyValues><KeyValue key= value= type= keyType=/></KeyValues>`; `type` and
`keyType` are `nil` / `boolean` / `number` / `string` (default) / `global`
(`_G[value]`). Sets `object[key] = value` on the Lua wrapper.
- A LayoutField: frames, textures, font strings. Also a child of
`AnimationGroup` and `Animation`.
- `C_XMLUtil.GetTemplateInfo(name).keyValues` is a list of
`{key, keyType, type, value}` (all strings); ours always returns `{}`
(`src/xml/Templates.cpp`).
**Ordering.** `NineSlicePanelMixin:OnLoad` reads `self:GetParent().layoutType`
— a parent's KeyValue must be set before its child frames load. 1.12's frame
load (benilla-re `ui/frames#loading-from-xml`): `0x769820` loads the inherited
node first, then attributes, `Layers`, `Scripts`; `0x76A060` then loads the
child `<Frames>` and the load ends (OnLoad). So the existing
`Xml::FrameLoad::AutoSubscribe` (after `0x769820`, as `<Attributes>` uses) is
the right point: template values first, the node's own win, before children
and OnLoad.
**Plan.**
1. Textures / font strings: `ParentKey.cpp` owns the `0x76FE20` / `0x770F40`
loader hooks and calls `Animation::Xml::LoadAnimations` from them by hand.
Turn them into a shared `Xml::RegionLoad::AutoSubscribe` fan-out (like
`FrameLoad`) and subscribe ParentKey, Animations and KeyValues.
2. `Xml::PushTypedValue(L, type, value)` shared with `<Attributes>`
(`Frame::Attributes::LoadXmlAttributes`, engine `FUN_XML_ATTR_TO_BOOL` /
`FUN_SSTR_TO_FLOAT`), plus `global`.
3. `src/xml/KeyValues.cpp` for frames + regions; the animation loader
(`src/animation/Xml.cpp`) reads it for groups and animations.
4. Fill `GetTemplateInfo`'s `keyValues` from the template node.
**Unverifiable without a retail binary** — follow `<Attributes>` and say so in
the code: a `boolean` value other than true/false, a `number` that fails to
parse, and whether `GetTemplateInfo` includes inherited templates' entries
(plan: the node's own only).
## 105. Button methods — small to medium
Button methods later clients have that 1.12 + ClassicAPI lack. 4.3.4 adds three
over 1.12 (`CSimpleButton_Scripts.cpp`); retail's `SimpleButtonAPIDocumentation`
(`_classic_era_` install) lists the rest. `Get/SetNormalFontObject` are done
(`src/frame/Modern.cpp`).
**From 4.3.4 (decomp available).**
- **DONE** (`src/frame/MotionScriptsWhileDisabled.cpp`, verified in-game
2026-10-19). `SetMotionScriptsWhileDisabled(enabled)` / `GetMotionScriptsWhileDisabled()`
— the one real new capability: tooltips on disabled buttons. 4.3.4
`CSimpleButton::OnLayerCursorEnter/Exit` (`CSimpleButton.cpp:827/844`): an
enabled button runs the frame's enter/leave and the label refresh; a disabled
one does nothing unless the flag is set, then shows `m_hoverFrame` and runs
ONLY the OnEnter/OnLeave script (no highlight, no label refresh). 1.12 is
4.3.4 without the flag: `0x779490` (slot 19) / `0x7794E0` (slot 20) skip the
frame's enter/leave (`0x76B6A0` / `0x76B6F0`, scripts + highlight) and the
label refresh `0x779810` for state 0 (benilla-re `ui/button#entering-and-leaving`).
Needs: a per-button flag (side map, reset on reload), co-hooks on the two
slots, a way to run just the script (find the script runner inside
`0x76B6A0`), what 1.12 has for `m_hoverFrame`, and the XML attribute
`motionScriptsWhileDisabled` (4.3.4 `m_buttonFlags` bits 0x4 set / 0x8 value,
`CSimpleButton.cpp:1058`). Default false.
- **DONE** (`src/frame/FormattedText.cpp`, shared with the font string's;
verified in-game 2026-10-19).
`button:SetFormattedText(fmt, ...)` — 4.3.4 formats into a 4096-byte buffer
and calls the button's `SetText`. We have it on font strings only
(`src/fontstring/Metrics.cpp`, engine `str_format` under pcall); register the
same on the Button registry with the button's own SetText.
**From later clients (contract from retail docs only — no decomp).**
- **DONE** (`src/frame/SetEnabled.cpp`). `SetEnabled(enabled)` — `Enable()` /
`Disable()` by a bool, through the button's Enable vmethod as they do.
- `SetNormalAtlas` / `SetPushedAtlas` / `SetDisabledAtlas` /
`SetHighlightAtlas(atlas[, blendMode])` — the state texture made or reused
through `SetNormalTexture` etc., then `Texture::Atlas`'s `SetAtlas`.
- `ClearNormalTexture` / `ClearPushedTexture` / `ClearDisabledTexture` /
`ClearHighlightTexture` — remove the state texture. Check what 1.12's
`SetNormalTexture(nil)` does first (`CSimpleButton::SetStateTexture`
`0x778FD0` deletes the old one).
- **DONE** (`src/frame/MouseRegistration.cpp`). `RegisterForMouse(buttons...)`
— which mouse buttons fire OnMouseDown/Up. 1.12 filters nothing: the base
frame pair 0x76BF70 / 0x76C040 fire both for any button through the runner,
where `Frame::ClickEvents`' gate now refuses unregistered ones.
## 106. Script-object API sweep — remaining methods, globals and scripts
A name-level diff, 2026-10-19: every 4.3.4 method table
(`wowdecomp15595/Engine/Source/Frame/*_Scripts.cpp`) and retail's
`Blizzard_APIDocumentationGenerated/Simple*APIDocumentation.lua` (`_classic_era_`
install) against 1.12 (`docs/BlizzardScriptAPI.md`) and what `src/` registers.
Texture (#102), FontString (#103 done) and Button (#105) have their own items.
Each entry still needs the usual check of how the engine does it before building.
### From 4.3.4 (decomp available)
- **DONE** (`src/slider/Enable.cpp`). **Slider** `Enable` / `Disable` / `IsEnabled`: frame flag `0x400`, read by the
thumb-drag path (`CSimpleSlider.cpp:317`); `Disable` runs OnDisable unless
loading (we have OnEnable/OnDisable in `src/frame/EnableScripts.cpp`).
- **DONE** (`src/frame/MinMaxChanged.cpp`). **OnMinMaxChanged** (Slider, StatusBar): `SetMinMaxValues` runs it with
`(min, max)` when the range changes (`CSimpleStatusBar.cpp:39/141`). 1.12 has
no such script.
- **DONE** (`src/statusbar/Fill.cpp`, `src/statusbar/BarTexture.cpp`; XML
`reverseFill` / `rotatesTexture` / `fillStyle` attributes not backported).
**StatusBar** `SetReverseFill` / `GetReverseFill`, `SetRotatesTexture` /
`GetRotatesTexture` (`CSimpleStatusBar.cpp:135`, the vertical texcoord path
at `:285`). Retail adds `SetFillStyle` (STANDARD / CENTER / REVERSE),
`SetColorFill`, `SetStatusBarDesaturated` / `Desaturation`.
- **DONE** (`src/scrollingmessageframe/`, retail's shapes).
**ScrollingMessageFrame** `GetMessageInfo`, `SetScrollOffset` (1.12's
`SetScrollFromBottom`, 0x00793070, under its later name, clamped as
retail), `GetScrollOffset`, `GetMaxScrollRange`, `ScrollByAmount`,
`AddOnDisplayRefreshedCallback`, `SetInsertMode` / `GetInsertMode` (TOP
through a redirect of the layout's one line-anchor call, 0x00788975),
`BackFillMessage` (writes 4.3.4's addToTop slot of the ring, the free one
before the oldest; a full frame drops it, as retail's CircularBuffer
`PushBack` does — 4.3.4 overwrites the oldest there).
- **DONE** (`src/scrollingmessageframe/MessageInfo.cpp`).
**ScrollingMessageFrame** `RemoveMessagesByPredicate` (retail's shape; it
covers 4.3.4's `RemoveMessagesByAccessID` / `RemoveMessagesByExtraData`,
whose int fields our retail-shaped records do not have). The compaction
is 4.3.4's `RemoveLines` loop over 1.12's ring, then the engine's own
layout (0x00788750) at the kept scroll offset and re-arm (0x00788B80),
or Clear (0x007882B0) when nothing is kept.
- **DONE** (`src/editbox/Focus.cpp`, `src/animation/Framerate.cpp`).
**Globals** (`SimpleFrameScript_Scripts.cpp`): `GetCurrentKeyBoardFocus()`
(the focused edit box's wrapper, or nil); `SetMaxAnimFramerate(fps)` /
`GetMaxAnimFramerate()` — 4.3.4's `CSimpleAnim::s_frameInterval`, the 1/30 s
throttle our animation port already has.
- Not worth it: Frame `EnableJoystick` / `IsJoystickEnabled`; the stereo-depth
set `SetDepth` / `GetDepth` / `GetEffectiveDepth` / `IgnoreDepth` /
`IsIgnoringDepth`; `GetText(token[, gender[, ordinal]])` — gendered
global-string lookup, little use on 1.12.
### From later clients (retail docs only — contract, no decomp)
Likely worth it (small, ported code uses them):
- Object: `GetParentKey` / `SetParentKey` / `ClearParentKey`, `GetDebugName`.
- Region: `SetIgnoreParentAlpha` / `IsIgnoringParentAlpha` (4.3.4 has it
internally: its texture XML load calls `SetIgnoreParentAlpha` from
`m_regionFlags 0x10/0x20`, `CSimpleRender.cpp`),
`SetIgnoreParentScale` / `IsIgnoringParentScale`.
- ScriptRegion: `GetScaledRect`, `IsRectValid`, `Intersects`.
- Frame: `GetResizeBounds` (we have `SetResizeBounds`), `SetFixedFrameStrata` /
`SetFixedFrameLevel` / `HasFixed*`, `GetHighestFrameLevel` /
`GetRaisedFrameLevel`, `SetUsingParentLevel`, `ClearAttributes`,
`IsObjectLoaded`, `RotateTextures` (on `Texture::Transform`), `AbortDrag`.
- Slider: `SetObeyStepOnDrag`, `SetStepsPerPage`, `IsDraggingThumb`,
`SetEnabled` (also EditBox `SetEnabled`).
- FontString / Font: `SetTextScale` /
`GetTextScale`, `ClearText`, `SetTextToFit`,
`GetUnboundedStringWidthForText`, `FindCharacterIndexAtCoordinate`.
- Texture: `GetTextureFilePath`, `ClearVertexOffsets`.
- SimpleHTML `GetContentHeight`; ColorSelect alpha (`SetColorAlpha` + its
textures).
Larger, decide separately: mouse-motion / click split and propagation
(`SetMouseMotionEnabled`, `SetMouseClickEnabled`, `SetPropagateMouseClicks`,
`SetPassThroughButtons`); `SetClipsChildren` (scissoring); `CreateLine` (the
Line region type); texture slicing (`SetTextureSliceMargins` / `Mode`); Model
camera / transform / alpha (~40 methods); `RegisterEventCallback`; EditBox
secure-text and byte-limit options; MessageFrame fade power and message IDs.
-115
View File
@@ -1,115 +0,0 @@
# embed_addon.cmake — bundle an addon directory into a generated C++ header.
#
# Invoked from CMakeLists.txt via `cmake -P` as a custom command. Reads every
# file under SRC_DIR recursively and emits OUT_HEADER containing:
#
# namespace Addons::Embedded {
# struct File {
# const char *path;
# const unsigned char *data;
# size_t size;
# };
# extern const File kFiles[];
# extern const size_t kFileCount;
# }
#
# Paths are normalized to lowercase backslash-form relative to
# `Interface\AddOns\` so they match what the engine's TOC parser
# constructs when it asks for the addon's files (see
# `s_Interface_AddOns__s__s_toc_00853840` in the binary). The
# manifest is hash-table-friendly for fast lookup but the lookup
# walks the array linearly — fine for 25 files.
#
# Usage:
# cmake -DSRC_DIR=... -DOUT_HEADER=... -DADDON_NAME=... -P embed_addon.cmake
if(NOT SRC_DIR)
message(FATAL_ERROR "embed_addon.cmake: SRC_DIR required")
endif()
if(NOT OUT_HEADER)
message(FATAL_ERROR "embed_addon.cmake: OUT_HEADER required")
endif()
if(NOT ADDON_NAME)
message(FATAL_ERROR "embed_addon.cmake: ADDON_NAME required")
endif()
file(GLOB_RECURSE INPUT_FILES RELATIVE "${SRC_DIR}" "${SRC_DIR}/*")
list(SORT INPUT_FILES) # deterministic codegen
set(BODY "")
set(MANIFEST "")
set(INDEX 0)
foreach(REL_PATH ${INPUT_FILES})
set(ABS_PATH "${SRC_DIR}/${REL_PATH}")
file(READ "${ABS_PATH}" CONTENT_HEX HEX)
string(LENGTH "${CONTENT_HEX}" HEX_LEN)
math(EXPR FILE_SIZE "${HEX_LEN} / 2")
# Convert hex string to comma-separated byte literals. 16 bytes per line
# keeps the generated header readable.
set(BYTES "")
set(COL 0)
set(POS 0)
while(POS LESS HEX_LEN)
string(SUBSTRING "${CONTENT_HEX}" ${POS} 2 BYTE)
if(COL EQUAL 0)
string(APPEND BYTES " ")
endif()
string(APPEND BYTES "0x${BYTE},")
math(EXPR POS "${POS} + 2")
math(EXPR COL "${COL} + 1")
if(COL EQUAL 16)
string(APPEND BYTES "\n")
set(COL 0)
else()
string(APPEND BYTES " ")
endif()
endwhile()
if(NOT COL EQUAL 0)
string(APPEND BYTES "\n")
endif()
# Normalize path to engine-style: `<AddonName>\Sub\Path.lua` with
# backslashes. Engine constructs full path as
# `Interface\AddOns\<AddonName>\<file>` — we strip the
# `Interface\AddOns\<AddonName>\` prefix at lookup time so storing
# just the relative form keeps the manifest small.
string(REPLACE "/" "\\\\" REL_PATH_BS "${REL_PATH}")
string(APPEND BODY "static const unsigned char kData_${INDEX}[] = {\n${BYTES}};\n\n")
string(APPEND MANIFEST " { \"${REL_PATH_BS}\", kData_${INDEX}, ${FILE_SIZE} },\n")
math(EXPR INDEX "${INDEX} + 1")
endforeach()
set(HEADER_CONTENT "// Auto-generated by embed_addon.cmake — do not edit.
// Source: ${SRC_DIR}
//
// Addon \"${ADDON_NAME}\" embedded as a fallback for users who don't have
// it installed on disk. See src/addons/Embedded.cpp for the file-read
// hook that surfaces these buffers to the engine.
#pragma once
#include <cstddef>
namespace Addons::Embedded {
namespace ${ADDON_NAME}Files {
${BODY}static const struct File {
const char *path;
const unsigned char *data;
size_t size;
} kFiles[] = {
${MANIFEST}};
static constexpr size_t kFileCount = sizeof(kFiles) / sizeof(kFiles[0]);
} // namespace ${ADDON_NAME}Files
} // namespace Addons::Embedded
")
file(WRITE "${OUT_HEADER}" "${HEADER_CONTENT}")
message(STATUS "embed_addon: wrote ${OUT_HEADER} (${INDEX} files)")
-62
View File
@@ -1,62 +0,0 @@
# embed_file.cmake — bundle a single file into a generated C++ header.
#
# Invoked from CMakeLists.txt via `cmake -P` as a custom command. Reads
# INPUT_FILE and emits OUT_HEADER containing a constexpr byte array
# named SYMBOL plus a `SYMBOL ## Size` size constant. Both live at file
# scope; the header is meant to be included exactly once.
#
# Usage:
# cmake -DINPUT_FILE=... -DOUT_HEADER=... -DSYMBOL=... -P embed_file.cmake
if(NOT INPUT_FILE)
message(FATAL_ERROR "embed_file.cmake: INPUT_FILE required")
endif()
if(NOT OUT_HEADER)
message(FATAL_ERROR "embed_file.cmake: OUT_HEADER required")
endif()
if(NOT SYMBOL)
message(FATAL_ERROR "embed_file.cmake: SYMBOL required")
endif()
file(READ "${INPUT_FILE}" CONTENT_HEX HEX)
string(LENGTH "${CONTENT_HEX}" HEX_LEN)
math(EXPR FILE_SIZE "${HEX_LEN} / 2")
# Convert hex string to comma-separated byte literals. 16 bytes per
# line keeps the generated header readable.
set(BYTES "")
set(COL 0)
set(POS 0)
while(POS LESS HEX_LEN)
string(SUBSTRING "${CONTENT_HEX}" ${POS} 2 BYTE)
if(COL EQUAL 0)
string(APPEND BYTES " ")
endif()
string(APPEND BYTES "0x${BYTE},")
math(EXPR POS "${POS} + 2")
math(EXPR COL "${COL} + 1")
if(COL EQUAL 16)
string(APPEND BYTES "\n")
set(COL 0)
else()
string(APPEND BYTES " ")
endif()
endwhile()
if(NOT COL EQUAL 0)
string(APPEND BYTES "\n")
endif()
set(HEADER_CONTENT "// Auto-generated by embed_file.cmake — do not edit.
// Source: ${INPUT_FILE}
#pragma once
#include <cstddef>
static constexpr unsigned char ${SYMBOL}[] = {
${BYTES}};
static constexpr size_t ${SYMBOL}Size = sizeof(${SYMBOL});
")
file(WRITE "${OUT_HEADER}" "${HEADER_CONTENT}")
message(STATUS "embed_file: wrote ${OUT_HEADER} (${FILE_SIZE} bytes)")
+209
View File
@@ -0,0 +1,209 @@
# embed_resources.cmake — embed the addons, the bindings XML and the
# built-in textures as Win32 RCDATA resources.
#
# Runs at configure time. It writes two files into OUT_DIR:
#
# embedded.rc one `<id> RCDATA "<path>"` line per pack; rc.exe
# reads each gzipped pack from disk.
# embedded_resources.h the IDs the DLL looks up at runtime through
# src/embed/Resource.h:
#
# namespace Embed::Ids { constexpr int kBindingsXml = ...; }
# namespace Addons::Embedded::Manifest {
# constexpr const char *kAddons[] = { ... }; // in ADDONS order
# constexpr size_t kAddonCount = ...;
# struct File { const char *path; int resourceId; int index; };
# constexpr File kFiles[] = { ... };
# constexpr size_t kFileCount = ...;
# }
# namespace Texture::Builtin::Manifest {
# struct File { const char *path; int resourceId; int index; };
# constexpr File kFiles[] = { ... };
# constexpr size_t kFileCount = ...;
# }
#
# Each resource is a pack: one gzip stream of several files, which
# pack_files.cmake joins at build time into `OUT_DIR/embed/<name>.pack.gz`.
# Resource 1 is the bindings XML, a pack of one; then each addon is one
# pack, in ADDONS order; then the textures, one pack. A pack compresses each
# file against the files before it, so the addon text packs to about 22% of
# its size, against 27% for one gzip stream per file. The DLL inflates a
# whole pack with the engine's zlib on first use (src/embed/Resource.cpp),
# so the load-on-demand addon costs nothing until it loads.
#
# Addon file paths are relative to ADDONS_ROOT, in backslash form
# (`!!!ClassicAPI\Util\Print.lua`) — the suffix the engine builds after
# `Interface\AddOns\`. Texture paths are relative to TEXTURES_ROOT, where
# each file sits at its game path (`Interface\Cursor\Quest.blp`), for
# src/texture/Builtin.cpp. The DLL compares both ignoring case. A file's
# index is its place in its pack, which is in path order.
#
# Each addon's `.toc` is the one file that is not embedded verbatim: its
# `## Version:` line is stamped with ADDON_VERSION into a copy under
# OUT_DIR, so a release build is a pure function of `-DCLASSICAPI_TAG` and
# the source tocs stay `DEV`. The developer marker `.classicapi-dev` is
# never embedded: it must reflect on-disk presence only (see
# DiskHasDevMarker in src/addons/Embedded.cpp).
#
# Rebuild triggers: adding or removing a file reconfigures through the
# CONFIGURE_DEPENDS glob; editing a toc reconfigures through
# CMAKE_CONFIGURE_DEPENDS; editing any other file re-packs its addon through
# the pack's custom command, which recompiles the .rc through its
# OBJECT_DEPENDS.
#
# Usage:
# embed_resources(TARGET <t> ADDONS_ROOT <dir> ADDONS <folder names...>
# ADDON_VERSION <v> BINDINGS_XML <file>
# TEXTURES_ROOT <dir> OUT_DIR <dir>)
set(_EMBED_PACK_SCRIPT "${CMAKE_CURRENT_LIST_DIR}/pack_files.cmake")
# Add the build-time command that packs `ARGN` (absolute paths, in pack
# order) into `<out_dir>/embed/<name>.pack.gz`, and set `gz` in the caller
# to that path. The paths reach the script through a generated list file:
# an addon's paths are too long for one command line.
function(_embed_pack out_dir name)
set(pack "${out_dir}/embed/${name}.pack")
set(list "set(FILES\n")
foreach(path ${ARGN})
string(APPEND list " [==[${path}]==]\n")
endforeach()
string(APPEND list ")\n")
_embed_write_if_changed("${pack}.cmake" "${list}")
add_custom_command(
OUTPUT "${pack}.gz"
COMMAND "${CMAKE_COMMAND}" "-DLIST=${pack}.cmake" "-DOUT=${pack}.gz"
-P "${_EMBED_PACK_SCRIPT}"
DEPENDS ${ARGN} "${pack}.cmake" "${_EMBED_PACK_SCRIPT}"
VERBATIM)
set(gz "${pack}.gz" PARENT_SCOPE)
endfunction()
# Write `content` to `path` only when it differs, so an unchanged
# reconfigure does not touch the file and trigger a rebuild.
function(_embed_write_if_changed path content)
set(tmp "${path}.tmp")
file(WRITE "${tmp}" "${content}")
configure_file("${tmp}" "${path}" COPYONLY)
file(REMOVE "${tmp}")
endfunction()
function(embed_resources)
cmake_parse_arguments(E ""
"TARGET;ADDONS_ROOT;ADDON_VERSION;BINDINGS_XML;TEXTURES_ROOT;OUT_DIR"
"ADDONS" ${ARGN})
set(rc "// Generated by cmake/embed_resources.cmake - do not edit.\n\n")
set(addon_names "")
set(manifest "")
set(inputs "")
set(bindings_id 1)
_embed_pack("${E_OUT_DIR}" "Bindings.xml" "${E_BINDINGS_XML}")
string(APPEND rc "${bindings_id} RCDATA \"${gz}\"\n")
list(APPEND inputs "${gz}")
set(id 2)
foreach(addon ${E_ADDONS})
string(APPEND addon_names " \"${addon}\",\n")
file(GLOB_RECURSE files CONFIGURE_DEPENDS RELATIVE
"${E_ADDONS_ROOT}" "${E_ADDONS_ROOT}/${addon}/*")
list(FILTER files EXCLUDE REGEX "(^|/)\\.classicapi-dev$")
list(SORT files) # deterministic indexes
set(paths "")
set(index 0)
foreach(rel ${files})
set(abs "${E_ADDONS_ROOT}/${rel}")
if(rel MATCHES "\\.toc$")
file(READ "${abs}" toc)
string(REGEX REPLACE "## Version:[^\n\r]*"
"## Version: ${E_ADDON_VERSION}" toc "${toc}")
set(stamped "${E_OUT_DIR}/embed/${rel}")
_embed_write_if_changed("${stamped}" "${toc}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${abs}")
set(abs "${stamped}")
endif()
list(APPEND paths "${abs}")
string(REPLACE "/" "\\\\" rel_bs "${rel}")
string(APPEND manifest " { \"${rel_bs}\", ${id}, ${index} },\n")
math(EXPR index "${index} + 1")
endforeach()
_embed_pack("${E_OUT_DIR}" "${addon}" ${paths})
string(APPEND rc "${id} RCDATA \"${gz}\"\n")
list(APPEND inputs "${gz}")
math(EXPR id "${id} + 1")
endforeach()
file(GLOB_RECURSE textures CONFIGURE_DEPENDS RELATIVE
"${E_TEXTURES_ROOT}" "${E_TEXTURES_ROOT}/*")
list(SORT textures) # deterministic indexes
set(texture_paths "")
set(texture_manifest "")
set(index 0)
foreach(rel ${textures})
list(APPEND texture_paths "${E_TEXTURES_ROOT}/${rel}")
string(REPLACE "/" "\\\\" rel_bs "${rel}")
string(APPEND texture_manifest " { \"${rel_bs}\", ${id}, ${index} },\n")
math(EXPR index "${index} + 1")
endforeach()
_embed_pack("${E_OUT_DIR}" "Textures" ${texture_paths})
string(APPEND rc "${id} RCDATA \"${gz}\"\n")
list(APPEND inputs "${gz}")
_embed_write_if_changed("${E_OUT_DIR}/embedded.rc" "${rc}")
_embed_write_if_changed("${E_OUT_DIR}/embedded_resources.h"
"// Generated by cmake/embed_resources.cmake — do not edit.
// Resource IDs for the RCDATA packs in embedded.rc, and each embedded file's
// place in them. Load them through src/embed/Resource.h.
#pragma once
#include <cstddef>
namespace Embed::Ids {
constexpr int kBindingsXml = ${bindings_id}; // a pack of the one file
} // namespace Embed::Ids
namespace Addons::Embedded::Manifest {
// Registration order: the first one registers, and so loads, first.
constexpr const char *kAddons[] = {
${addon_names}};
constexpr size_t kAddonCount = sizeof(kAddons) / sizeof(kAddons[0]);
struct File {
const char *path;
int resourceId; // its addon's pack
int index; // its place in the pack
};
constexpr File kFiles[] = {
${manifest}};
constexpr size_t kFileCount = sizeof(kFiles) / sizeof(kFiles[0]);
} // namespace Addons::Embedded::Manifest
namespace Texture::Builtin::Manifest {
struct File {
const char *path; // the game path
int resourceId; // the textures' pack
int index; // its place in the pack
};
constexpr File kFiles[] = {
${texture_manifest}};
constexpr size_t kFileCount = sizeof(kFiles) / sizeof(kFiles[0]);
} // namespace Texture::Builtin::Manifest
")
add_custom_target(${E_TARGET}_embed DEPENDS ${inputs})
add_dependencies(${E_TARGET} ${E_TARGET}_embed)
target_sources(${E_TARGET} PRIVATE "${E_OUT_DIR}/embedded.rc")
set_source_files_properties("${E_OUT_DIR}/embedded.rc" PROPERTIES
OBJECT_DEPENDS "${inputs}")
endfunction()
+50
View File
@@ -0,0 +1,50 @@
# pack_files.cmake — join files into one gzipped pack at build time, for
# embed_resources.cmake.
#
# cmake -DLIST=<list.cmake> -DOUT=<pack.gz> -P pack_files.cmake
#
# LIST sets FILES to the paths to join, in order. The pack is one gzip
# stream, so each file compresses against the files before it: the addon
# text packs about 16% smaller than when each file is gzipped alone. Inside
# the stream is an index, each file's size as a decimal line and then an
# empty line, followed by the files' bytes in FILES order. The DLL splits
# it in src/embed/Resource.cpp.
include("${LIST}")
set(index "")
foreach(file IN LISTS FILES)
file(SIZE "${file}" size)
string(APPEND index "${size}\n")
endforeach()
# Not file(WRITE): on Windows it writes each \n as \r\n.
file(CONFIGURE OUTPUT "${OUT}.index" CONTENT "${index}\n" @ONLY NEWLINE_STYLE UNIX)
# Join `ARGN` byte for byte into `out`.
function(cat out)
execute_process(COMMAND "${CMAKE_COMMAND}" -E cat ${ARGN}
OUTPUT_FILE "${out}" RESULT_VARIABLE rc)
if(NOT rc EQUAL 0)
message(FATAL_ERROR "pack_files.cmake: cannot join into ${out}: ${rc}")
endif()
endfunction()
# `cmake -E cat` takes its files on the command line, which Windows limits
# to 32767 characters: join in batches of 100, then join the batches.
set(parts "${OUT}.index")
list(LENGTH FILES count)
set(first 0)
while(first LESS count)
list(SUBLIST FILES ${first} 100 batch)
set(part "${OUT}.part${first}")
cat("${part}" ${batch})
list(APPEND parts "${part}")
math(EXPR first "${first} + 100")
endwhile()
cat("${OUT}.raw" ${parts})
# The raw format holds the one file's bytes with no archive entry around
# them, so OUT is a plain gzip stream.
file(ARCHIVE_CREATE OUTPUT "${OUT}" PATHS "${OUT}.raw" FORMAT raw
COMPRESSION GZip COMPRESSION_LEVEL 9)
file(REMOVE ${parts} "${OUT}.raw")
+38
View File
@@ -0,0 +1,38 @@
// Generated from cmake/version.rc.in by CMake configure_file().
// Stamps the PE VERSIONINFO resource so Explorer -> Properties -> Details
// and GetFileVersionInfo() report the same version as the CLASSIC_API_VERSION
// Lua global. Both derive from the CLASSICAPI_TAG (vMAJOR.MINOR.PATCH) cache
// var; an untagged dev build gets the 9999.99.99 "newer than everything"
// sentinel.
#include <winver.h>
VS_VERSION_INFO VERSIONINFO
FILEVERSION @CLASSICAPI_VER_MAJOR@,@CLASSICAPI_VER_MINOR@,@CLASSICAPI_VER_PATCH@,0
PRODUCTVERSION @CLASSICAPI_VER_MAJOR@,@CLASSICAPI_VER_MINOR@,@CLASSICAPI_VER_PATCH@,0
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
FILEFLAGS 0x0L
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_DLL
FILESUBTYPE VFT2_UNKNOWN
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0"
BEGIN
VALUE "CompanyName", "ClassicAPI Team"
VALUE "FileDescription", "ClassicAPI - modern WoW API backport for 1.12.1"
VALUE "FileVersion", "@CLASSICAPI_VER_STRING@"
VALUE "InternalName", "ClassicAPI"
VALUE "LegalCopyright", "Licensed under GPLv3"
VALUE "OriginalFilename", "ClassicAPI.dll"
VALUE "ProductName", "ClassicAPI"
VALUE "ProductVersion", "@CLASSICAPI_VER_STRING@"
END
END
BLOCK "VarFileInfo"
BEGIN
// 0x0409 = U.S. English, 1200 = Unicode codepage.
VALUE "Translation", 0x409, 1200
END
END
+19214 -2614
View File
File diff suppressed because it is too large Load Diff
+58 -1
View File
@@ -9,7 +9,8 @@ ImageBase `0x00400000`. All VAs in this doc use that base.
## How Blizzard wires Lua
There are two registries.
There are two Blizzard registries, plus the Lua standard libraries, which are
bound a third way (§3) and are NOT in the batch counts below.
### 1. Global functions — `FrameScript_RegisterFunction` at `0x00704120`
@@ -57,6 +58,62 @@ C3 ret
23 tables found, **481 methods total**. The runtime dispatcher at `0x005368D0`
resolves `frame:method(...)` by looking the name up in the matching context.
### 3. Lua standard libraries — `luaL_openlib` tables
The Lua 5.0 standard libraries, and Blizzard's replacements inside them, are
bound by `luaL_openlib` walking one `luaL_reg { char *name; lua_CFunction
func; }[]` table per library when the Lua state is created (`FUN_00703B80`,
called immediately BEFORE `FUN_LOAD_SCRIPT_FUNCTIONS`). They never pass
through `FrameScript_RegisterFunction`, so none of them appear in the 54
batches above or in the loop scan behind `raw_globals.txt` — which is how
`debugprofilestart` / `debugprofilestop` (stock since 1.7.0) went
uncatalogued here until 2026-09. **Before declaring a global absent, check
these tables or `/dump` the name in game.**
**Base library** — table `[0x00811E28]`, 36 entries, `.rdata`. Blizzard's
own base library: the stock 5.0 set minus `dofile`/`loadfile`/`require`/
`print` (`print` is a ClassicAPI backport), plus the `debug*` /
`*errorhandler` / `date` / `time` additions.
```
0x00702770 setglobal 0x00702DF0 type
0x007027B0 getglobal 0x00702E30 tonumber
0x007027E0 debugload 0x00702F40 tostring
0x007027F0 debuginfo 0x007030A0 unpack
0x00702800 debugprint 0x007030F0 rawequal
0x00702810 debugdump 0x00703130 rawget
0x00702820 debugbreak 0x00703160 rawset
0x00702830 debugtimestamp 0x007031A0 assert
0x00702840 debugprofilestart 0x00703200 gcinfo
0x00702860 debugprofilestop 0x00703250 collectgarbage
0x00702900 seterrorhandler 0x00703280 loadstring
0x00702950 geterrorhandler 0x007032F0 pcall
0x00702970 error 0x00703340 xpcall
0x007029F0 getmetatable 0x007033A0 date
0x00702A40 setmetatable 0x007035A0 time
0x00702AC0 getfenv 0x00703760 debugstack
0x00702BE0 setfenv
0x00702C90 next
0x00702CD0 ipairs
0x00702DA0 pairs
```
`debugprofilestart` stores `rdtsc` in `0x00CEEB58` (u64);
`debugprofilestop` pushes `|rdtsc − start| / (ticksPerSecond / 1000)` as a
double, where `ticksPerSecond` is `FUN_0042C020` = `(int64)(1000.0 /
[0x008332C8])` — a TSC scale calibrated at boot (the image holds `1.0`). So:
milliseconds with a sub-microsecond fraction, from the CPU counter, unrelated
to the engine's millisecond tick and to `GetTime()`.
The `table`, `string` and `math` libraries have the same shape (the `table`
library's `luaL_reg` is at `0x00822D70` — see `Offsets.h`
`FUN_LUA_TABLE_INSERT`) and are not enumerated here. The short global
aliases (`tinsert`, `getn`, `strlen`, `format`, `floor`, …) are not registered
at all: an embedded Lua chunk at `.data 0x008722E8`, run by the same state
init, assigns them from the library tables (`tinsert = tab.insert`). A module
that registers over a library function must therefore re-bind its alias —
`Game::Lua::RegisterGlobalAlias`.
## Scope
The 54 global-function batches split into two phases:
+11
View File
@@ -435,6 +435,17 @@ and other DLLs claim for custom events.
## Notes on specific entries
- **`[336] UPDATE_MOUSEOVER_UNIT` now fires on loss too (ClassicAPI).**
Stock 1.12 fires this only when a mouseover unit is *gained*; moving
the cursor off a unit clears the mouseover and signals nothing.
ClassicAPI co-hooks the engine's mouseover set/clear chokepoint
(`0x00492890`, the sole writer of the mouseover GUID) and fires
`UPDATE_MOUSEOVER_UNIT` on the unit→non-unit transition, matching
retail. Gated on the *old* mouseover being a unit and the *new* one
not, so moving off a gameobject / item (which never fired a gain)
doesn't spuriously fire. No payload either way — handlers read
`UnitExists("mouseover")`, false at fire time on loss. See
[API.md](API.md#update_mouseover_unit-event-loss-fire-fix).
- **Repeated `UNIT_*` entries at low indices** (e.g. four slots named
`UNIT_DAMAGE` at 128–131, five `UNIT_STATS` at 144–148, seven
`UNIT_RESISTANCES` at 149–155) — these are the per-stat /
+858
View File
@@ -0,0 +1,858 @@
# Backporting inline `|T…|t` texture escape sequences to 1.12
The 1.12 text engine shows `|Tpath:height:width:…|t` markup as literal text.
This project makes it draw the icon inline in FontStrings, chat, and tooltips —
the way 4.3.4 and later clients do. The feature is complete and shipped
([src/text/InlineTexture.cpp](../src/text/InlineTexture.cpp),
[src/text/InlineTexturePool.cpp](../src/text/InlineTexturePool.cpp)).
This file is the reverse-engineering map. **Current design** below states what
ships today. Everything from **Goal & spec** down is the historical RE trail —
the 4.3.4 study, the 1.12 injection map, and the bring-up plan. It is kept for
the addresses and the reasoning, not as a description of the current code.
## Current design (shipped)
Each icon renders as an **engine-managed region** (a pooled `CSimpleTexture`)
anchored to its owning FontString. The engine draws the region every frame and
moves it with its line, so texture residency and scroll tracking are correct by
construction. (A raw-GxU-quad renderer existed during bring-up and was removed
in `56c2670`; its RE is the "REMOVED" section below.)
The DLL hooks the engine's own text pipeline — no companion addon:
- **Positioning** — a co-hook on the glyph emitter `FUN_005ccbe0` records each
icon at its pen position and delegates the plain text runs to the engine
(segmented delegation, below). The pen read-back needed a fix: the engine's
pen is lazy and omits the last glyph's own advance, so a coin sat on its
digits; the emitter now adds the true terminal advance from the engine's own
glyph-advance helpers (`550cf5e`).
- **Rendering** — 4.3.4's `CSimpleEmbeddedTexture` model. Each icon is a
pooled `CSimpleTexture` with no frame, anchored to its fontstring: it is in
no draw layer, so the fontstring draws it. The fontstring's batch call
(`FUN_FONTSTRING_EMIT` `0x00772E50`, 4.3.4's `CSimpleFontString::Draw` →
`QueueTextures`) adds the icons right after its text, and only when the text
went in, so an icon shows exactly when its line does — hidden, faded out, off
screen, or scrolled off the top of a chat frame — in the same frame.
- **No one-frame lag** — 4.3.4 sets the embedded textures up in `UpdateString`,
right after it builds the string. The `RebuildString` co-hook does the same:
a rebuild drops the fontstring's icons, lays the new node out now (the
ensure-built call the paint makes) and applies the placements at once, so a
string's icons draw with its text wherever it was rebuilt (a chat line laid
out by its frame, a tooltip line, a rect change). The paint-pass co-hook
`FUN_005c8fe0` still walks the icon records and queues them to
`Text::InlineTexturePool` for the next frame tick: the backstop for a string
whose placement can't be computed at rebuild time.
- **Placement coordinates** — text pen space IS render-target pixels. The
engine stores node positions NORMALIZED (fs-local anchor ÷
`[0x832A44]`/`[0x832A48]` per axis, `FUN_0041ade0`), and the origin finalize
`FUN_005cdf70` multiplies by the integer raster dimensions
`[0xC2B9A4]`/`[0xC2B9A0]` (rounded, with the justify shift and vertical
align folded in). So the flush converts pen → fs-relative anchor with
`K = raster ÷ anchorExtent`, **per axis**, from those four live globals — no
calibration, no cache, correct at every resolution and UI scale (`968335d`).
Two earlier forms both failed: an empirical K (`origin ÷ rect edge`) that
chat could never self-derive (its rect edge sits near screen x = 0 and
failed the divide guard) and so rode a global cache seeded by whichever
fontstring derived first — right only at the layout it was calibrated on;
then a closed form built from the SetPoint px factor, which used the wrong
global pair. Full derivation chain at `VAR_TEXT_RASTER_X/Y` in `Offsets.h`.
- **Fade / parent alpha** — icons fade with their line (the pool mirrors the
fs's folded colour alpha per frame, `3ca3b7e`), and segmented GLYPHS do too:
a bit-3 (standalone FontString) node's baked per-glyph colours never re-bake
on an alpha change (the engine's colour-change invalidate `FUN_005ccb40`
skips bit-3 nodes), so the flush mirrors the node's live alpha byte
(node+0x2c — SetTextColor alpha × frame-chain alpha, kept folded by the
engine) into every baked colour, change-detected per page (`bd14a93`). An
earlier `0xFF` alpha force at emit was a misdiagnosis of a bubble that built
while faded out; it froze icon-line text fully opaque while everything
around it faded.
- **Size, spacing and alignment are 4.3.4's rules** (decompiled source in
`C:\Git\wowdecomp15595`; 3.3.5 has the same). See "Icon geometry" below.
Every hand-tuned constant this module once carried (a 0.18 × font lead/trail
pad, a 0.6 × font vertical centre, a −1px region nudge, a size multiplier)
is gone.
- **Measure** — three cold FontString-level co-hooks make measure match the
drawn result: width (`FUN_00772890`), height (`FUN_007729B0`), and wrap
(`FUN_005C7260`). `GetStringWidth`, `fontstring:GetStringHeight`, wrap
breaks, and line height all count the icon.
- **Tall icons** — a line holding an icon taller than the font moves itself
and the lines after it down by the overflow, as 4.3.4 does, so it does not
overlap its neighbors; the icon aligns by the line's vertical justification
(below). A hyperlink
that contains a tall icon is hoverable across the whole icon
(`49934b0`, `b9d0705`).
- **Chat fade** — icons fade in lockstep with their chat line (`3ca3b7e`).
- **Edit boxes** — render the icons in their text, as 4.3.4 does; the caret,
the mouse and the arrow keys treat an icon as one character, Ctrl+C
drops icons (4.3.4's 0x1500 strip mask), and a multi-line box's caret,
selection and click rows follow the lines a tall icon moves (below;
4.3.4's own rows do not). Typed markup stays literal by the engine's own
input escape (below).
- **Payload** — the full
`|Tpath:height:width:offsetX:offsetY:texW:texH:left:right:top:bottom:r:g:b|t`:
size, pen offset, sprite-sheet crop, and vertex tint. BLP and uncompressed
TGA.
- **Anti-spoof** — chat neutralizes a player-injected `|T` the way the edit
box neutralizes a typed one (the `|` is doubled).
- **Raid markers** — `{rt1}`/`{skull}`/… become icons in the CHAT_MSG text and,
separately, in the speech bubble after its escape strip (4.3.4's
`CGChatBubbleFrame::ParseRaidIcons`).
Every fs-level measure path now counts icons: width (`FUN_00772890`), height
(`FUN_007729B0`), wrap (`FUN_005C7260`), and the substring measure
(`FUN_00772AE0` — an earlier note claimed nothing consumed it; its xrefs
refute that: the GameTooltip auto-size measures each WRAPPED SEGMENT of a
wrap-enabled line through it, so icon-bearing wrapped tooltip lines
undersized their tooltip until it was hooked too). The Lua control surface is
one toggle: `_classicapi_InlineTexEnable` (the whole-feature kill switch; the
SEH latch trips it on a fault). The
bring-up tune / stat / probe functions were removed (`5e5677b`, `6800a9a`).
## REMOVED (bring-up record) — the raw-GxU-quad rendering primitive
This was the FIRST renderer: each icon drawn as a raw textured quad through the
text VB path. It shipped, then was removed in `56c2670` for the engine-region
model (regions are resident by construction; the quad path needed the texture-
residency machinery below and still flickered on VRAM pressure — see
`docs/InlineTextureResidency.md`). This section is the address record for the
removed code, not a description of the current renderer. `LoadTextureByPath`,
`DrawTexturedQuad`, and the GxU device offsets it names are gone from
`Offsets.h`; the values live here and in git history.
An arbitrary texture draws through the text VB path as a coloured, alpha-blended
quad. The end-to-end recipe:
1. **Load by path** — `LoadTextureByPath` replicates `FUN_00770200`'s load: build
flags via `FUN_0058a980(&flags, DAT_00878cf0, 0,0, 0,0,0, 1, 0)`, then
`FUN_00449d90(path, &desc, flags, 0, 1)` with a byte-identical 5-dword desc
(`{PTR_FUN_007ffa10, 8, &self8, (&self8)|1, 0}`). Returns the **HTEXTURE**
(0x15c-byte struct; path@+0xc, flags@+0x110, refcount@+4).
2. **THE KEY — residency + correct bind via `FUN_0044acf0(HTEXTURE, 1, 0)`.**
This is the engine's own "get renderable texture" call (what the widget
render uses every frame). It returns the bindable **CGxTexture** at
`[HTEXTURE+0x140]` and, with force=1, drives the streaming load
(`FUN_0044ad50` submits/prioritises it via `[HTEXTURE+0x138]`). **Calling it
every frame is the live reference that makes the texture resident** — no
hidden widget, no manual BLP decode. This was the entire multi-session
blocker: WoW streams textures and only loads ones a live frame references; a
standalone `FUN_00449d90` texture never loads on its own. Binding the raw
HTEXTURE is `SetTexture([HTEXTURE+0x48]=0)` = a **white** quad; the D3D
handle lives on the CGxTexture (`[CGxTexture+0x48]`), not the HTEXTURE.
Dead ends that wasted time: manually invoking the decode callback
`FUN_0044a260` (fills `[+0x120]` but not the bindable `+0x140`, and faults);
binding `[HTEXTURE+0x48]` or `[HTEXTURE+0x120]` (both wrong offsets); forcing
the streamable flag `tex[0x3c]|=0x80` (crashes in d3d9 — the bind's stream-in
vfunc corrupts the resource).
3. **Bind** — `FUN_00589e80(0x17, cgxTex)` (selector 0x17 = text texture stage).
4. **Colour** — the font stage's default stage-0 COLOROP is already MODULATE, so
`texture.rgb × diffuse(white)` = the icon's true colours; texture alpha works
too. No colorop override is needed for a plain white vertex. (If a tint is
wanted later: COLOROP is D3DTSS internal state `0x42` via `FUN_005a2570`; the
engine leaves COLORARG1 at the D3D default = TEXTURE. Do NOT poke it directly
mid-draw — it leaks `MODULATE` to the whole UI when a fault skips the restore.
Use the engine's selector `0x1f` (value→COLOROP/ALPHAOP preset table at
`DAT_0080a25c`/`DAT_0080a274`; value 1 = MODULATE/MODULATE).)
5. **Quad** — lock the shared dynamic VB `FUN_0058a140(0, 0x18, 0x800)`, get the
write ptr `FUN_0058a080`, write **4 verts** of the format
`{float x,y,z; u32 colorBGRA; float u,v}` (stride 0x18) in corner order
**TL, TR, BL, BR** (matches the shared quad index buffer `{0,1,2, 2,1,3}` and
the device cull winding), submit `FUN_005c8f40(&handle, 4)`, unlock
`FUN_0058a0a0(handle, 0)`.
6. **Where** — co-hook the text paint pass `FUN_005c8fe0` and draw after the
original glyph flush (device is in the correct textured-UI state there).
Coordinate space is **per-layout pixels, y-down**; glyph verts live at small
local coords (a probed glyph was at ~(9,33)–(17,50)). Draw coords must be
within the layout's rendered area (a fixed (100,100) test lands in chat).
The build-side gotcha: the D3D device (default backend, `FUN_0058dd70`) is
actually **OpenGL** (`glMaterialfv`/`glFogi`) — the D3D backend is `FUN_0058ba70`
(`FUN_00598ce0`, vtable `PTR_FUN_00809ef8`); its state applier is `vtable[1]` =
`FUN_005a2f00`, which maps engine selectors to D3D via `FUN_005a2570`
(SetRenderState `+0xe4`, SetTextureStageState `+0x10c`, SetSamplerState `+0x114`,
SetTexture `+0x104`). Selector map (shared across GL/D3D backends): 7=blend,
0x10=depthtest, 0x14=cullface, 0x17-0x1e=texture bind (8 units),
0x1f-0x26=colorop/alphaop preset (unit 0-7).
## SOLVED — positioning, measure/wrap, edit boxes, texcoords
The primitive draws at arbitrary coords; the rest is knowing WHERE and WHEN.
Everything is in [src/text/InlineTexture.cpp](../src/text/InlineTexture.cpp);
offsets under the "Inline texture escape" + positioning blocks in
[Offsets.h](../src/Offsets.h).
### The text render hierarchy (verified)
```
frame → renderNode [frame+0x118] → group [renderNode+0x18]
→ node [group+0x18] → line [node+0x24] ← the emitter's `this`
```
- Main UI render `FUN_007657d0(DAT_00cf0bd8)` walks strata → frames, calls
`FUN_0076fb00(renderNode)` per frame's render node.
- `FUN_0076fb00` draws the frame's Texture regions then `FUN_005c1ef0(group)` →
`FUN_005c8b70(group)` → `FUN_005c8fe0(node)` per node.
- `FUN_005c8fe0(node)` = the **paint pass** we co-hook: ensures each line built
(`FUN_005cd6a0` → `FUN_005cdc20` → the emitter), then binds each font page and
copies the line's per-page glyph batches into the dynamic VB, translated by the
line origin `[line+0x70]/[+0x74]`.
- The **emitter** `FUN_005ccbe0(line, text, len, colorState, penXYZ, pageMask,
linkState)` builds one wrapped line's glyph quads. `this` (the "line"/node the
icon list keys on) owns batches `[+0xa0+page*4]` and origin `[+0x70]`. **Note
the render node the emitter sees has NO back-pointer up to the frame.**
### Positioning — segmented delegation (co-hook the emitter)
We do NOT reimplement the emitter's intricate glyph vertex math. Instead, in the
`FUN_005ccbe0` co-hook, for a line containing an inline texture:
1. Split the line at icon boundaries. Render each **plain run** by calling the
ORIGINAL emitter on just that substring — the engine still draws every glyph.
2. Thread the pen across runs: on return the emitter leaves the final node-local
pen x in **`linkState[4]`**, stored with `FSTP dword` — a **FLOAT bit
pattern**, not an int. Read it as a float (`*(float*)&linkState[4]`); an
int-cast yields garbage (this bug hid the icon off-screen and dropped the
trailing text).
3. Record an `IconRecord` at the pen (node-local `x`,`y`) into `g_nodeIcons[line]`
and advance the pen by the icon width. No draw runs during the build — icons
are recorded and **flushed** in the `FUN_005c8fe0` paint co-hook, which
computes each icon's pen-space position (line origin `[line+0x70]/[+0x74]`
maps node-local → pen, the same translate the glyph copy `FUN_005c8710`
applies), converts pen → anchor with the per-axis K (see **Placement
coordinates** in Current design), and queues it to `Text::InlineTexturePool`
as a placement RELATIVE TO THE OWNING FONTSTRING. The pool applies
placements on the next frame tick.
4. Restore `penXYZ[0]` on exit (the original never writes it; the draw builder
does NOT reset it between left-justified lines, so leaving it mutated
cascade-shifts every following line).
### The span rule — `|T…|t` only, `||` is always a literal pipe
One scanner, `IconSpanAt`, decides what a span is, with 4.3.4's
`GxuDetermineQuotedCode` CODE_TEXTURESTART rule: after `|T` (or `|A`), the
FIRST `|` must be followed by `t` (`a`), and an empty `|T|t` is literal.
Anything else is not a span and draws as text. Every walker steps over `||`
as a pair, because `||` is the escaped pipe in both engines.
That is what keeps typed markup literal everywhere — chat display, edit
boxes, macros: the edit box stores a typed `|` as `||` (`0x77c254`; Paste
goes through the same `InsertChar`, as in 4.3.4), so a typed `|Tpath|t` is
`||Tpath||t` in every buffer it reaches.
(An earlier version matched a "doubled" `||T…||t` form too, on the belief
that the FontString sanitizer doubled unknown escapes. Stock 1.12 has no
such sanitizer — not SetText `0x771d80`, its grammar pass `0x7716f0`,
FitText `0x771ec0`, nor the edit box's RebuildLabel `0x77d4d0`. The `||T`
seen in chat lines was typed text, and our own `{rt1}` expansion emitted it
on purpose to survive the bubble's escape strip. Matching it turned every
typed `|T` into an icon, which is why the edit box needed the suppression
gates the span rule replaced.)
### bit-3 batch-clear mode
The emitter clears the line's page batches at its top only when node flag
`[line+0x5c] & 0x08` is set (the FontString/static case). Calling the original
per segment would then wipe all but the last run. Handled by doing the clear
ONCE per build (a `len==0` original call with bit 3 still set), then clearing
bit 3 so the per-segment calls APPEND, restoring flags on exit. Bit 5 (shadow)
isn't set for these nodes, so the only added work is a harmless colour append.
Clearing bit 3 has one more consequence: it switches the engine from the
UNIFORM colour path (node+0x2c, consulted live at every paint) to baked
PER-GLYPH colours the paint uses verbatim. The build-time alpha in colorState
is already correct (the engine folds SetTextColor alpha × frame-chain alpha
into node+0x2c on every alpha change), but the baked copies never refresh —
the flush's alpha mirror keeps them tracking later fades. See **Fade / parent
alpha** in Current design.
### Multi-line / multi-icon accumulation
The draw builder walks a node's wrapped lines by calling the emitter repeatedly
on the SAME node, advancing the text pointer. So the icon list is cleared ONCE
per build — on the first wrapped line, detected by `text == [node+0x48]` (the
node's text start) — and icons ACCUMULATE across lines. Multiple icons per line
fall out of the segmentation loop naturally.
### Icon geometry — 4.3.4's rules, ported
**Size** (`ParseEmbeddedTexture`, 0x00617BA0 in 4.3.4). A WRITTEN size is not
pixels: it multiplies by `fontPx / (14 × ddcWidthScale)`, the reduction of the
engine's `windowPx / (aspectComp × 1024) × fontHeight / NDCToDDCWidth(14 /
(aspectComp × 1024))` (the call list of the real apwow.exe function confirms
`CoordinateGetAspectCompensation` + `NDCToDDCWidth`). So sizes are relative to
a 14-unit font and follow the text's size, UI scale and resolution. 1.12 holds
ddcWidthScale in the same Coordinate static (`VAR_COORD_DDC_WIDTH_SCALE`,
0x00832A44 — the four statics sit at 0x00832A40 with 4.3.4's exact initial
values). On top of that, every size multiplies by the fontstring's layout
scale (`fs+0x7C`) — 3.3.5's `CGxString::m_scale`, applied again although the
font height already includes it. 4.3.4 dropped this factor; 3.3.5's was kept
after a side-by-side look in game. Every wrap gets the same scale, as 4.3.4
passes `m_layoutScale` to every `CalcWrapPoint`: the draw builder through the
node's owner, and the three fs-level callers (the height getter, the
display-text truncation inside the rebuild, the break array) through a
fontstring scope their co-hooks set (`WrapLayoutScale`). Size cases: height ≤ 0 → font height; width absent → the height;
width > 0 → width × scale, or a RATIO of the height when the height came from
the font (`:0:2` is twice as wide); width ≤ 0 → the font height. Offsets are
screen pixels and move only the drawn texture (+x right, +y UP), never the
layout. `ResolveIconSize` is the one implementation.
**Spacing** (`InitializeTextLine`, case CODE_TEXTURESTART). An icon starts at
the previous glyph's INK edge — bearing + cell width, clamped to ≥ 0 and
capped at the glyph's own advance (`FUN_TEXT_GLYPH_BASE_ADVANCE`) — plus
the face's outline ink (4 × scale thick / 2 × scale thin, `face+0x180` bits 3 /
0; the same constants the 1.12 emitter grows its line by); with no glyph
since the line start or the last icon it starts at the pen, no gap. The next
glyph starts at `floor(iconRight + 0.5)` with no kerning against the icon.
1.12's emitter doesn't report its last glyph's position (its pen is lazy), so
`drawRun` replays the run's placements with the emitter's own helpers — the
pair advance, the snap rounding (`FADD 0.5; __ftol`), `FUN_TEXT_GLYPH_DESC`
(`CGxFont::NewCodeDesc`) and `FUN_TEXT_GLYPH_BEARING` — and floors the cell
width in snap mode exactly as the emitter draws the quad. Measures count an
icon as its width plus the outline gap when a glyph precedes it
(`SumIconAdvances`); the engine measures width alone, but counting the gap
keeps measure and render in step for tooltips and right-justified text. The
advance cap is ClassicAPI's: every measure counts the preceding glyph by its
advance, so an ink edge past the advance (a glyph cell wider than its step —
seen on "[" in chat) pushed each following icon and the rest of the line past
the measured width, and wrapped chat lines overran the frame edge.
**Vertical** (same case + `CreateGeometry`). By the node's vertical justify
(`OFF_TEXT_NODE_JUSTIFY_V`, node+0x50: 0 top / 1 middle / 2 bottom — the
branch of the origin finalize `FUN_005cdf70`): top → the icon's top on the line
top; bottom → its bottom on the baseline; middle → centred on the font height
below the line top. The baseline is `penXYZ[1]` and the line top is the draw
builder's `linkState[1]` (baseline + font height + spacing), 4.3.4's
m_baseLineHeight / m_lineHeight.
**Tall lines** (`CGxString::InitializeText` + `InitializeViewTranslation` +
`GxuFontGetWrappedTextHeight`), mirrored step for step:
- A line whose tallest icon reaches past the font height moves down by that
overflow, and every later line with it: all of it before the line for
bottom justify, all after for top, `floor(overflow / 2)` before and after
for middle. The emitter co-hook moves the builder's pen y and link band
(`penXYZ[1]` = its `local_48`, `linkState[1]/[3]` = its `local_74[0]/[2]`),
which the builder lowers per line, so the move carries forward.
- The node's summed overflow (`m_extraLineHeight`) joins the text height the
origin finalize justifies by: the `FUN_TEXT_NODE_FINALIZE_ORIGIN` co-hook
raises the node position y (`+0x24`) by half / all of it for middle /
bottom justify for the call, so the engine's own math and rounding produce
4.3.4's origin. It also runs on every reposition (`FUN_005ccb10`).
- `GetStringHeight` adds the same per-line overflows, summed. The wrap
stepper reports each line's overflow during the engine's own height pass,
so the lines are the engine's breaks; the sum is kept per fontstring while
the engine serves its cached height.
A link's hit band grows toward where its icon reaches (below for top, above
for bottom, half each way for middle); 4.3.4 keeps the band at the text.
### Measure / wrap — co-hook the tokenizer
Line wrap is decided by the measure/fit functions (`FUN_005c6940`, `FUN_005c7470`
via `FUN_005c7260`), which all share the `|`-tokenizer `FUN_005c2810`. Left
alone, they count the hidden path text and wrap early. Fix: co-hook the
tokenizer — when it's at an inline-texture span, consume the whole span as ONE
near-zero-width token so every measure/fit caller ignores the path characters.
The emitter detects icons independently (it scans the raw bytes), so the draw
path is unaffected.
### Measure width: FIXED at the fs-level choke (`GetStringWidth` counts icons)
The tokenizer reports an icon span as a **near-zero-width** token, so at the
gxu loop level every measure caller counts the icon as ~0 pixels wide. (The
emitter still reserves the render width, so text after an icon positions
correctly.) An earlier version of this doc concluded that the gap could not
be closed cleanly, because the gxu engine has **no single cold choke**:
- `FUN_005c6940` (width), `FUN_005c7470`/`FUN_005c7260` (wrap), and the
hit-test loop each tokenize and accrue width independently.
- The token contract has no width field.
- The per-glyph helpers (`FUN_005cabd0`/`FUN_005c6b70`) are the hottest text
functions in the engine.
That analysis was right about the gxu level. The choke sits ONE LEVEL UP:
**`FUN_00772890` = `CSimpleFontString::GetStringWidthInternal`**
(`Offsets::FUN_FONTSTRING_STRING_WIDTH`) is cold, MinHook-safe, and the single
funnel for exactly 4 callers:
- `Script_GetStringWidth` (0x0079E510)
- the GameTooltip auto-size (0x00530640)
- the editbox selection-piece placer (0x0077DE70, a whole last line's width)
- the layout effective-width vmethod (`FUN_00772930` = fs+0x24 vtbl +0x1C,
which feeds auto-width fontstring layout)
It lazily computes into the `fs+0xFC` cache (anchor units, 0.0 sentinel) via
the measure core `FUN_0044D670`, then divides the pen-space result by
`fs+0x7C`.
The co-hook lives in `src/text/InlineTexture.cpp`. It calls the original,
then adds the icons' advances (`SumIconAdvances`) whenever the feature is
on — the same condition the tokenizer hook intercepts on, so measure and
render never disagree.
The icon sum is computed in TRUE PEN PX — the exact numbers the emitter
reserves — and bridged into the getter's return space by the font height
known in both spaces: `sumPen × (fontHInt / fontHPen)`. `ResolveFsPenFont`
replicates the render chain: `fontHPen = round((fontHInt × fs+0x7C, floored
at [0x801628]/rasterY) × rasterY)` (the rebuild's node fontSize + the node
ctor's min clamp + the emitter's own height helper), and the outline ink
resolves through `face = [[fs+0xE0]+0x20]` — the same object the node stores
at +0x44. fs-built nodes are always in snap mode (no fs-flag maps to node
bit 7), so the snap-truncated advances are exact. The per-icon advance comes
from `IconAdvancePen`, the **same helper** the emitter reserves with — so the
measured width matches the rendered width by construction, outline ink and
pixel snapping included. (An earlier bridge used the SetPoint push factor
`div×1024/mul ≈ 1468` as the intermediate — the units cancelled for `:0`
icons, but it couldn't express the truncation or the ink.)
Unit trap (hit on first flight): escape sizes are UI PIXELS. Do NOT divide
the icon sum by `fs+0x7C` — that field is the layout UI *scale* (~0.68–1.0).
The original's own `out / fs+0x7C` applies to a value the measure core
already ran through the `FUN_0041AD80` gxu→internal converter, not to raw
pixels. The `/0x7C` version measured a 16px icon as +44k px.
The hook NEVER writes the `fs+0xFC` cache: the original can serve the cached
value, so the icon sum is re-derived and re-added per call (idempotent).
The same hook also fixes two layout consumers for free: tooltips auto-size
wide enough for icon-bearing lines, and auto-width fontstrings lay out at
their true rendered width.
### Wrap: FIXED at the shared stepper (`FUN_TEXT_WRAP_STEPPER` = 0x005C7260)
Wrap decisions also measured icons as ~0, so a chat line with prefix icons
broke as if the icons were not there and the emitter's real advances ran past
the right edge. The choke is the wrap-stepper dispatcher `FUN_005C7260`: it
lays out one wrapped line per call, and its exactly 4 callers are EVERY wrap
consumer — the draw builder `FUN_005CDC20` (render breaks), the height
measure `FUN_005C2070`, the chars-that-fit counter `FUN_005C21C0` (ellipsis),
and the break-array computer `FUN_005C2430` (behind `FUN_00772B60`).
The co-hook shrinks the `wrapWidth` argument by a **minimal feasible
shrink** whenever the feature is on. The stepper reports each
probe's measured (icons-at-zero) line width in `outWidth`, which gives a
direct feasibility check: the line renders inside the frame iff its icons
fit in the shrink plus the spare the break left (`iconSum ≤ s + (probeW −
outWidth)`). The hook probes sandboxed (local out-params plus a COPY of the
`p10` in/out state byte, so the caller's first-line state is not consumed):
s = 0 first (feasible → no shrink at all — the common short-message case),
escalate by the measured deficit when infeasible, bisect down after the
first feasible hit; ≤8 probes, and with no feasible hit the last escalation
target wins (wraps early rather than overflowing). The feasibility check
carries a HALF-GLYPH tolerance: an auto-width fontstring (single anchor, no
width — e.g. pfUI's addon-list labels) wraps at the icon-inclusive string
width our GetStringWidth hook feeds the effective-width vmethod, so its line
fits with exactly zero slack, and cross-computation drift between the two
hooks' unit chains (plus OUTLINE extras and the trailing-glyph quirk) read
"fits exactly" as "1px over" — shrinking a zero-slack line forces a wrap
that had no business existing. Genuine icon overflow is ≥ a full icon, so
half a glyph separates drift from real overflow. `outBreak` and
`outNext − text` are byte counts; `outBreak == len` means the whole text
fit. Two rejected earlier schemes, for the record: a naive whole-remaining-
text sum shredded an 8-icon line to one word per line, and a fixed-point
iteration on the icon count oscillated (a ~55-byte zero-width escape makes
the break↔icon-count coupling discontinuous — no fixed point exists).
`text` always points at the REMAINING text, so a continuation line whose
icons are behind it gets sum = 0. Because all four consumers share the hook,
render breaks, `GetStringHeight`, truncation, and break arrays shift
together. (A `_classicapi_InlineTexWrap(n)` ring dumped the last 8
icon-bearing calls during bring-up; removed with the other diagnostics in
`5e5677b`.)
Unit trap #2 (hit TWICE): the stepper's inputs are gxu-normalized, PER AXIS —
fontH is normalized-Y (× rasterY = pen px) and wrapWidth/outWidth are
normalized-X (× rasterX = pen px). Both caller flavors land there: the draw
builder passes node+0x1C/+0x3C (normalized at block creation), and the
fs-level callers (the path chat wraps through) x-normalize their widths
inside `FUN_0044d670` before gxu. First flight subtracted raw pixels and
annihilated the small normalized widths (2-glyph chat fragments). The second
converted with `fontH / fontHPx` — a Y-AXIS factor applied to an X-axis
width — overshrinking the budget by the render aspect (×1.33 at 4:3, ×2.37
at 2560×1080): icon-bearing chat lines wrapped a word or two early, worse per
icon and per aspect. The correct pen-x → width-units factor is `1/rasterX`,
and the glyph-relative tolerances use `fontHPx/rasterX` so "half a glyph"
means an actual glyph width.
**Chat hyperlink hover over inline icons works (verified).** An emote wrapped in a
hyperlink — `|Htel:name|h|T…|t|h`, the TwitchEmotes pattern — pops its tooltip when
you hover the *icon*, not just adjacent text. The hover region is NOT re-measured
on hover: the engine records each hyperlink's screen rect at layout time into a
`GXUFONTHYPERLINKINFO` array (32-byte entries: rect + link data) via `FUN_005cd310`,
called from the draw builder `FUN_005cdc20` — the same layout pass that runs the
line through our co-hooked tokenizer (`FUN_005c2810`) and wrap-stepper
(`FUN_005c7260`). So the recorded rect rides the same icon-aware position
accounting the wrap fix installs; the icon lands inside the hover region for free,
and hovering it fires the frame's `OnHyperlinkEnter`. This is a consequence of the
wrap fix, not a separate feature. (`FUN_005cd310` itself, from benilla
font/string "Hyperlink regions", difftested: it multiplies the rect's y fields
`+0x08`/`+0x10` by 1/H and its x fields `+0x0c`/`+0x14` by 1/W and appends the
32-byte record to the array at `+0x7c`. Ghidra's own decompile of the call
args is mangled.)
**Still icon-blind (accepted residuals):**
- Sub-pixel only for an icon after a glyph: layout starts it at that glyph's
INK edge while measures count the glyph's advance, so the two differ by the
glyph's right bearing — the same discrepancy 4.3.4 has between its own
layout and measure loops. A string-final icon measures exactly (the gxu
width loop ends on the last glyph's ink, which is where the icon starts).
What remains is the icon region's ±0.5px placement rounding and the base
loop's ~0 contribution for the payload-0 icon token.
- An fs whose `fs+0xFC` cache was filled while the feature was toggled
differently (`_classicapi_InlineTexEnable`) keeps its old base width until
the next `SetText`/font change re-dirties it. Debug-toggle-only.
### Edit boxes — 4.3.4's model, no special case
4.3.4's edit box renders `|T…|t` in its text: no frame code ever sets the
FontString style bit 0x10000 that `ConvertStringFlags` maps to the gxu
texture-off flag 0x1000. Its cursor treats the span as one markup token
(`UpdateTextInfo` / `GetNumToLen`), and its `CopyToClipboard` strips with
0x1500 — colours, links AND textures. Typed markup never renders because a
typed `|` is stored as `||` (`CSimpleEditBox.cpp`, `ch == '|'`). 1.12 does
the same input escape, so ClassicAPI's edit boxes need no special case:
- **Render** — the label FontString (`RebuildLabel` `0x77d4d0`,
`SetText(buffer + scroll, 0)`, no pipe doubling) renders like any other,
and its regions parent to the edit box, so a ScrollFrame clips them.
- **Cursor** — the class array (`0x77ba90`) tokenizes through our tokenizer
hook, so a span is one class-6 letter: Left/Right cross it in one step,
Backspace deletes it whole, and an insert can never land inside it.
Class 6 is also the safe class — a skip class (0/4) as the last token
hangs the step loop (benilla ui/editboxmarkup "Faults"). 4.3.4 joins an
icon with the following character into one step; ours is its own step.
- **Caret x** — `FUN_0077DA80` measures the line through
`FUN_00772AE0`, whose co-hook adds the icons.
- **Rows (multi-line)** — `PlaceCaret` (`0x77da80`), `PlaceSelectionPiece`
(`0x77de70`) and `GetIndexAtPoint` (`0x77d0d0`) step rows of one height
(font height + spacing, pixel-aligned), as 4.3.4's `UpdateVisibleCursor`,
`UpdateHighlightArea` and `ConvertCoordinateToIndex` do — while the render
moves a tall-icon line and every line after it down by the overflow
(`InitializeText`; the emitter co-hook) and the box grows to match (the
string-height co-hook). 4.3.4 has that fault too; `EditBox::IconRows`
(`src/editbox/IconRows.cpp`) gives each placer the render's move, from
`Text::InlineTexture::LineIconShift` over the box's own line table: the
click's y is moved onto the uniform row of the icon-aware row under it
before the engine maps it; a selection piece is re-anchored after the
engine placed it, with the engine's own x; the caret likewise, then
`OnCursorChanged` fired once with the moved y through
`FUN_FRAME_RUN_SCRIPT_VARIADIC` exactly as `PlaceCaret` fires it (its own
fire muted for the call by emptying the slot), so
`ScrollingEditBoxMixin:ScrollCursorIntoView` scrolls to the real caret.
- **Click → cursor, single-line window** — `GetIndexAtPoint` (`0x77d0d0`),
`RebuildLabel` and `MeasureWindow` count characters with
`FUN_FONTSTRING_FIT_TEXT` (`0x772bc0` → `0x44d860` → `0x5c6c50`), whose
kernel counts an icon as one character of no width. Its co-hook mirrors
4.3.4's `GxuFontGetMaxCharsWithinWidth`: the run before each icon is fitted
by the original with the budget the earlier icons left, and an icon fits
when the icon-aware width through its end does.
- **Ctrl+C** — `CopySelection` (`0x77e1d0`) pushes 0x500; patched to 4.3.4's
0x1500, and the `GxuStripControlCodes` (`0x5c2590`) co-hook honours 0x1000
by dropping spans and stray `|t`. Paste re-escapes every `|`
(`InsertChar` per character), as in 4.3.4.
(History: before the span rule, every typed `|T` reached the emitter as a
matching `||T`, so edit boxes were special-cased with three gates — node
flag bit 6, a focused-buffer pointer test, and a content compare of the
render line against the focused input — plus a re-entry bracket so the
delegated raw layout did not draw blank. All removed. Node flag bit 6 is
NON-SPACE-WRAP, not "editable"; the gate only worked because the macro
editor sets it.)
### Descriptor fields + the vertical flip
`ParseIcon` handles the full positional payload
`path:height:width:offsetX:offsetY:texW:texH:left:right:top:bottom:r:g:b`.
Texcoords crop a sprite sheet to one cell: `u = left/texW, right/texW`,
`v = top/texH, bottom/texH` — e.g. `UI-RaidTargetingIcons` is a 256×256 sheet,
4×2 grid of 64×64, so marker N's cell is `256:256:<col*64>:<+64>:<row*64>:<+64>`.
**Vertex colour (`r:g:b`, 0-255):** the last three positional fields tint the
icon. They pack to `0xFFrrggbb` — the same `0xAARRGGBB` order the tokenizer's
`|cAARRGGBB` colour path builds (verified from `FUN_005c2810`'s colour branch),
so the value flows straight into the quad's vertex colour and the font stage's
default MODULATE COLOROP multiplies `texture.rgb × tint`. White (`255:255:255`,
the default) = untinted. Because parsing is positional, a tint needs all the
preceding fields present; the `TintIcon` helper passes `0`s for width..bottom
(texW/texH `0` disables the texcoord crop → full texture) so the colour lands in
the trailing slots.
**Texcoord order:** the region's 4-float texcoord setter
(`FUN_SIMPLETEXTURE_SET_TEXCOORD`) takes the rect **Y-FIRST INTERLEAVED**
(`{v0, u0, v1, u1}`), matching the engine's `{yA, left, yB, right}` rect
convention — diagnosed in-game when `{u0,v0,u1,v1}` rendered a raid-mark crop as
the wrong cell. v is top-down, same as the `|T` payload's top/bottom fields.
(The removed quad path had the inverse concern: the OpenGL backend put v=0 at
the bottom, so the quad mapped the TOP screen corners to v1 — kept here as the
backend note.)
### Build / deploy / test cadence
- `set -o pipefail; cmake --build build --config Release 2>&1 | tail -5 && cp build/Release/ClassicAPI.dll "C:/WoW/Octo/dll/ClassicAPI.dll"`
— `pipefail` stops a failed build from deploying a stale DLL.
- **The client must be fully EXITED to relink** (it loads a symlink to the
linker's output). DLL changes need a full restart, not `/reload`.
- **The embedded `!!!ClassicAPI` addon is symlinked**, so Lua-only changes (the
`TextureTest()` harness in `Util/AddOnCompat.lua`) need only `/reload`.
### Remaining / optional
- **Measure width, height, wrap** — all DONE (the three fs-level co-hooks in
Current design). Vertex-colour tint (`:r:g:b`) — DONE. The bring-up
diagnostics (`_classicapi_InlineTexSuppress/Tune/Stats/ProbeFS/RegionCal/Wrap`
and the capture globals) were REMOVED (`5e5677b`); only
`_classicapi_InlineTexEnable` remains.
- **Animated emotes** — no DLL work is needed: a TwitchEmotes-style animator
re-`SetText`s each line ~30fps and rewrites the `|T` texcoords to crop the
current film-strip frame. That is addon Lua. RLE-compressed TGAs do not
decode in 1.12 (uncompressed only) — convert with
`magick in.tga -compress none in.tga` (no `-orient`/`-flip`: the region
renderer's texcoord order shows the frame right-side-up).
- **Still icon-blind** (accepted): the hyperlink hit-test past a tall icon
OUTSIDE the link on the same line. The substring measure `FUN_00772AE0` was
hooked once its real consumer surfaced (the tooltip auto-size measures
wrapped SEGMENTS with it).
## Goal & spec
Render the modern inline-texture escape (warcraft.wiki.gg/wiki/UI_escape_sequences#Textures):
```
|Tpath:height[:width[:offsetX:offsetY[:texWidth:texHeight:left:right:top:bottom[:rV:gV:bV]]]]|t
```
Atlas markup is also supported:
```
|A:atlasName:height:width[:offsetX:offsetY]|a
```
It shares every scanner, measure, wrap and placement stage with `|T` — only the
payload parser differs. `ParseAtlasIcon` resolves the name through
`Texture::Atlas` and fills the SAME `IconDesc`, because an atlas is exactly the
"path + normalized sub-rect" that struct already carries for a `|T` span with
texcoords. A `height`/`width` of `0` resolves to the atlas's own pixel size at
PARSE time (not the line font height `|T` falls back to), which is what keeps the
rest of the pipeline marker-agnostic. Tiling atlases draw one quad, so
`tilesHorizontally` / `tilesVertically` are not honored here.
Adding any further marker means touching `IconStartLen`, `FindIconClose`,
`InlineSpanLen`, the ghost guard in `FlushLayout` — and, mandatory,
`chat/IconFilter.cpp`, or the marker becomes a chat-spoof vector.
FileDataID paths are Legion+ — 1.12 resolves texture PATH strings only.
## Confirmed: 1.12 has ZERO inline-texture support
In-game test on the target client — all of these render as literal text, no
icon:
```
|TInterface\Icons\INV_Misc_Coin_01:16|t
|TInterface\Icons\INV_Misc_Coin_01:16:16|t
|TInterface\Icons\INV_Misc_Coin_01:16:16:0:0|t
```
Root cause (see 1.12 map below): the shared escape tokenizer has no `T`/`t`
case, so `|T` falls through to "literal `|` + ordinary glyphs".
## Reference: 4.3.4 (`C:\WoW\Proudmoore\apwow.exe`, build 15595)
4.3.4's text pipeline is a shared `|`-tokenizer feeding per-purpose loops that
`switch` on the returned token type. It DOES support `|T`.
- **Tokenizer `FUN_00613980`** — reads one token, returns a type code, bytes
consumed (`*param2`), payload char (`*param5`). `|`-switch token types:
`1`=color(`|c`+8 hex), `2`=reset(`|r`), `3`=break(`|n`/newline), `4`=`||`,
`5`=`|H`, `6`=`|h`, **`7`=texture(`|T`…`|t`)**, `8`=`|t`, `9`/`10`=`|K`/`|k`
callback, `0xb`/`0xc`=`|W`/`|w`, `0`=ordinary glyph. The `T` case scans
forward to the closing `|t` and returns 7 with the whole span's byte length.
- **Field parser `FUN_00617ba0(tokenStart, &desc, size)`** — splits the `|T`
payload on `:` (helpers: `FUN_0040fa50`=strchr, `FUN_004b3d00`=atof,
`FUN_004b3480`=atoi) into a **0x40-byte descriptor**:
| off | field |
|----|-------|
| `+0x10`/`+0x14` | path ptr / length (up to first `:`) |
| `+0x18` | height (font-scaled) — required |
| `+0x1C` | width (defaults to height) |
| `+0x20`/`+0x24` | offsetX / offsetY |
| `+0x28`–`+0x34` | 4 normalized texcoords (texel ÷ texW/texH) |
| `+0x3C` | hasTexCoords flag |
| `+0x38`–`+0x3B` | vertex B/G/R/A |
| `+0x3D` | hasColor flag |
- **Measure loop `FUN_00618430`** — walks tokens; `case 7` calls
`FUN_00617ba0` and adds the texture width to the pen.
- **Draw emitter `FUN_0061ea10`** (analog of 1.12 `FUN_005ccbe0`) — its
`case 7` is the texture draw:
1. `FUN_00617ba0(tokenStart, &desc)` — parse fields into the descriptor
(stored inline on the line-state struct at `param7+0xb`, 0x10 dwords).
2. Compute pen x, width (`desc.width[+0x18 dword = param7[0x12]] * scale`),
and y from the justify mode `[obj+0x58]` (0=baseline, 1=center, 2=top).
3. Copy the descriptor to a stack struct and call **`FUN_0061e820`** — the
inline-texture quad emit. (`FUN_0061dd50` handles a region-state 1→2
transition when a texture interrupts a hyperlink capture.)
- **`FUN_0061e820`** — normalizes the 4 quad corners (÷ screen w/h from
`DAT_00dd9ea0`/`DAT_00dd9ea4`) and calls `FUN_0061e410(1, &verts)`.
- **`FUN_0061e410(count=1, &verts)`** (`__thiscall`, ECX = a vertex-buffer
object) — appends `count` quads of **0x40 bytes** (one quad = pos + texcoords)
to a **dedicated inline-texture vertex buffer**, growing it as needed
(`FUN_0061db40`). So inline textures accumulate in their OWN batch, separate
from the per-font-page glyph batches, each quad carrying its own texture
(bound at flush). This is the concrete confirmation of the "separate quad
path" — the backport must add such a batch + flush on the 1.12 side.
## Target: 1.12 (`C:\WoW\Octo\WoW.exe`, build 5875) injection map
Same architecture as 4.3.4, different addresses and token numbering. Reached
from `Script_GetStringWidth` (`FUN_0079e510`) → `FUN_00772890` →
`FUN_0044d670` → `FUN_005c2050` → the loops.
- **Shared tokenizer `FUN_005c2810`** — `~11 callers`. `|`-switch token types:
`0`=color(`|c`), `1`=reset(`|r`), `2`=break(`|n`/newline), `3`=`||`,
`4`=`|H`, `5`=`|h`, `6`=ordinary glyph. **No `T`/`t` case** → `|T` hits the
fall-through (`*param5=0x7c; return 6`) = literal `|` then glyphs. Adding a
texture token means picking an unused code (e.g. `7`).
- **Measure loop `FUN_005c6940`** — `switch`: `0/1/4/5` zero-width, `2` break,
default glyph (advance via `FUN_005c6b70`; kerning `FUN_005ca2d0`/
`FUN_005ca4b0`). No texture case.
- **Fit/width loops** `FUN_005c6c50` (chars-into-width + per-char x, for
cursor/wrap) and `FUN_005c7470` (truncation/ellipsis). Same switch shape.
- **Draw builder `FUN_005cdc20`** — reads the layout object's text at `[+0x48]`,
handles line-wrap / justify (`[+0x54]`) / color state, per line calls the
glyph emitter and `FUN_005cd310` (hyperlink rect registration).
- **Glyph emitter `FUN_005ccbe0`** — the real quad emitter. Per glyph:
`FUN_005cabd0(fontFace,char)` → glyph record (atlas **page** at `rec[10]`,
advance `rec[0x12]`, texcoords `rec[0x18..0x1b]`), then appends 4 verts to a
**per-atlas-page** batch at `[obj + page*4 + 0xa0]`. `case 0/1` set/reset
color, `4/5` open/close hyperlink region, default = glyph.
### The architectural wrinkle
Glyph quads batch **per font-atlas page**. An inline `|T` texture is an
arbitrary texture, not a font page, so it cannot join that batch — it needs a
**separate textured-quad draw** (its own draw call, correctly ordered against
the glyph batches so it appears inline). This is the substantive work, not the
tokenizing. 4.3.4 solves it exactly this way — captured below: its draw `case 7`
appends the quad to a dedicated inline-texture vertex buffer at
`renderObject+0x9c`, separate from the per-font-page glyph batches (see the
`FUN_0061ea10` / `FUN_0061e820` items under Open items).
## Strategy
The tokenizer is shared by ~11 callers, so DON'T just make it return a new
type — the other callers' `switch`es would hit `default` and mis-handle it.
Instead:
1. **Reimplement (co-hook) the measure loop `FUN_005c6940` and the draw
builder `FUN_005cdc20`/emitter `FUN_005ccbe0`** — copy existing logic
(fully decompiled), delegate every non-texture token to the original
handling, and add an inline `|T…|t` case: measure → advance pen by texture
width; draw → emit the arbitrary-texture quad.
2. **Port `FUN_00617ba0`** (field parse → 0x40 descriptor). Standalone, safe to
write now from the 4.3.4 decompilation; needs 1.12 equivalents of strchr/
atof/atoi (trivial or already in `Offsets.h`).
3. **Leave the shared tokenizer `FUN_005c2810` and the other ~9 callers
untouched** — they keep rendering `|T` literally (wrap/cursor math slightly
off inside a texture in v1 — cosmetic, extend later).
4. **Texture load by path** — reuse the engine's `Texture:SetTexture` loader;
**quad emit** — the primitive 4.3.4's draw case uses (to pin).
Risk: the hot text path (every string every frame). But these are
deterministic C functions, NOT the contended nampower/SuperWoW targets, so the
MinHook-collision concern is low. Reimplementing two complex loops faithfully
is the real cost.
## Incremental slices
1. Fixed-size `|Tpath:height|t` — render + width only (ignore width/offset/
texcoord/color). Proves the end-to-end quad path.
2. width, offsetX/Y.
3. texcoords (`texW:texH:l:r:t:b`).
4. vertex color.
5. correct wrap/cursor (extend `FUN_005c6c50`/`FUN_005c7470`).
## Open items / next steps
- [x] **4.3.4 draw-side `case 7`** — captured: `FUN_0061ea10` case 7 →
`FUN_00617ba0` (parse) + `FUN_0061e820`→`FUN_0061e410` (append quad to a
dedicated inline-texture vertex buffer). Separate batch, per-quad texture.
- [x] **4.3.4 inline-texture buffer located** — `FUN_0061e820` (`RET 0x40`,
i.e. a 0x40-byte quad struct by value) does `ADD ECX,0x9c` before
`FUN_0061e410`, so the dedicated inline-texture vertex buffer is at
**renderObject+0x9c** (glyph batches are the `+0xa0 + page*4` array — the
two are adjacent but distinct). Quad struct: positions at `+0x8..+0x14`,
texcoords at `+0x20..+0x2c` (rest = z / texture handle / color). Appended
one quad at a time via `FUN_0061e410(this=buf@+0x9c, count, &quad)`.
- [x] **Flush + path→texture load** — NOT traced on the 4.3.4 side by design;
its purpose (the flush + per-quad texture bind + path→load mechanism) is
fully answered on the **1.12 side** below: paint/flush `FUN_005c8fe0`,
bind `FUN_00589e80(0x17,tex)` + draw `FUN_005c8f40`, load `FUN_00449d90`.
4.3.4's own `+0x9c`-buffer flush is not needed — we implement against 1.12.
- [x] **1.12 path→texture loader** — `FUN_00770200(textureObj, path, flag,
blend=DAT_00878cf0, flag)`. It's the string-path branch of
`Script_Texture_SetTexture` (`FUN_0079bb40`, method-table entry at
`0x0087c1a0`). This is how a `|T` path becomes a bound texture.
- [x] **1.12 batch render + textured-quad GPU primitive — FOUND.** The paint
pass is `FUN_005c8fe0(layoutObj)`: it ensures each line built
(`FUN_005cd6a0`), then per font page (stride 0x18, indices 0..7 over
`[obj+0x18c+page*0x18]` = the page's texture object) does:
- **bind texture:** `FUN_00589e80(0x17, texturePage)` (0x17 = the texture
render-state selector),
- **lock dynamic VB:** `FUN_0058a140(0, stride=0x18, 0x800)` → handle;
`FUN_0058a080(handle)` → vertex data ptr,
- copy the page's built verts from the per-page batch at
`[lineObj + 0xa0 + page*4]` (`FUN_005ce090`=count, `FUN_005ce0c0`=copy),
- **draw:** `FUN_005c8f40(&handle, vertCount)` (flush/submit),
- **unlock:** `FUN_0058a0a0(handle, 0)`.
**Vertex stride = 0x18** (24 bytes = pos + uv + packed color). So an inline
`|T` quad = 4 (or 6) such verts, bound to its own texture. Reuse path for
the `|T` draw: `FUN_00589e80(0x17, inlineTex)` → write quad verts →
`FUN_005c8f40`. **`FUN_005c8fe0` is the co-hook site for strategy B** —
after the glyph batches are drawn, draw the frame's collected `|T` quads.
- [x] **Path → bindable texture handle — RESOLVED.** `FUN_00770200`
(SetTexture-by-path) internally calls **`FUN_00449d90(path, &desc, flags,
0, 1)`** — the general path→CGxTexture loader (normalizes path, by-name
cache, creates on miss via `FUN_0044a140`/`FUN_0044a310`, returns a
**fallback texture on failure so never null**) — and stores the handle at
`textureObj+0xcc`. That handle is the SAME CGxTexture type
`FUN_00589e80(0x17, tex)` binds (the `tex[0x3c]` streamable flag +
non-null `*tex` that `FUN_00593840` checks are CGxTexture fields; font
pages and Texture widgets bind identically). So a `|T` draws as:
`tex = FUN_00449d90(path,&desc,flags,0,1)` → `FUN_00589e80(0x17,tex)` →
write 4 verts (stride 0x18) → `FUN_005c8f40(&vb,n)`. No scratch widget
needed if we replicate `FUN_00770200`'s descriptor setup
(`FUN_0058a980(&desc, blend, …)` then `FUN_00449d90`); or, simplest, keep
one scratch Texture object, `FUN_00770200(scratch,path,…)`, read
`[scratch+0xcc]`. The internal by-name cache makes repeats cheap.
Two implementation strategies once the primitive is pinned:
- **A (mirror 4.3.4):** own a separate inline-texture vertex buffer, flush it
in the paint pass alongside the glyph batches. Faithful, more integration.
- **B (immediate):** at paint time, draw each collected `|T` quad immediately
via the GxU primitive (bind `FUN_00770200`'d texture, draw one quad). Simpler;
inline textures are few, so per-quad draw calls are fine. Likely the better
first cut.
- [ ] Confirm 1.12's tokenizer flag bits (`param4 & 0x100/0x200/0x400/0x800`)
that gate color/escape handling, so the reimplemented loops pass them
through unchanged.
## Reality check on scope — how it actually landed
The plan above feared reimplementing 1.12's glyph emitter `FUN_005ccbe0` (a
long, intricate function) and the measure loop. It did not come to that. The
shipped design avoids both:
- **Positioning** does NOT reimplement the emitter — it SEGMENTS the line at
icon boundaries and delegates each plain run to the ORIGINAL emitter, so the
engine still lays out every glyph. We only track where the icons go.
- **Rendering** does NOT stand up a separate quad batch — icons are
engine-managed regions anchored to their FontString (the removed quad batch
was strategy B; regions replaced it).
- **Measure** does NOT reimplement the loops — three cold co-hooks on the
fs-level width / height / wrap functions add the icons' contribution and call
the originals.
The result is the largest feature in the project, but built from co-hooks that
delegate to the engine rather than from reimplemented layout code. It was
verified by in-game iteration over many build/test rounds, as expected.
+115
View File
@@ -0,0 +1,115 @@
# Why inline icons render as engine regions
Inline `|T…|t` icons render as pooled `CSimpleTexture` regions
([src/text/InlineTexturePool.cpp](../src/text/InlineTexturePool.cpp)) — one per
visible icon, anchored to the icon's owning FontString. The engine draws each
region every frame like any UI texture, so the icon is resident by construction
and moves with its line for free. This is 4.3.4's `CSimpleEmbeddedTexture`
model, built from the parts 1.12 ships.
This file records why that design was chosen and the RE behind it. A raw-GxU-
quad renderer came first and was removed (`56c2670`).
## History — a residency misdiagnosis, corrected
The quad renderer flickered: a random subset of chat icons blanked on scroll,
and a second client showed no icons at all. The first diagnosis was **texture
residency** — the theory that a raw quad bound a texture the VRAM manager had
evicted, because a raw quad is owned by no frame object.
That diagnosis was wrong. The real cause was the Large-Address-Aware pointer
bound (`dc61f77`): a 2GB cap in the flush's `LooksReadable` check rejected valid
heap pointers above `0x80000000`, and the flush's node walk BREAKS on a rejected
node. So one high node truncated the walk, and every node after it lost its
icon. That is the "random subset blanks" pattern, and a second client shows none
because it grows the heap past 2GB sooner. With the bound fixed, the raw quads
did not flicker either.
So engine regions are kept for **4.3.4 parity**, not necessity. They are
resident by construction, which closes the residency question for good — but the
question was never the real bug. Do not re-open the residency investigation; the
D3D notes at the end are the record of what was ruled out.
## The region the pool builds
1.12 ships `CSimpleTexture` — the ordinary `Texture` widget
(`frame:CreateTexture()`). It is a managed, reference-counted, `CGxTexCache`-
backed, engine-drawn texture. The only thing 3.3.5's `CSimpleEmbeddedTexture`
adds is automatic inline layout inside the FontString, and the emitter already
computes the icon positions — so the pool supplies them. (`CSimpleEmbeddedTexture`
is compiled into 3.3.5 only; RTTI confirms it is absent from 1.12.)
Per icon, the pool takes a pooled region and sets the texture, texcoords,
colour, and two anchor points relative to the owning FontString's bottom-left.
The engine then owns load, residency, managed-pool reload, clipping, and draw.
### 1.12 entry points (used by the pool)
RTTI name strings: `.?AVCSimpleTexture@@` @ `0x00846588`,
`.?AVCSimpleFontString@@` @ `0x00846544`.
Create a `CSimpleTexture` from C (mirrors `Tooltip::LinePool`'s FontString path):
```
void* mem = FUN_00760450(&DAT_00cf4ce0, 0, /*rtti*/0x00846588, 0xFFFFFFFE); // pool alloc
void* tex = FUN_0076fc40(mem, parentFrame, /*drawLayer*/2, /*sublayer*/1); // ctor
```
Set the texture path (loads through the engine's own loader, owns the handle):
```
FUN_00770200(tex, path, 0, DAT_00878cf0, 0); // CSimpleTexture::SetTexture(path)
```
`FUN_00770200` builds GxTexFlags (`FUN_0058a980`), loads via `FUN_00449d90`,
stores the HTEXTURE at `tex+0xCC` (owned ref), releases the old one
(`FUN_0041aed0`), and marks the region dirty. This ownership is the whole
residency story — the engine holds the texture and reloads it on eviction.
Region methods the pool calls directly:
| method | C++ target |
|---|---|
| SetTexCoord | `FUN_00770410(tex, &{v0,u0,v1,u1})` — Y-FIRST interleaved |
| SetColor | `FUN_0077F750(tex, &BGRA)` — also the chat-fade alpha mirror |
| SetPoint | `FUN_00767C70` — internal units (see LinePool `PixelToInternal`) |
| Show / Hide | `FUN_0077FCB0` / `FUN_0077FC60` (desired-shown `+0xC4`, realized `+0xC8`) |
`CSimpleTexture` layout (from ctor `FUN_0076fc40`): vtable `0x0081c718`;
region-render vtable at `+0x24`; HTEXTURE `+0xCC`; blend `+0xD0`; per-corner
quad position/texcoord arrays `+0xD4..+0x100` (`OFF_SIMPLETEXTURE_CORNERS`);
`+0x128` a flag. The region-render vtable slot 0 (`0x00770670`) computes the
screen rect and calls `FUN_007705b0` to STORE the quad corners; the GPU draw is
deferred to the engine's batched region paint.
## The pen↔anchor bridge
The emitter computes icon positions in PEN units; the pool stores region
`SetPoint` offsets in ANCHOR units, relative to the FontString's rect. The
bridge is one scale `K` (pen units per anchor unit) plus the FontString's own
rect: the flush reads the FontString rect and derives `K` per node, converts
each icon's screen rect to FontString-relative anchor offsets, and queues that.
The pool applies the queued placement on the next frame tick — never mid-render.
`K` derivation and the FontString-relative store are in `FlushLayout`
([src/text/InlineTexture.cpp](../src/text/InlineTexture.cpp)); the
convergence pass in `Maintain`
([src/text/InlineTexturePool.cpp](../src/text/InlineTexturePool.cpp)) self-heals
any residual scale from the region's own frame-scale chain.
## What was ruled out during the residency chase (do not re-investigate)
The blank icons had zero CPU-side signature — records present, node chain
contiguous, geometry sane, index buffer ready at submit, batched draw, z-buffer
excluded twice. The full D3D9 render state at the true draw point was benign:
`zFunc=8` always, `aBlend=1`, `colorW=0xF`, scissor and stencil off, texture
stage MODULATE with a valid bound texture every draw. All of this was consistent
with the LAA-bound truncation (the node never reached the draw), not with a lost
texture surface.
D3D9 device access, if it is ever needed again:
- `IDirect3DDevice9* = *(void**)(*(void**)0x00C0ED38 + 0x38a8)` (CGxDeviceD3d).
- `GetRenderState` = device vtable `+0xE8`; `SetRenderState` `+0xE4`.
- The GxU re-applies its cached render states before every draw (`FUN_005a1b20`),
so a raw `SetRenderState` for a GxU-managed state is overwritten; `ZENABLE` is
not in that path, so a direct set survives.
+5 -3
View File
@@ -178,9 +178,9 @@ behaviour the comment describes (`push 0; mov edx, 1; mov ecx, L`) is
| `0x006F4450` | `lua_next` | fastcall | calls `luaH_next` at `0x006FA2A0` | ★ |
| `0x006F44E0` | `lua_concat` | fastcall | calls `luaV_concat` at `0x006F84D0` | ★ |
| `0x006F4560` | `lua_newuserdata` | fastcall | tag 7; calls `luaS_newudata` at `0x006F9E30` | ★ |
| `0x006F45B0` | `lua_getupvalue` | fastcall | reads upvalue from C closure | ◦ |
| `0x006F4660` | `lua_setupvalue` | fastcall | | ◦ |
| `0x006F46E0` | *internal upvalue helper*| | shared by get/set above | ◦ |
| `0x006F45B0` | `lua_pushupvalues` | fastcall | pushes the running C closure's upvalues, returns how many | ★ |
| `0x006F4660` | `lua_getupvalue` | fastcall | `(L, funcindex, n)`: pushes upvalue n, returns its name or null | ★ |
| `0x006F46E0` | `aux_upvalue` | | finds upvalue n of a function, returns its name | ★ |
## Auxiliary library (`luaL_*`)
@@ -213,6 +213,8 @@ filenames in Lua 5.0 by behaviour.
|--------------|--------------------------|---------------------------------------------------|
| `0x006F3140` | `setobj` / TValue copy | 16-byte memcpy |
| `0x006F58B0` | `equalobj` | called by `lua_equal` |
| `0x006F6050` | `luaD_precall` | frame setup for a call; Lua closure: reads Proto (`+0xc` of the closure), `is_vararg` at Proto `+0x46` → `adjust_varargs`, `numparams` `+0x45`, `maxstacksize` `+0x47`; C closure: reserves 0x14 slots and calls the C function |
| `0x006F6200` | `adjust_varargs` | stock 5.0: pads missing fixed params with nil, then `luaH_new(L, nvar, 1)` + `luaH_setnum` per extra arg + sets field `"n"` and pushes the table. So EVERY call to a vararg Lua function allocates one table, whether the body uses `arg` or `...` — keep vararg helpers off per-frame paths |
| `0x006F65A0` | `luaD_call` | the actual call dispatcher |
| `0x006F6960` | `luaD_pcall` | protected call dispatcher |
| `0x006F7340` | `luaD_growstack` (or checkstack) | invoked when stack needs space |
+38
View File
@@ -1259,4 +1259,42 @@
2: 0x00706040 CreateFont
3: 0x007060B0 CreateFrame
=== luaL_openlib base library Table 0x00811E28 Count=36 (not a FrameScript_RegisterFunction batch; see BlizzardScriptAPI.md §3) ===
0: 0x00702770 setglobal
1: 0x007027B0 getglobal
2: 0x007027E0 debugload
3: 0x007027F0 debuginfo
4: 0x00702800 debugprint
5: 0x00702810 debugdump
6: 0x00702820 debugbreak
7: 0x00702830 debugtimestamp
8: 0x00702840 debugprofilestart
9: 0x00702860 debugprofilestop
10: 0x00702900 seterrorhandler
11: 0x00702950 geterrorhandler
12: 0x00702970 error
13: 0x007029F0 getmetatable
14: 0x00702A40 setmetatable
15: 0x00702AC0 getfenv
16: 0x00702BE0 setfenv
17: 0x00702C90 next
18: 0x00702CD0 ipairs
19: 0x00702DA0 pairs
20: 0x00702DF0 type
21: 0x00702E30 tonumber
22: 0x00702F40 tostring
23: 0x007030A0 unpack
24: 0x007030F0 rawequal
25: 0x00703130 rawget
26: 0x00703160 rawset
27: 0x007031A0 assert
28: 0x00703200 gcinfo
29: 0x00703250 collectgarbage
30: 0x00703280 loadstring
31: 0x007032F0 pcall
32: 0x00703340 xpcall
33: 0x007033A0 date
34: 0x007035A0 time
35: 0x00703760 debugstack
Vendored Submodule
+1
+9
View File
@@ -0,0 +1,9 @@
; Exports for ClassicAPI.dll.
;
; `Load` is VanillaFixes' post-injection entry point: after the launcher
; injects each dlls.txt DLL, the VanillaFixes runtime calls the DLL's `Load`
; export on the game's MAIN thread (GetProcAddress(module, "Load")), outside
; the loader lock and with no timeout. Listing it here exports it undecorated
; as "Load" so GetProcAddress finds it regardless of calling convention.
EXPORTS
Load
+98
View File
@@ -14,6 +14,7 @@
#include "Common.h"
#include <cstring>
#include <string>
#include <windows.h>
namespace Common {
@@ -31,4 +32,101 @@ bool PatchBytes(void *dst, const void *src, size_t len) {
return true;
}
bool RedirectCall(uintptr_t site, uintptr_t expected, const void *target) {
const auto *code = reinterpret_cast<const uint8_t *>(site);
if (code[0] != 0xE8)
return false;
const auto callee = [site](int32_t rel) { return site + 5 + static_cast<uintptr_t>(rel); };
int32_t rel = 0;
std::memcpy(&rel, code + 1, sizeof rel);
const uintptr_t to = reinterpret_cast<uintptr_t>(target);
if (callee(rel) == to)
return true;
if (callee(rel) != expected)
return false;
rel = static_cast<int32_t>(to - (site + 5));
return PatchBytes(reinterpret_cast<uint8_t *>(site) + 1, &rel, sizeof rel);
}
bool RedirectJcc(uintptr_t site, uintptr_t expected, const void *target) {
const auto *code = reinterpret_cast<const uint8_t *>(site);
if (code[0] != 0x0F || (code[1] & 0xF0) != 0x80)
return false;
const auto dest = [site](int32_t rel) { return site + 6 + static_cast<uintptr_t>(rel); };
int32_t rel = 0;
std::memcpy(&rel, code + 2, sizeof rel);
const uintptr_t to = reinterpret_cast<uintptr_t>(target);
if (dest(rel) == to)
return true;
if (dest(rel) != expected)
return false;
rel = static_cast<int32_t>(to - (site + 6));
return PatchBytes(reinterpret_cast<uint8_t *>(site) + 2, &rel, sizeof rel);
}
bool RedirectSlot(uintptr_t slot, uintptr_t expected, const void *target) {
uintptr_t current = 0;
std::memcpy(&current, reinterpret_cast<const void *>(slot), sizeof current);
const uintptr_t to = reinterpret_cast<uintptr_t>(target);
if (current == to)
return true;
if (current != expected)
return false;
return PatchBytes(reinterpret_cast<void *>(slot), &to, sizeof to);
}
bool ReplaceWithCall(uintptr_t site, const uint8_t *original, size_t len, const void *target) {
uint8_t code[64];
if (len < 5 || len > sizeof code)
return false;
code[0] = 0xE8;
const int32_t rel = static_cast<int32_t>(reinterpret_cast<uintptr_t>(target) - (site + 5));
std::memcpy(code + 1, &rel, sizeof rel);
std::memset(code + 5, 0x90, len - 5);
const void *at = reinterpret_cast<const void *>(site);
if (std::memcmp(at, code, len) == 0)
return true;
if (std::memcmp(at, original, len) != 0)
return false;
return PatchBytes(reinterpret_cast<void *>(site), code, len);
}
void BoundedCopy(char *dst, const char *src, size_t n) {
if (dst == nullptr || n == 0)
return;
size_t i = 0;
for (; src != nullptr && src[i] != '\0' && i + 1 < n; ++i)
dst[i] = src[i];
dst[i] = '\0';
}
void EnsureParentDirs(const char *relPath) {
std::string accum;
for (const char *p = relPath; *p != '\0'; ++p) {
if (*p == '\\' || *p == '/') {
if (!accum.empty())
CreateDirectoryA(accum.c_str(), nullptr);
accum.push_back('\\');
} else {
accum.push_back(*p);
}
}
}
char FoldPathChar(char c) {
if (c == '/')
return '\\';
if (c >= 'A' && c <= 'Z')
return static_cast<char>(c + ('a' - 'A'));
return c;
}
bool SamePath(const char *a, const char *b) {
for (; FoldPathChar(*a) == FoldPathChar(*b); ++a, ++b) {
if (*a == '\0')
return true;
}
return false;
}
} // namespace Common
+41 -20
View File
@@ -11,28 +11,49 @@
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
#include <cstddef>
#include <cstdint>
namespace Common {
#define HOOK_FUNCTION(offset, hook, original) \
{ \
auto *target = reinterpret_cast<LPVOID>(offset); \
if (MH_CreateHook(target, reinterpret_cast<LPVOID>(hook), \
reinterpret_cast<LPVOID *>(&original)) != MH_OK) \
return FALSE; \
if (MH_EnableHook(target) != MH_OK) \
return FALSE; \
}
#define UNHOOK_FUNCTION(offset, original) \
{ \
auto *target = reinterpret_cast<LPVOID>(offset); \
if (MH_DisableHook(target) != MH_OK) \
return FALSE; \
if (MH_RemoveHook(target) != MH_OK) \
return FALSE; \
(original) = nullptr; \
}
bool PatchBytes(void *dst, const void *src, size_t len);
// Points the `E8 rel32` call at `site` to `target` when it still calls
// `expected`; true when the call now reaches `target`. A call that reaches
// anything else (another DLL's patch, a different build) is left alone.
// Idempotent, so it can run on every registration pass.
bool RedirectCall(uintptr_t site, uintptr_t expected, const void *target);
// RedirectCall for a `0F 8x rel32` conditional jump: points the taken branch
// at `site` to `target` when it still reaches `expected`. Same contract.
bool RedirectJcc(uintptr_t site, uintptr_t expected, const void *target);
// RedirectCall for a function-pointer slot (a vtable entry): points the slot
// at `slot` to `target` when it still holds `expected`. Same contract.
bool RedirectSlot(uintptr_t slot, uintptr_t expected, const void *target);
// Writes `call target` plus NOP padding over the `len` bytes (5 to 64) of
// code at `site` when they still hold `original`; true when the site
// now calls `target`. A site holding anything else (another DLL's patch, a
// different build) is left alone. Idempotent, like RedirectCall.
bool ReplaceWithCall(uintptr_t site, const uint8_t *original, size_t len, const void *target);
// Bounded, always-terminated string copy: writes at most `n - 1`
// characters plus the terminator, and treats a null `src` as empty. `n`
// is the size of `dst`. Stands in for `strncpy`, which MSVC deprecates
// (C4996) and which does not terminate on truncation.
void BoundedCopy(char *dst, const char *src, size_t n);
// Creates every parent directory of `relPath` (backslash- or slash-separated,
// e.g. "BlizzardInterfaceCode\FrameXML\Foo.lua"), relative to the working
// directory. Directories that already exist are a no-op.
void EnsureParentDirs(const char *relPath);
// `c` as game paths compare it: '/' as '\', and A-Z as a-z.
char FoldPathChar(char c);
// Whether `a` and `b` are the same game path: equal after FoldPathChar, so
// any case and either slash.
bool SamePath(const char *a, const char *b);
} // namespace Common
+184 -59
View File
@@ -15,9 +15,14 @@
#include "Game.h"
#include "MinHook.h"
#include "Offsets.h"
#include "config/CommandLine.h"
#include "config/FileSwitch.h"
#include "event/Custom.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"
static Game::FrameScript_Initialize_t FrameScript_Initialize_o = nullptr;
static Game::LoadScriptFunctions_t LoadScriptFunctions_o = nullptr;
@@ -33,24 +38,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();
// 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();
@@ -71,62 +69,189 @@ static void __fastcall LoadScriptFunctions_h() {
static void __stdcall LoadGlueScriptFunctions_h() {
LoadGlueScriptFunctions_o();
Game::RunGlueModuleRegistrations();
// World→glue teardown destroyed every world fontstring and text node the
// inline-icon maps reference; forget them now that the glue UI is booting.
// (Glue→world is covered by FrameScript_Initialize_h; the node-free hook
// handles individual deaths, but bulk teardown paths may bypass it.)
Text::InlineTexture::PrepareForReload();
Text::InlineTexturePool::PrepareForReload();
Texture::Transform::PrepareForReload();
Texture::Mask::PrepareForReload();
}
// Every Lua-side `frame:RegisterEvent(...)` is a chance to claim a slot
// for any custom event still waiting. By this point the engine's table
// is fully populated and SuperWoWhook / other DLLs have done their
// post-rebuild writes, so the table state is settled and our backwards
// walk finds genuine NULL slots near the tail.
// for any custom event still waiting. By the first FrameXML registration
// the engine's table is fully populated and SuperWoWhook / other DLLs have
// done their post-rebuild writes, so the walk from the low end finds
// genuinely free slots. A registration that arrives EARLIER (another DLL's
// frame, between LoadScriptFunctions and the table build — issue #134)
// still sees glue's 26-entry table; `RetryClaims` refuses that table and
// re-validates its cached slots against the live one on every call.
static void __fastcall FrameRegisterEvent_h(void *frame, void *edx,
const char *eventName) {
Event::Custom::RetryClaims();
// Throttled-internally; no-op when the cache or scan toggle is off.
Player::NameCache::Tick();
FrameRegisterEvent_o(frame, edx, eventName);
}
// ---------------------------------------------------------------------------
// Hook install — kept OFF the Windows loader lock.
//
// Every MH_EnableHook freezes all process threads (CreateToolhelp32Snapshot +
// SuspendThread/GetThreadContext each). Doing ~90 of those from DllMain, under
// the loader lock, is the pattern MinHook documents as unsafe: on machines
// whose security stack intercepts thread suspension it stalled the remote
// LoadLibrary thread past VanillaFixes' 10-second injection deadline, so VF
// read the still-running thread as STILL_ACTIVE (259) and showed its generic
// "compatible client" error — a false diagnosis of a slow load.
//
// So DllMain installs nothing. The install runs later, on a thread that does
// NOT hold the loader lock, via one of two triggers that both funnel through
// the latched EnsureInitialized():
// * VanillaFixes' `Load` export, called on the game's main thread after
// injection (the sanctioned VF extension point), or
// * a fallback worker thread we spawn from DllMain, ONLY when VanillaFixes
// is not the loader (no VfPatcher.dll in the process), for injectors that
// never call `Load`.
//
// The worker MUST stand down under VanillaFixes. VF creates the process
// suspended and injects every dlls.txt DLL sequentially via remote threads;
// a worker spawned from our DllMain starts the moment our own LoadLibrary
// releases the loader lock — i.e. while VF is still injecting the NEXT
// dlls.txt DLL. Its ~90-prologue install (plus the MH_ApplyQueued
// thread-freeze) then races that DLL's DllMain patching the same engine
// functions, which made SuperWoWhook.dll fail to load whenever ClassicAPI
// preceded it in dlls.txt. `Load` has no such race: VfPatcher calls it on the
// game's main thread after the process resumes, when every DllMain in the
// injection chain has already completed, serialized in dlls.txt order.
// ---------------------------------------------------------------------------
static volatile LONG g_initClaimed = 0; // 0 until a thread takes the installer role
static volatile LONG g_initDone = 0; // 0 until the install has finished
static volatile LONG g_initResult = 1; // 0 = success, 1 = failure (until proven)
static volatile LONG g_mhInitialized = 0; // MH_Initialize succeeded (gates detach teardown)
static bool CreateAndQueue(uintptr_t offset, void *hook, void **original) {
auto *target = reinterpret_cast<LPVOID>(offset);
if (MH_CreateHook(target, hook, original) != MH_OK)
return false;
// Queue only — a single MH_ApplyQueued below applies the whole batch in
// one thread-freeze.
if (MH_QueueEnableHook(target) != MH_OK)
return false;
return true;
}
static bool InstallHooks() {
if (MH_Initialize() != MH_OK)
return false;
InterlockedExchange(&g_mhInitialized, 1);
if (!CreateAndQueue(Offsets::FUN_INVALID_FUNCTION_PTR_CHECK,
reinterpret_cast<void *>(InvalidFunctionPtrCheck_h), nullptr))
return false;
// Four core init hooks — each runs glue logic (PrepareForReload,
// RunModuleRegistrations, RunGlueModuleRegistrations, EnableWrites,
// RetryClaims) tightly coupled to DllMain state, so a declarative
// HookAutoRegister wouldn't simplify them.
if (!CreateAndQueue(Offsets::FUN_FRAME_SCRIPT_INITIALIZE,
reinterpret_cast<void *>(FrameScript_Initialize_h),
reinterpret_cast<void **>(&FrameScript_Initialize_o)))
return false;
if (!CreateAndQueue(Offsets::FUN_LOAD_SCRIPT_FUNCTIONS,
reinterpret_cast<void *>(LoadScriptFunctions_h),
reinterpret_cast<void **>(&LoadScriptFunctions_o)))
return false;
if (!CreateAndQueue(Offsets::FUN_LOAD_GLUE_SCRIPT_FUNCTIONS,
reinterpret_cast<void *>(LoadGlueScriptFunctions_h),
reinterpret_cast<void **>(&LoadGlueScriptFunctions_o)))
return false;
if (!CreateAndQueue(Offsets::FUN_FRAME_REGISTER_EVENT,
reinterpret_cast<void *>(FrameRegisterEvent_h),
reinterpret_cast<void **>(&FrameRegisterEvent_o)))
return false;
// All feature hooks declared via `Game::HookAutoRegister` at file scope
// in their respective modules (create + queue-enable, no apply yet).
if (!Game::RunHookRegistrations())
return false;
// One thread-freeze that activates every queued hook at once.
return MH_ApplyQueued() == MH_OK;
}
// Runs InstallHooks exactly once. Returns 0 on success, 1 on failure. If a
// second caller arrives while the install is in flight, it blocks briefly so
// both callers observe the real result.
static DWORD EnsureInitialized() {
if (InterlockedCompareExchange(&g_initClaimed, 1, 0) == 0) {
g_initResult = InstallHooks() ? 0 : 1;
InterlockedExchange(&g_initDone, 1);
} else {
while (InterlockedCompareExchange(&g_initDone, 0, 0) == 0)
Sleep(1);
}
return static_cast<DWORD>(g_initResult);
}
static DWORD WINAPI InitWorker(LPVOID) {
EnsureInitialized();
return 0;
}
// VanillaFixes calls this on the game's MAIN thread after injection
// (InitAdditionalDLLs -> GetProcAddress(module, "Load")), outside the loader
// lock and with no timeout — the sanctioned VF extension point. Returns 0 on
// success; VF reports any non-zero result to the user. Exported undecorated
// as "Load" via src/ClassicAPI.def.
extern "C" DWORD Load() { return EnsureInitialized(); }
BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) {
if (reason == DLL_PROCESS_ATTACH) {
DisableThreadLibraryCalls(hModule);
if (MH_Initialize() != MH_OK)
return FALSE;
// The ONE thing that has to happen this early, and the only modules this
// file names directly. The engine parses its launch switches and reads
// its config file during boot, several calls before VanillaFixes invokes
// `Load`, so our switches cannot be wired from the normal install path.
// Each is a single rel32 store, not a hook, so it carries none of the
// loader-lock cost described above.
Config::CommandLine::Install();
Config::FileSwitch::Install();
auto *target = reinterpret_cast<LPVOID>(Offsets::FUN_INVALID_FUNCTION_PTR_CHECK);
if (MH_CreateHook(target, reinterpret_cast<LPVOID>(InvalidFunctionPtrCheck_h), nullptr) != MH_OK)
return FALSE;
if (MH_EnableHook(target) != MH_OK)
return FALSE;
// Four core init hooks stay here — each runs glue logic
// (PrepareForReload, RunModuleRegistrations,
// RunGlueModuleRegistrations, EnableWrites, RetryClaims)
// that's tightly coupled to DllMain state, so a declarative
// HookAutoRegister wouldn't simplify them.
HOOK_FUNCTION(Offsets::FUN_FRAME_SCRIPT_INITIALIZE, FrameScript_Initialize_h,
FrameScript_Initialize_o);
HOOK_FUNCTION(Offsets::FUN_LOAD_SCRIPT_FUNCTIONS, LoadScriptFunctions_h,
LoadScriptFunctions_o);
HOOK_FUNCTION(Offsets::FUN_LOAD_GLUE_SCRIPT_FUNCTIONS,
LoadGlueScriptFunctions_h, LoadGlueScriptFunctions_o);
HOOK_FUNCTION(Offsets::FUN_FRAME_REGISTER_EVENT, FrameRegisterEvent_h,
FrameRegisterEvent_o);
// All feature hooks declared via `Game::HookAutoRegister` at
// file scope in their respective modules.
if (!Game::RunHookRegistrations())
return FALSE;
// Install nothing here (loader lock — see the block comment above).
//
// Under VanillaFixes, `Load` is the ONLY install trigger. VfPatcher.dll
// is injected before any dlls.txt DLL, so its presence identifies VF as
// the loader; and the `Load` mechanism shipped in the same VF release
// (v1.4) as dlls.txt support itself, so any VF that loaded us will call
// it. Spawning the worker here would race the DllMains of the dlls.txt
// DLLs VF injects after us (see the block comment above).
if (GetModuleHandleW(L"VfPatcher.dll") == nullptr) {
// Any other injector: no `Load` caller exists, so install from a
// worker off the lock. The new thread cannot run its body until
// DllMain returns and the loader lock releases, and we never wait
// on it. DisableThreadLibraryCalls suppressed its THREAD_ATTACH.
HANDLE worker = CreateThread(nullptr, 0, InitWorker, nullptr, 0, nullptr);
if (worker != nullptr)
CloseHandle(worker);
}
} else if (reason == DLL_PROCESS_DETACH) {
// Clean /quit path. Flush before MH_Uninitialize — the cache's
// file I/O uses Win32 directly (no MinHook involvement), so
// either order works in practice, but flushing first lets us
// bail early if the hook teardown ever grows side effects.
// Hard process termination (task manager kill) bypasses this
// path; that's an inherent OS limitation, and the 5-minute
// backstop flush in Remember() covers the worst case there.
Player::NameCache::Flush();
MH_Uninitialize();
// Process exit — only tear down if we actually initialized. A
// clean /quit already saved the name cache from its atexit handler,
// which runs before this; this save covers an exit that skips the
// atexit handlers (Storm's fatal exit 0x0064CC80 calls ExitProcess
// itself) and a save that failed there. Save before
// MH_Uninitialize — the cache's file I/O uses Win32 directly (no
// MinHook involvement), so either order works in practice, but
// saving first lets us bail early if the hook teardown ever grows
// side effects. Hard process termination (task manager kill)
// bypasses this path; that's an inherent OS limitation, and the
// 5-minute backstop flush covers the worst case there.
if (g_mhInitialized) {
Player::NameCache::Shutdown();
MH_Uninitialize();
}
}
return TRUE;
}
+373 -57
View File
@@ -14,9 +14,43 @@
#include "Game.h"
#include "MinHook.h"
#include "Offsets.h"
#include "api/Documentation.h"
#include "compat/WowTurbo.h"
namespace Game {
void *ResolveUnitToken(const char *token) {
using ResolveUnitToken_t = void *(__fastcall *)(const char *token);
auto fn = reinterpret_cast<ResolveUnitToken_t>(Offsets::FUN_RESOLVE_UNIT_TOKEN);
return fn(token);
}
float PixelToInternal(float px) {
const float mul = Read<float>(Offsets::VAR_COORD_DDC_WIDTH_SCALE);
const float div = Read<float>(Offsets::VAR_COORD_ASPECT_COMPENSATION);
if (div == 0.0f)
return 0.0f;
return px * mul / (div * static_cast<float>(Offsets::UI_COORD_SCALE_UNIT));
}
double InternalToPixel(float internal) {
const float mul = Read<float>(Offsets::VAR_COORD_DDC_WIDTH_SCALE);
const float div = Read<float>(Offsets::VAR_COORD_ASPECT_COMPENSATION);
if (mul == 0.0f)
return 0.0;
return static_cast<double>(internal) * div * Offsets::UI_COORD_SCALE_UNIT / mul;
}
bool StringToFlag(const char *text) {
using StringToFlag_t = int(__fastcall *)(const char *text);
return reinterpret_cast<StringToFlag_t>(Offsets::FUN_XML_ATTR_TO_BOOL)(text) != 0;
}
int StrCmpI(const char *a, const char *b, int n) {
using SStrCmpI_t = int(__stdcall *)(const char *a, const char *b, int n);
return reinterpret_cast<SStrCmpI_t>(Offsets::FUN_SSTR_CMP_I)(a, b, n);
}
namespace Lua {
// Each entry binds a typed function pointer in `Game::Lua::` to the
// corresponding raw VA in `Offsets`. The X-macro keeps the column-aligned
@@ -38,25 +72,44 @@ namespace Lua {
F(NewTable, lua_newtable, LUA_NEW_TABLE) \
F(GetTable, lua_gettable, LUA_GET_TABLE) \
F(RawGet, lua_rawget, LUA_RAW_GET) \
F(RawGetI, lua_rawgeti, LUA_RAWGETI) \
F(RawSetI, lua_rawseti, LUA_RAW_SET_I) \
F(SetTable, lua_settable, LUA_SET_TABLE) \
F(RawSet, lua_rawset, LUA_RAW_SET) \
F(GetMetatable,lua_getmetatable,LUA_GET_METATABLE)\
F(SetMetatable,lua_setmetatable,LUA_SET_METATABLE)\
F(Insert, lua_insert, LUA_INSERT) \
F(Remove, lua_remove, LUA_REMOVE) \
F(Replace, lua_replace, LUA_REPLACE) \
F(GetTop, lua_gettop, LUA_GET_TOP) \
F(SetTop, lua_settop, LUA_SET_TOP) \
F(Call, lua_call, LUA_CALL) \
F(PCall, lua_pcall, LUA_PCALL) \
F(Next, lua_next, LUA_NEXT) \
F(Type, lua_type, LUA_TYPE) \
F(TypeName, lua_typename, LUA_TYPE_NAME) \
F(Error, lua_error, LUA_ERROR) \
F(ToPointer, lua_topointer, LUA_TO_POINTER) \
F(ToThread, lua_tothread, LUA_TO_THREAD) \
F(IsCFunction, lua_iscfunction, LUA_IS_C_FUNCTION)\
F(ToCFunction, lua_tocfunction, LUA_TO_C_FUNCTION)\
F(GetStack, lua_getstack, LUA_GET_STACK) \
F(GetInfo, lua_getinfo, LUA_GET_INFO) \
F(XMove, lua_xmove, LUA_X_MOVE) \
F(NewThread, lua_newthread, LUA_NEW_THREAD) \
F(Resume, lua_resume, LUA_RESUME) \
F(Yield, lua_yield, LUA_YIELD) \
F(ArgError, luaL_argerror, LUAL_ARG_ERROR)
F(ArgError, luaL_argerror, LUAL_ARG_ERROR) \
F(CheckLString,luaL_checklstring,LUAL_CHECK_LSTRING)\
F(CheckNumber, luaL_checknumber,LUAL_CHECK_NUMBER)\
F(OptNumber, luaL_optnumber, LUAL_OPT_NUMBER) \
F(SetN, luaL_setn, LUAL_SETN) \
F(Ref, luaL_ref, LUA_REF_REF) \
F(Unref, luaL_unref, LUA_REF_UNREF) \
F(CheckStack, lua_checkstack, LUA_CHECK_STACK) \
F(Concat, lua_concat, LUA_CONCAT) \
F(NewUserdata, lua_newuserdata, LUA_NEW_USERDATA) \
F(ToUserdata, lua_touserdata, FUN_FRAMESCRIPT_GET_OBJECT)
#define CLASSICAPI_BIND_LUA(Name, Typedef, Offset) \
const Typedef##_t Name = reinterpret_cast<Typedef##_t>(Offsets::Offset);
@@ -71,7 +124,7 @@ using RegisterFrameMethods_t = void(__fastcall *)(const FrameMethodEntry *table,
} // namespace
void *State() {
return *reinterpret_cast<void **>(static_cast<uintptr_t>(Offsets::VAR_LUA_STATE));
return Game::Read<void *>(Offsets::VAR_LUA_STATE);
}
namespace {
@@ -90,26 +143,120 @@ void *ResolveObject(void *L, int idx) {
return result;
}
void RegisterGlobalFunction(const char *name, CFunction func) {
auto fn = reinterpret_cast<FrameScript_RegisterFunction_t>(
Offsets::FUN_FRAMESCRIPT_REGISTER_FUNCTION);
fn(name, func);
int ObjectLuaRef(void *object) {
using ScriptRegister_t = void(__thiscall *)(void *object, void *nameOrNull);
if (Game::Read<int>(object, Offsets::OFF_COBJECT_LUA_REFCOUNT) == 0)
reinterpret_cast<ScriptRegister_t>(
Offsets::FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER)(object, nullptr);
return Game::Read<int>(object, Offsets::OFF_COBJECT_LUA_REF);
}
// Aliased to the same engine entry; the engine reads VAR_LUA_STATE
// internally to decide which state to write to, and the glue hook
// runs while that pointer is set to the glue state. Wrapped as a
// named function (rather than `using RegisterGlueFunction = ...`) so
// callers express intent at the call site.
void RegisterGlueFunction(const char *name, CFunction func) {
auto fn = reinterpret_cast<FrameScript_RegisterFunction_t>(
Offsets::FUN_FRAMESCRIPT_REGISTER_FUNCTION);
fn(name, func);
void PushObject(void *L, void *object) {
RawGetI(L, REGISTRY_INDEX, ObjectLuaRef(object));
}
void RegisterFrameMethods(void *context, const FrameMethodEntry *table, int count) {
auto fn = reinterpret_cast<RegisterFrameMethods_t>(Offsets::FUN_REGISTER_FRAME_METHODS);
fn(table, count, context);
bool ToFlag(void *L, int index, bool defaultValue) {
// Returns a full int in EAX on every path (Ghidra's `bool` is wrong).
using ToFlag_t = int(__fastcall *)(void *L, int index, int defaultValue);
return reinterpret_cast<ToFlag_t>(Offsets::FUN_LUA_TO_BOOLEAN_LOOSE)(L, index,
defaultValue ? 1 : 0) != 0;
}
const char *ObjectName(void *object) {
using GetName_t = const char *(__thiscall *)(void *);
const void *vtable = Game::Read<const void *>(object, 0);
return Game::Read<GetName_t>(vtable, Offsets::VTBL_SCRIPTOBJECT_GET_NAME)(object);
}
const char *ObjectDisplayName(void *object) {
const char *name = ObjectName(object);
return name != nullptr ? name
: reinterpret_cast<const char *>(Offsets::VAR_STR_UNNAMED);
}
namespace {
using FrameScriptIsA_t = char(__thiscall *)(void *self, int typeId);
const char *EngineString(uintptr_t address) {
return reinterpret_cast<const char *>(address);
}
// Shared body: the engine's prologue with N accepted type ids.
void *ResolveChecked(void *L, int idx, const uintptr_t *typeIdVars, int count,
bool raiseError) {
if (Type(L, idx) != TYPE_TABLE) {
if (raiseError)
Error(L, EngineString(Offsets::STR_FS_THIS_NON_TABLE));
return nullptr;
}
void *obj = ResolveObject(L, idx);
if (obj == nullptr) {
if (raiseError)
Error(L, EngineString(Offsets::STR_FS_THIS_NON_OBJECT));
return nullptr;
}
for (int i = 0; i < count; ++i) {
if (IsA(obj, typeIdVars[i]))
return obj;
}
if (raiseError)
Error(L, EngineString(Offsets::STR_FS_WRONG_OBJECT_TYPE));
return nullptr;
}
} // namespace
int FrameScriptTypeId(uintptr_t typeIdVar) {
auto &typeId = Game::Ref<int>(typeIdVar);
if (typeId == 0) {
auto &counter = Game::Ref<int>(Offsets::VAR_FRAMESCRIPT_TYPE_ID_COUNTER);
counter += 1;
typeId = counter;
}
return typeId;
}
bool IsA(void *object, uintptr_t typeIdVar) {
auto **vtable = *reinterpret_cast<void ***>(object);
auto isA = reinterpret_cast<FrameScriptIsA_t>(
vtable[Offsets::OFF_VMT_FRAMESCRIPT_ISA / sizeof(void *)]);
return isA(object, FrameScriptTypeId(typeIdVar)) != 0;
}
void *ResolveTypedObject(void *L, int idx, uintptr_t typeIdVar, bool raiseError) {
return ResolveChecked(L, idx, &typeIdVar, 1, raiseError);
}
void *ResolveTypedObjectAny(void *L, int idx, const uintptr_t *typeIdVars,
int count, bool raiseError) {
return ResolveChecked(L, idx, typeIdVars, count, raiseError);
}
void *ResolveTooltip(void *L, int idx, bool raiseError) {
return ResolveTypedObject(L, idx, Offsets::VAR_GAMETOOLTIP_LUA_TYPE_ID, raiseError);
}
void *ResolveFrame(void *L, int idx, bool raiseError) {
return ResolveTypedObject(L, idx, Offsets::VAR_FRAME_LUA_TYPE_ID, raiseError);
}
void *ResolveRegion(void *L, int idx, bool raiseError) {
return ResolveTypedObject(L, idx, Offsets::VAR_REGION_LUA_TYPE_ID, raiseError);
}
void *ResolveTexture(void *L, int idx, bool raiseError) {
return ResolveTypedObject(L, idx, Offsets::VAR_TEXTURE_LUA_TYPE_ID, raiseError);
}
void *ResolveFontString(void *L, int idx, bool raiseError) {
return ResolveTypedObject(L, idx, Offsets::VAR_FONTSTRING_LUA_TYPE_ID, raiseError);
}
void *ResolveEditBox(void *L, int idx, bool raiseError) {
return ResolveTypedObject(L, idx, Offsets::VAR_EDITBOX_LUA_TYPE_ID, raiseError);
}
void *ResolveModel(void *L, int idx, bool raiseError) {
return ResolveTypedObject(L, idx, Offsets::VAR_MODEL_LUA_TYPE_ID, raiseError);
}
void *ResolvePlayerModel(void *L, int idx, bool raiseError) {
return ResolveTypedObject(L, idx, Offsets::VAR_PLAYERMODEL_LUA_TYPE_ID, raiseError);
}
void *ResolveDressUpModel(void *L, int idx, bool raiseError) {
return ResolveTypedObject(L, idx, Offsets::VAR_DRESSUPMODEL_LUA_TYPE_ID, raiseError);
}
// Looks up `_G[name]`. If absent, creates a fresh table and binds it.
@@ -127,11 +274,110 @@ void EnsureGlobalTable(void *L, const char *name) {
Insert(L, -2); // [tbl, name, tbl]
SetTable(L, GLOBALS_INDEX); // _G[name] = tbl; pops k+v. [tbl]
}
// Same, one level down: ensures `parent[name]` is a table, with `parent`
// on top of the stack. Leaves `[parent, sub]`. Raw access, so a namespace
// carrying a metatable can't divert the read or the write.
void EnsureSubTable(void *L, const char *name) {
PushString(L, name); // [parent, name]
RawGet(L, -2); // [parent, parent[name]]
if (Type(L, -1) == TYPE_TABLE)
return;
SetTop(L, -2); // pop the non-table. [parent]
NewTable(L); // [parent, sub]
PushString(L, name); // [parent, sub, name]
PushValue(L, -2); // [parent, sub, name, sub]
RawSet(L, -4); // parent[name] = sub. [parent, sub]
}
// The escape-hatch namespace. Registering a name is not the same as owning
// it: the engine's registrars write `_G`, FrameXML and every addon load
// after that, and whoever writes last wins with no error and no way for the
// loser to notice. `GetServerTime` is the case on record — a client whose
// GameTime.lua declares its own replaced ours on every login.
//
// So every name the registrars below bind is also bound under
// `_G.ClassicAPI`, which nothing else writes. Two properties earn their
// keep, and both depend on doing this HERE rather than from Lua:
//
// - It runs at registration, so the mirror captures OUR function. A
// Lua-side `ClassicAPI.X = X` in the embedded addon would run after
// FrameXML and faithfully copy the clobbered version.
// - It mirrors by VALUE, reading the name back instead of making a
// second closure over the same C function. So `ClassicAPI.X == X`
// holds until something replaces the global, and the pair doubles as
// a clobber check for addons and for us.
//
// Not covered: frame methods (`obj:Method()` lives in the per-frame-type
// registry, not `_G`) and `RegisterIntegerEnum` values (a mirrored number
// is a copy, not a reference).
constexpr const char *kMirrorTable = "ClassicAPI";
void MirrorRegistration(const char *tableName, const char *name) {
void *L = State();
if (L == nullptr)
return;
const int top = GetTop(L);
// Read back whatever the registration actually bound.
if (tableName != nullptr) {
EnsureGlobalTable(L, tableName); // [src]
PushString(L, name); // [src, name]
RawGet(L, -2); // [src, value]
} else {
PushString(L, name); // [name]
GetTable(L, GLOBALS_INDEX); // [value]
}
if (Type(L, -1) != TYPE_FUNCTION) {
SetTop(L, top); // registration didn't land; nothing to mirror
return;
}
const int valueIdx = GetTop(L); // absolute, so the pushes below can't skew it
EnsureGlobalTable(L, kMirrorTable); // [..., mirror]
if (tableName != nullptr)
EnsureSubTable(L, tableName); // [..., mirror, sub]
PushString(L, name);
PushValue(L, valueIdx);
RawSet(L, -3); // target[name] = value
SetTop(L, top);
}
} // namespace
void RegisterGlobalFunction(const char *name, CFunction func, const Doc::Function *doc) {
auto fn = reinterpret_cast<FrameScript_RegisterFunction_t>(
Offsets::FUN_FRAMESCRIPT_REGISTER_FUNCTION);
fn(name, func);
MirrorRegistration(nullptr, name);
Api::Documentation::RecordGlobal(name, doc);
}
// Aliased to the same engine entry; the engine reads VAR_LUA_STATE
// internally to decide which state to write to, and the glue hook
// runs while that pointer is set to the glue state. Wrapped as a
// named function (rather than `using RegisterGlueFunction = ...`) so
// callers express intent at the call site.
void RegisterGlueFunction(const char *name, CFunction func, const Doc::Function *doc) {
auto fn = reinterpret_cast<FrameScript_RegisterFunction_t>(
Offsets::FUN_FRAMESCRIPT_REGISTER_FUNCTION);
fn(name, func);
// `State()` is the glue state here for the same reason the engine
// registrar writes there, so the mirror lands on the glue `_G`.
MirrorRegistration(nullptr, name);
Api::Documentation::RecordGlobal(name, doc);
}
void RegisterFrameMethods(void *context, ArrayRef<FrameMethodEntry> methods,
Doc::MethodList docs) {
auto fn = reinterpret_cast<RegisterFrameMethods_t>(Offsets::FUN_REGISTER_FRAME_METHODS);
fn(methods.data, methods.count, context);
Api::Documentation::RecordFrameMethods(context, methods, docs);
}
// Registers `func` at `_G[tableName][methodName]`. If the namespace
// doesn't already exist, creates an empty table for it.
void RegisterTableFunction(const char *tableName, const char *methodName, CFunction func) {
void RegisterTableFunction(const char *tableName, const char *methodName, CFunction func,
const Doc::Function *doc) {
void *L = State();
if (L == nullptr)
return;
@@ -140,13 +386,44 @@ void RegisterTableFunction(const char *tableName, const char *methodName, CFunct
PushCClosure(L, func, 0); // [tbl, methodName, closure]
SetTable(L, -3); // tbl[m]=c; pops k+v. [tbl]
SetTop(L, -2); // pop tbl. []
MirrorRegistration(tableName, methodName);
Api::Documentation::RecordTable(tableName, methodName, doc);
}
void RegisterIntegerEnum(const char *parent, const char *sub,
const EnumIntegerEntry *entries, int count) {
// `_G[alias] = _G[tableName][methodName]`, by VALUE. The engine binds its
// short aliases this way (`tinsert = tab.insert` in the compat snippet it
// runs at Lua init), so a module that registers over a library function has
// to re-bind the alias to the same closure — that keeps `tinsert ==
// table.insert` true, as the engine left it, instead of minting a second
// closure. A plain raw write, exactly what the snippet's assignment did. No-op
// if the source is not a function (nothing was registered to alias).
void RegisterGlobalAlias(const char *alias, const char *tableName, const char *methodName,
const Doc::Function *doc) {
void *L = State();
if (L == nullptr)
return;
const int top = GetTop(L);
EnsureGlobalTable(L, tableName); // [tbl]
PushString(L, methodName); // [tbl, m]
RawGet(L, -2); // [tbl, value]
if (Type(L, -1) != TYPE_FUNCTION) {
SetTop(L, top);
return;
}
PushString(L, alias); // [tbl, value, alias]
PushValue(L, -2); // [tbl, value, alias, value]
RawSet(L, GLOBALS_INDEX); // _G[alias] = value. [tbl, value]
SetTop(L, top);
MirrorRegistration(nullptr, alias);
Api::Documentation::RecordGlobal(alias, doc);
}
// `_G[parent][sub] = { entries }`, creating `_G[parent]` if needed.
static bool SetIntegerTable(const char *parent, const char *sub,
const EnumIntegerEntry *entries, int count) {
void *L = State();
if (L == nullptr)
return false;
EnsureGlobalTable(L, parent); // [parentTbl]
PushString(L, sub); // [parentTbl, subName]
NewTable(L); // [parentTbl, subName, subTbl]
@@ -157,6 +434,19 @@ void RegisterIntegerEnum(const char *parent, const char *sub,
}
SetTable(L, -3); // parentTbl[sub] = subTbl
SetTop(L, -2); // pop parentTbl
return true;
}
void RegisterIntegerEnum(const char *parent, const char *sub, ArrayRef<EnumIntegerEntry> entries,
const char *docSystem) {
if (SetIntegerTable(parent, sub, entries.data, entries.count))
Api::Documentation::RecordEnum(parent, sub, entries, docSystem);
}
void RegisterConstants(const char *sub, ArrayRef<EnumIntegerEntry> entries,
const char *docSystem) {
if (SetIntegerTable("Constants", sub, entries.data, entries.count))
Api::Documentation::RecordConstants(sub, entries, docSystem);
}
void SetFieldNumber(void *L, const char *key, double value) {
@@ -177,12 +467,45 @@ void SetFieldBool(void *L, const char *key, bool value) {
SetTable(L, -3);
}
void SetFieldNil(void *L, const char *key) {
PushString(L, key);
PushNil(L);
SetTable(L, -3);
}
void SetGlobalNumber(void *L, const char *name, double value) {
PushString(L, name);
PushNumber(L, value);
RawSet(L, GLOBALS_INDEX);
}
bool PushGlobalFunction(void *L, const char *name) {
PushString(L, name);
GetTable(L, GLOBALS_INDEX);
if (Type(L, -1) == TYPE_FUNCTION)
return true;
SetTop(L, -2); // pop the non-function
return false;
}
void CallGlobal(void *L, const char *name) {
const int top = GetTop(L);
if (PushGlobalFunction(L, name))
Call(L, 0, 0);
SetTop(L, top);
}
bool CallGlobalString(void *L, const char *name, const char *arg) {
const int top = GetTop(L);
const bool called = PushGlobalFunction(L, name);
if (called) {
PushString(L, arg);
Call(L, 1, 0);
}
SetTop(L, top);
return called;
}
void PushLocalizedString(void *L, const char *globalName, const char *fallback) {
PushString(L, globalName);
GetTable(L, GLOBALS_INDEX);
@@ -194,45 +517,14 @@ void PushLocalizedString(void *L, const char *globalName, const char *fallback)
}
}
// In-place `string.gsub(stack[-1], pattern, replacement)` — replaces
// the string at the top of the stack with the substitution result.
// Discards gsub's second return (the substitution count) by
// requesting only one return from `Call`.
static void GsubInPlace(void *L, const char *pattern, const char *replacement) {
PushString(L, "string");
GetTable(L, GLOBALS_INDEX);
PushString(L, "gsub");
GetTable(L, -2); // [..., str, string, gsub]
Remove(L, -2); // [..., str, gsub]
Insert(L, -2); // [..., gsub, str]
PushString(L, pattern);
PushString(L, replacement);
Call(L, 3, 1); // [..., result]
}
void PushLocalizedFormatInt(void *L, const char *globalName,
const char *fallback, int n) {
// Resolve `string.format` from _G.
PushString(L, "format");
GetTable(L, GLOBALS_INDEX);
PushLocalizedString(L, globalName, fallback);
// Expand WoW's `|4singular:plural;` (and 3-form
// `|4nom:gen_sing:plural;`) pluralization template by piggybacking
// on Lua's `string.gsub`. The 2- vs 3-form distinction is locale
// grammar (Slavic counting has a separate genitive-singular form
// for 2..4); we collapse to nominative/plural since vanilla has
// no proper locale-aware counting rules. 3-form pattern runs
// first because it's more specific. Vanilla's `string.format`
// doesn't process `|4` natively, so without this the template
// would render literally.
const char *picker3 = (n == 1) ? "%1" : "%3";
const char *picker2 = (n == 1) ? "%1" : "%2";
GsubInPlace(L, "|4([^:;]+):([^:;]+):([^;]+);", picker3);
GsubInPlace(L, "|4([^:;]+):([^;]+);", picker2);
PushNumber(L, static_cast<double>(n));
Call(L, 2, 1); // format(expandedFmt, n) → string
Call(L, 2, 1); // format(fmt, n) → string
}
} // namespace Lua
@@ -240,7 +532,7 @@ namespace Console {
namespace {
using RegisterCommand_t = int(__fastcall *)(const char *name, void *handler,
int category, const char *description);
using Write_t = void(__fastcall *)(const char *line, int colorFlag);
using Write_t = void(__fastcall *)(const char *line, int color);
} // namespace
void RegisterCommand(const char *name, CommandHandler handler, int category,
@@ -249,16 +541,20 @@ void RegisterCommand(const char *name, CommandHandler handler, int category,
fn(name, reinterpret_cast<void *>(handler), category, description);
}
void Write(const char *line) {
void Write(const char *line, Color color) {
auto fn = reinterpret_cast<Write_t>(Offsets::FUN_CONSOLE_WRITE);
fn(line, 0);
fn(line, color);
}
void(__cdecl *const Printf)(const char *format, ...) =
reinterpret_cast<void(__cdecl *)(const char *, ...)>(Offsets::FUN_CONSOLE_PRINTF);
} // namespace Console
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) {
@@ -266,8 +562,10 @@ ModuleAutoRegister::ModuleAutoRegister(Fn f) : fn(f), next(g_moduleHead) {
}
void RunModuleRegistrations() {
Api::Documentation::BeginPass(Api::Documentation::ENV_GAME);
for (auto *node = g_moduleHead; node != nullptr; node = node->next)
node->fn();
Api::Documentation::EndPass();
}
GlueModuleAutoRegister::GlueModuleAutoRegister(Fn f)
@@ -276,8 +574,19 @@ GlueModuleAutoRegister::GlueModuleAutoRegister(Fn f)
}
void RunGlueModuleRegistrations() {
Api::Documentation::BeginPass(Api::Documentation::ENV_GLUE);
for (auto *node = g_glueModuleHead; node != nullptr; node = node->next)
node->fn();
Api::Documentation::EndPass();
}
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)
@@ -288,10 +597,17 @@ HookAutoRegister::HookAutoRegister(uintptr_t target, void *hook, void **original
bool RunHookRegistrations() {
for (auto *node = g_hookHead; node != nullptr; node = node->next) {
auto *targetPtr = reinterpret_cast<LPVOID>(node->target);
// A hook must wrap the engine's body, not wow_turbo's reimplementation.
Compat::WowTurbo::Reclaim(node->target);
if (MH_CreateHook(targetPtr, node->hook,
reinterpret_cast<LPVOID *>(node->original)) != MH_OK)
return false;
if (MH_EnableHook(targetPtr) != MH_OK)
// Queue, don't enable. The caller (InstallHooks) applies every
// queued hook with a single MH_ApplyQueued, so all ~90 hooks share
// ONE thread-freeze instead of one freeze per hook. This is the
// difference that keeps install cheap on machines whose security
// stack intercepts SuspendThread / VirtualProtect per call.
if (MH_QueueEnableHook(targetPtr) != MH_OK)
return false;
}
return true;
+491 -29
View File
@@ -13,10 +13,89 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace Game {
// --- Typed engine-memory access ---------------------------------------------
//
// The canonical way to read/write an engine object field or a fixed-VA global,
// replacing the `*reinterpret_cast<const T *>(base + Offsets::OFF_X)` idiom
// (and its double-cast variant when `base` isn't a byte pointer). Offsets stay
// in Offsets.h per the single-source-of-truth rule — these only centralize the
// cast noise, they add no checking.
//
// Game::Read<int>(obj, Offsets::OFF_FIELD) field read
// Game::Ref<uint32_t>(obj, Offsets::OFF_FIELD) writable field lvalue
// Game::Ptr<float>(obj, Offsets::OFF_FIELD) pointer TO a field (arrays,
// out-params for engine calls)
// Game::Read<float>(Offsets::VAR_GLOBAL) fixed-VA global read
// Game::Ref<int>(Offsets::VAR_GLOBAL) fixed-VA global lvalue
template <typename T>
inline const T *Ptr(const void *base, uintptr_t offset) {
return reinterpret_cast<const T *>(reinterpret_cast<const uint8_t *>(base) + offset);
}
template <typename T>
inline T *Ptr(void *base, uintptr_t offset) {
return reinterpret_cast<T *>(reinterpret_cast<uint8_t *>(base) + offset);
}
template <typename T>
inline T Read(const void *base, uintptr_t offset) {
return *Ptr<T>(base, offset);
}
template <typename T>
inline T &Ref(void *base, uintptr_t offset) {
return *Ptr<T>(base, offset);
}
template <typename T>
inline T Read(uintptr_t address) {
return *reinterpret_cast<const T *>(address);
}
template <typename T>
inline T &Ref(uintptr_t address) {
return *reinterpret_cast<T *>(address);
}
// Calls `fn(object)` for each object of one of a frame's intrusive lists,
// OFF_FRAME_REGION_LIST or OFF_FRAME_CHILD_LIST: node+4 next, node+8 object,
// a NULL or low-bit-1 link ends it - the walk the engine's own frame code
// does (the alpha setter, the bounds walk 0x00786F80).
template <typename Fn>
void ForEachFrameListObject(void *frame, uintptr_t listOffset, Fn fn) {
uintptr_t link = Read<uintptr_t>(frame, listOffset);
while (link != 0 && (link & 1) == 0) {
void *obj = *reinterpret_cast<void *const *>(link + 8);
const uintptr_t next = *reinterpret_cast<const uintptr_t *>(link + 4);
if (obj != nullptr)
fn(obj);
link = next;
}
}
// --- Engine primitives ------------------------------------------------------
// Resolve a unit token (`"player"`, `"target"`, `"party3"`, `"nameplate1"`,
// …) to its live `CGUnit_C *`, through the engine's own resolver
// (`FUN_RESOLVE_UNIT_TOKEN`). Returns null for a valid token that currently
// has no unit (e.g. `"target"` with nothing targeted). NOTE: the engine
// RAISES a Lua error for a string that isn't a valid token form (an arbitrary
// name like `"Bob"`), so only pass real unit tokens — the same contract every
// stock `Unit*` global carries. Centralizes the
// `reinterpret_cast<…>(FUN_RESOLVE_UNIT_TOKEN)` idiom that was copy-pasted
// across a dozen modules.
void *ResolveUnitToken(const char *token);
// UI pixels <-> internal layout (anchor) units. Script_SetPoint converts its
// pixel offsets with `px * [VAR_COORD_DDC_WIDTH_SCALE] / ([VAR_COORD_ASPECT_COMPENSATION]
// * UI_COORD_SCALE_UNIT)`; Script_GetLeft and Script_GetStringWidth push the
// inverse. A region's LOCAL pixels must be multiplied by its effective scale
// (OFF_REGION_EFFECTIVE_SCALE) first. Both return 0 while the scale globals
// are unset, so an early caller gets a zero offset rather than a wild one.
float PixelToInternal(float px);
double InternalToPixel(float internal);
using FrameScript_Initialize_t = bool(__fastcall *)();
using LoadScriptFunctions_t = void(__fastcall *)();
@@ -25,6 +104,132 @@ using LoadScriptFunctions_t = void(__fastcall *)();
// registering its 109 glue functions. See FUN_LOAD_GLUE_SCRIPT_FUNCTIONS.
using LoadGlueScriptFunctions_t = void(__stdcall *)();
// The engine's text-to-flag reader (FUN_XML_ATTR_TO_BOOL, 4.3.4's
// `StringToBOOL(const char *)`), which XML boolean attributes go through:
// true for text starting 1-9/T/Y/t/y or equal to "on"/"enabled" (any case),
// false for anything else, including null.
bool StringToFlag(const char *text);
// Storm's case-insensitive compare, SStrCmpI (FUN_SSTR_CMP_I) — the one the
// engine uses for names, tokens and tags: at most `n` characters, ASCII case
// folded, <0 / 0 / >0 like strcmp. The default `n` is Storm's "whole string".
// Always call it through here: the engine function is `__stdcall` (RET 0xC),
// and a `__cdecl` declaration drifts ESP by 12 per call.
int StrCmpI(const char *a, const char *b, int n = 0x7FFFFFFF);
// --- API documentation descriptors -----------------------------------------
//
// Every Lua registration (see the `Register*` functions in `Game::Lua`) can
// carry a descriptor: the signature the function presents to Lua — typed
// arguments and returns, nilability, defaults — plus a one-sentence summary.
// The descriptors are the single source of truth for the API's SHAPE.
// `src/api/Documentation.cpp` records each registration on the first pass of
// each Lua state and exports the result on demand as Blizzard
// `APIDocumentation` tables (`C_APIDocumentation.GetSystems` / `GetSystem`),
// which the embedded addon's `/api` browser renders. Prose beyond one
// sentence stays in the docs; a descriptor is shape, not manual.
//
// Rules:
// - One descriptor per REGISTERED NAME, not per C function. The same
// `Script_*` bound twice with different return conventions
// (`IsUsableSpell` → 1/nil pairs, `C_Spell.IsSpellUsable` → booleans)
// gets two descriptors; a pair with the same shape may share one.
// - `type` uses Blizzard's spellings — "number", "string", "bool",
// "table", "luaIndex", "UnitToken", "SpellIdentifier", … — or the Name
// of a `Structure` / enumeration declared elsewhere, which the browser
// renders as a link.
// - `Function::system` names the System a GLOBAL belongs to; convention
// `<Area>Globals` ("SpellGlobals", "ItemGlobals"). Table functions
// derive theirs from the table ("C_Spell" → System "Spell", Namespace
// "C_Spell"); frame methods from the registry. A global's system must
// not reuse a namespaced System's Name — the browser would prefix it.
// - Descriptors are `const` objects with constant initializers (string
// literals + file-scope arrays): no heap, no dynamic init.
// - Summaries are user-facing text: one sentence, plain words, present
// tense, no patch versions.
// A view over a file-scope `const T[]` that takes its count from the array's
// type, so no call site passes one; `{}` means none.
template <typename T>
struct ArrayRef {
const T *data = nullptr;
int count = 0;
constexpr ArrayRef() = default;
template <size_t N>
constexpr ArrayRef(const T (&a)[N]) : data(a), count(static_cast<int>(N)) {}
};
namespace Doc {
struct Field {
const char *name;
const char *type;
bool nilable;
const char *defaultValue; // Lua literal ("false", "0", "\"player\""), or nullptr
const char *doc; // one sentence, or nullptr
};
// Required argument / always-present return.
constexpr Field Req(const char *name, const char *type, const char *doc = nullptr) {
return {name, type, false, nullptr, doc};
}
// Optional: nilable when no default is given, otherwise non-nil with that
// default (Blizzard marks defaulted arguments `Nilable = false` + `Default`).
constexpr Field Opt(const char *name, const char *type, const char *dflt = nullptr,
const char *doc = nullptr) {
return {name, type, dflt == nullptr, dflt, doc};
}
// Variable arguments / returns.
constexpr Field Vararg(const char *type, const char *doc = nullptr) {
return {"...", type, true, nullptr, doc};
}
using FieldList = ArrayRef<Field>;
// A registered function. Positional init: `{summary, args, rets}` for a
// table function, `{summary, args, rets, "XGlobals"}` for a global, and
// `{summary, args, rets, nullptr, true}` for a namespaced ClassicAPI
// extension.
struct Function {
const char *summary;
FieldList args;
FieldList rets;
const char *system; // globals / glue / aliases only; see the rules above
bool extension; // a ClassicAPI-original API, not a Blizzard one
};
// Pairs a frame method with its descriptor BY NAME (the engine's method
// tables are name-keyed; `SetShown` exists on four registries with four
// function pointers). Order is free; unmatched names are reported.
struct Method {
const char *name;
const Function *doc;
};
using MethodList = ArrayRef<Method>;
// A table shape a function returns or accepts → `Tables{Type="Structure"}`
// in `system`. Self-registering: nothing binds a structure to Lua, so it
// chains onto a static list at construction. Declare it next to the
// function that returns it.
struct Structure {
Structure(const char *name, const char *system, FieldList fields,
const char *summary = nullptr);
const char *name;
const char *system;
FieldList fields;
const char *summary;
const Structure *next;
};
// A custom event's payload, attached to its `Event::Custom::AutoReserve`.
struct Event {
const char *system;
const char *summary;
FieldList payload;
};
} // namespace Doc
namespace Lua {
using CFunction = int(__fastcall *)(void *L);
@@ -41,7 +246,9 @@ constexpr int UpvalueIndex(int i) { return GLOBALS_INDEX - i; }
// `lua_call` / `lua_pcall` nresults sentinel meaning "all".
constexpr int MULTRET = -1;
// Type tag values returned by `Type()` (lua_type).
// Type tag values returned by `Type()` (lua_type). TYPE_NONE is an absent
// argument (past the top of the stack).
constexpr int TYPE_NONE = -1;
constexpr int TYPE_NIL = 0;
constexpr int TYPE_BOOLEAN = 1;
constexpr int TYPE_LIGHTUSERDATA = 2;
@@ -68,16 +275,30 @@ using lua_pushcclosure_t = void(__fastcall *)(void *L, CFunction fn, int upvals)
using lua_newtable_t = void(__fastcall *)(void *L);
using lua_gettable_t = void(__fastcall *)(void *L, int idx);
using lua_rawget_t = void(__fastcall *)(void *L, int idx);
// Pushes t[n] for the table at idx, raw (no metamethods). With idx =
// REGISTRY_INDEX it pushes a value stored under an integer ref.
using lua_rawgeti_t = void(__fastcall *)(void *L, int idx, int n);
// Pops the top value into t[n] for the table at idx, raw.
using lua_rawseti_t = void(__fastcall *)(void *L, int idx, int n);
using lua_settable_t = void(__fastcall *)(void *L, int idx);
using lua_rawset_t = void(__fastcall *)(void *L, int idx);
// Pushes the metatable of the value at idx and returns 1, or pushes
// nothing and returns 0 when it has none.
using lua_getmetatable_t = int(__fastcall *)(void *L, int idx);
// Pops the table at the top and installs it as the metatable of the value
// at idx; returns 1.
using lua_setmetatable_t = int(__fastcall *)(void *L, int idx);
using lua_insert_t = void(__fastcall *)(void *L, int idx);
using lua_remove_t = void(__fastcall *)(void *L, int idx);
// Pops the top value into slot idx.
using lua_replace_t = void(__fastcall *)(void *L, int idx);
using lua_gettop_t = int(__fastcall *)(void *L);
using lua_settop_t = void(__fastcall *)(void *L, int idx);
using lua_call_t = void(__fastcall *)(void *L, int nargs, int nresults);
using lua_pcall_t = int(__fastcall *)(void *L, int nargs, int nresults, int errfunc);
using lua_next_t = int(__fastcall *)(void *L, int idx);
using lua_type_t = int(__fastcall *)(void *L, int index);
using lua_typename_t = const char *(__fastcall *)(void *L, int type);
// The 1.12 `lua_error` wrapper at `0x6F4940` is actually variadic —
// it does `lua_pushvfstring(L, fmt, args)` then prepends `luaL_where`
// and throws. Existing callers pass a single literal (no `%`), which
@@ -89,6 +310,11 @@ using lua_error_t = void(__cdecl *)(void *L, const char *fmt, ...);
using lua_topointer_t = const void *(__fastcall *)(void *L, int idx);
using lua_tothread_t = void *(__fastcall *)(void *L, int idx);
using lua_iscfunction_t = int(__fastcall *)(void *L, int idx);
using lua_tocfunction_t = CFunction(__fastcall *)(void *L, int idx);
// Fill a lua_Debug (Offsets::SIZEOF_LUA_DEBUG bytes) for a call level /
// with the fields `what` names. Level 0 is the running C function.
using lua_getstack_t = int(__fastcall *)(void *L, int level, void *ar);
using lua_getinfo_t = int(__fastcall *)(void *L, const char *what, void *ar);
using lua_xmove_t = void(__fastcall *)(void *from, void *to, int n);
// `lua_newthread` returns the new `lua_State *` in eax, but Ghidra
// infers `void` because the inner call's value just flows through.
@@ -99,6 +325,26 @@ using lua_newthread_t = void *(__fastcall *)(void *L);
using lua_resume_t = int(__fastcall *)(void *L, int nargs);
using lua_yield_t = int(__fastcall *)(void *L, int nresults);
using luaL_argerror_t = void(__fastcall *)(void *L, int narg, const char *msg);
// The auxlib argument readers: each raises the engine's own "bad argument"
// error. CheckLString's `len` may be null.
using luaL_checklstring_t = const char *(__fastcall *)(void *L, int narg, unsigned int *len);
using luaL_checknumber_t = double(__fastcall *)(void *L, int narg);
using luaL_optnumber_t = double(__fastcall *)(void *L, int narg, double def);
using luaL_setn_t = void(__fastcall *)(void *L, int t, int n);
// Pops the top value into the table at `t` under a fresh integer key and
// returns the key (LUA_REFNIL, -1, for a nil). With REGISTRY_INDEX it anchors
// a value across calls; read it back with RawGetI(L, REGISTRY_INDEX, ref).
using luaL_ref_t = int(__fastcall *)(void *L, int t);
// Releases a key returned by luaL_ref; ignores LUA_REFNIL / LUA_NOREF.
using luaL_unref_t = void(__fastcall *)(void *L, int t, int ref);
using lua_checkstack_t = int(__fastcall *)(void *L, int size);
// Pops the top `n` values and pushes their `..` concatenation; n == 0 pushes
// "" and n == 1 leaves the value untouched.
using lua_concat_t = void(__fastcall *)(void *L, int n);
// Pushes a new full userdata of `size` bytes and returns its block.
using lua_newuserdata_t = void *(__fastcall *)(void *L, unsigned int size);
// The block of the full userdata at idx, the pointer of a light one, else null.
using lua_touserdata_t = void *(__fastcall *)(void *L, int idx);
extern const lua_isnumber_t IsNumber;
extern const lua_isstring_t IsString;
@@ -114,6 +360,13 @@ extern const lua_pushboolean_t PushBoolean;
// engine's `lua_pushboolean` ABI wants `int` (any non-zero = true), so
// this just funnels through the raw binding with a single conversion.
inline void PushBool(void *L, bool b) { PushBoolean(L, static_cast<int>(b)); }
// The engine's script-flag argument reader (FUN_LUA_TO_BOOLEAN_LOOSE, 4.3.4's
// `StringToBOOL(L, index, default)`), which every engine method taking an
// optional flag uses: nil is false, a boolean is itself, a number is its
// truncated int (so 0.5 is false), a string reads as StringToFlag except that
// text it does not recognize is `defaultValue`, and any other type is
// `defaultValue`.
bool ToFlag(void *L, int index, bool defaultValue = false);
extern const lua_pushstring_t PushString;
extern const lua_pushlstring_t PushLString;
extern const lua_pushvalue_t PushValue;
@@ -121,25 +374,44 @@ extern const lua_pushcclosure_t PushCClosure;
extern const lua_newtable_t NewTable;
extern const lua_gettable_t GetTable;
extern const lua_rawget_t RawGet;
extern const lua_rawgeti_t RawGetI;
extern const lua_rawseti_t RawSetI;
extern const lua_settable_t SetTable;
extern const lua_rawset_t RawSet;
extern const lua_getmetatable_t GetMetatable;
extern const lua_setmetatable_t SetMetatable;
extern const lua_insert_t Insert;
extern const lua_remove_t Remove;
extern const lua_replace_t Replace;
extern const lua_gettop_t GetTop;
extern const lua_settop_t SetTop;
extern const lua_call_t Call;
extern const lua_pcall_t PCall;
extern const lua_next_t Next;
extern const lua_type_t Type;
extern const lua_typename_t TypeName;
extern const lua_error_t Error;
extern const lua_topointer_t ToPointer;
extern const lua_tothread_t ToThread;
extern const lua_iscfunction_t IsCFunction;
extern const lua_tocfunction_t ToCFunction;
extern const lua_getstack_t GetStack;
extern const lua_getinfo_t GetInfo;
extern const lua_xmove_t XMove;
extern const lua_newthread_t NewThread;
extern const lua_resume_t Resume;
extern const lua_yield_t Yield;
extern const luaL_argerror_t ArgError;
extern const luaL_checklstring_t CheckLString;
extern const luaL_checknumber_t CheckNumber;
extern const luaL_optnumber_t OptNumber;
extern const luaL_setn_t SetN;
extern const luaL_ref_t Ref;
extern const luaL_unref_t Unref;
extern const lua_checkstack_t CheckStack;
extern const lua_concat_t Concat;
extern const lua_newuserdata_t NewUserdata;
extern const lua_touserdata_t ToUserdata;
// Returns the global `lua_State *` (read on demand from the engine's global).
// Callable outside a Lua callback, e.g. during LoadScriptFunctions setup.
@@ -155,9 +427,90 @@ void *State();
// the `self` slot of any `frame:method(...)` invocation.
void *ResolveObject(void *L, int idx);
// The inverse: the object's Lua-registry ref, created on first use exactly as
// the engine does it (GetMouseFocus and the script runners register an
// object with FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER when its refcount is 0).
int ObjectLuaRef(void *object);
// Pushes the object's Lua table (registry[ObjectLuaRef(object)]).
void PushObject(void *L, void *object);
// The object's global name (VTBL_SCRIPTOBJECT_GET_NAME), or nullptr when it
// has none.
const char *ObjectName(void *object);
// How the engine names an object in its frame-script usage errors:
// `GetName() ?: "<unnamed>"`.
const char *ObjectDisplayName(void *object);
// Same resolve, then the type gate every engine frame method applies to its
// `self` before touching it: `lua_type == table`, resolve to the object, then
// the `IsA(typeId)` vmethod at vtable+0x10. `ResolveObject` alone is not
// enough for a method that casts the result — it hands back a
// `CFrameScriptObject *` for ANY frame, so `GameTooltip.SetSpellByID(button)`
// would reach the tooltip builder with a Button. Frame methods are ordinary
// first-class Lua values (the per-type dispatcher is an `__index` handler
// that returns the method closure), so that call is reachable from plain Lua
// and the gate is not optional.
//
// `typeIdVar` is the class's `VAR_*_LUA_TYPE_ID`, which must match the
// registry the method was registered on. The id is assigned lazily by
// whichever method of the class runs first, so these mirror that assignment
// and work even before any stock method of the type has been called.
//
// Raises the engine's own three errors and returns null. Pass
// `raiseError = false` for an optional object ARGUMENT, where the caller
// wants a silent null rather than a "this" error naming the wrong slot.
// Returns null either way, so callers always check.
void *ResolveTypedObject(void *L, int idx, uintptr_t typeIdVar,
bool raiseError = true);
// For a method registered on SEVERAL registries, where any of those types is
// a legitimate `self`. Accepts the object if `IsA` passes for any of the
// listed ids — which is exactly what being in all of those registries means,
// and avoids having to pin down the shared base class.
void *ResolveTypedObjectAny(void *L, int idx, const uintptr_t *typeIdVars,
int count, bool raiseError = true);
// The class's live type id, assigning it if the engine has not yet. Needed
// directly only when calling a type-specific vtable slot.
int FrameScriptTypeId(uintptr_t typeIdVar);
// The object's `IsA(typeId)` vmethod for a class's `VAR_*_LUA_TYPE_ID`.
bool IsA(void *object, uintptr_t typeIdVar);
// Per-type sugar over `ResolveTypedObject`, so a call site cannot pair a
// method with the wrong class's id. `idx` defaults to the `self` slot.
void *ResolveTooltip(void *L, int idx = 1, bool raiseError = true);
void *ResolveFrame(void *L, int idx = 1, bool raiseError = true);
void *ResolveRegion(void *L, int idx = 1, bool raiseError = true);
void *ResolveTexture(void *L, int idx = 1, bool raiseError = true);
void *ResolveFontString(void *L, int idx = 1, bool raiseError = true);
void *ResolveEditBox(void *L, int idx = 1, bool raiseError = true);
void *ResolveModel(void *L, int idx = 1, bool raiseError = true);
void *ResolvePlayerModel(void *L, int idx = 1, bool raiseError = true);
void *ResolveDressUpModel(void *L, int idx = 1, bool raiseError = true);
// Every name these registrars bind is ALSO bound under `_G.ClassicAPI` —
// `ClassicAPI.GetSpellInfo`, `ClassicAPI.C_Item.IsBound` — as an escape
// hatch for names something else replaces later, and by value so
// `ClassicAPI.X == X` until that happens. Automatic; a new module needs no
// extra call. See `MirrorRegistration` in Game.cpp for why it lives here
// and what it does not cover.
//
// Every registrar also RECORDS the registration for the API documentation
// (`src/api/Documentation.cpp`): kind, table, name, registry, and which Lua
// state's pass it ran in (in-game / glue / both). Only the FIRST pass of
// each state records — later passes (every `/reload`) are no-ops — and a
// registration made outside a `Run*Registrations` pass is not recorded at
// all. The trailing `doc` argument is the descriptor (see `Game::Doc`
// above); pass `nullptr` for a not-yet-documented registration and
// `_classicapi_UndocumentedAPI()` lists it. The defaults exist only until
// the sweep finishes; then they go and a missing descriptor stops compiling.
// Registers a single global Lua function (e.g. `GetSpellInfo`). The function
// must use the WoW Lua C function ABI: `int __fastcall(void *L)`.
void RegisterGlobalFunction(const char *name, CFunction func);
void RegisterGlobalFunction(const char *name, CFunction func,
const Doc::Function *doc = nullptr);
// Glue-state equivalent of `RegisterGlobalFunction`. Identical wire
// (calls `FrameScript_RegisterFunction`); the engine routes the
@@ -167,7 +520,8 @@ void RegisterGlobalFunction(const char *name, CFunction func);
// its own 109 glue functions, and `VAR_LUA_STATE` still points at the
// glue state. Calling outside that window would silently target the
// wrong state.
void RegisterGlueFunction(const char *name, CFunction func);
void RegisterGlueFunction(const char *name, CFunction func,
const Doc::Function *doc = nullptr);
// Frame-method registration entry: { name, func } pairs walked by the engine's
// per-frame-type method-table iterator. Layout matches what the engine expects
@@ -179,19 +533,31 @@ struct FrameMethodEntry {
// Registers a batch of methods on a per-frame-type registry (e.g.
// GameTooltipMethodRegistry for `tooltip:Foo()` calls). `context` is the
// registry address — see Offsets::VAR_*_METHOD_REGISTRY.
void RegisterFrameMethods(void *context, const FrameMethodEntry *table, int count);
// registry address — see Offsets::VAR_*_METHOD_REGISTRY. `methods` and
// `docs` are file-scope arrays; `docs` pairs descriptors to the entries by
// NAME (any order, any subset).
void RegisterFrameMethods(void *context, ArrayRef<FrameMethodEntry> methods,
Doc::MethodList docs = {});
// Registers `func` at `_G[tableName][methodName]`, creating the namespace
// table if it doesn't already exist. This is how modern WoW C_*-style APIs
// are bound — the engine has no built-in support for table-bound Lua
// functions, so we manipulate the globals table directly via the Lua C API.
void RegisterTableFunction(const char *tableName, const char *methodName,
CFunction func);
CFunction func, const Doc::Function *doc = nullptr);
// Key/value pair for `RegisterIntegerEnum`. `key` becomes a field name
// (PascalCase, matching Blizzard's `Enum.*` naming) and `value` is the
// integer the enum field maps to.
// Binds `_G[alias]` to the SAME closure as `_G[tableName][methodName]`, by
// value — the way the engine's own Lua-init snippet binds its short aliases
// (`tinsert = table.insert`, `strlen = string.len`, …). Use it after
// registering over a library function whose alias the snippet has already
// captured, so the alias follows the replacement and `alias == table.method`
// stays true. Mirrored under `_G.ClassicAPI` like every other registration.
void RegisterGlobalAlias(const char *alias, const char *tableName, const char *methodName,
const Doc::Function *doc = nullptr);
// Key/value pair for `RegisterIntegerEnum` and `RegisterConstants`. `key`
// becomes a field name (PascalCase for Blizzard's `Enum.*`, UPPER_CASE for
// its `Constants.*`) and `value` is the integer the field maps to.
struct EnumIntegerEntry {
const char *key;
int value;
@@ -200,8 +566,17 @@ struct EnumIntegerEntry {
// Registers `_G[parent][sub] = { entries }` as an integer-valued enum
// table, creating `_G[parent]` if needed. Used for Blizzard-style
// `Enum.AddOnSecurityStatus = { Secure=0, Insecure=1, ... }` shapes.
void RegisterIntegerEnum(const char *parent, const char *sub,
const EnumIntegerEntry *entries, int count);
// `docSystem` is the documentation System the enumeration belongs to
// ("SpellBook", "Item", …); the entries themselves are the documentation.
// `entries` is a file-scope array.
void RegisterIntegerEnum(const char *parent, const char *sub, ArrayRef<EnumIntegerEntry> entries,
const char *docSystem = nullptr);
// Registers `Constants[sub] = { entries }`, Blizzard's engine constant
// tables (`Constants.MoneyFormattingConstants`). Documented as a "Constants"
// table of `docSystem`.
void RegisterConstants(const char *sub, ArrayRef<EnumIntegerEntry> entries,
const char *docSystem);
// Set `t[key] = value` on the table currently at stack[-1] (the most
// common shape used when populating a struct-style table mid-build).
@@ -211,6 +586,10 @@ void RegisterIntegerEnum(const char *parent, const char *sub,
void SetFieldNumber(void *L, const char *key, double value);
void SetFieldString(void *L, const char *key, const char *value);
void SetFieldBool(void *L, const char *key, bool value);
// `t[key] = nil` — clears a field a reused (caller-supplied) table may still
// hold from an earlier fill. Not for fresh tables: Lua 5.0 inserts a node for
// a missing key even when the value is nil.
void SetFieldNil(void *L, const char *key);
// Sets `_G[name] = value` via `lua_rawset` on the globals
// pseudo-index. `RawSet` over `SetTable` because the globals table has
@@ -238,8 +617,26 @@ void PushLocalizedString(void *L, const char *globalName, const char *fallback);
// `ITEM_SLOTS_IGNORED = "%d slot(s) ignored"`, etc.). Callers that
// need string or float args, or multiple args, can build their own
// using `PushLocalizedString` + manual `string.format` invocation.
// A `|4singular:plural;` in the string stays; the engine's grammar pass
// (Text::Grammar) expands it when the text is set.
void PushLocalizedFormatInt(void *L, const char *globalName,
const char *fallback, int n);
// Pushes `_G[name]` and returns true only if it resolved to a function
// (leaving it on the stack, ready to be called); otherwise pops it and
// returns false. The building block for the CallGlobal* helpers below and for
// any C module that dispatches to a Lua/FrameXML global by name (a pattern
// several modules otherwise open-code).
bool PushGlobalFunction(void *L, const char *name);
// `_G[name]()` — no args, no results; a no-op if the global isn't a function.
// Stack-neutral.
void CallGlobal(void *L, const char *name);
// `_G[name](arg)` — one string arg (NULL → nil), no results. Returns true iff
// the global was a function and got called, so callers can fall back to a
// native path when the FrameXML/addon global is absent. Stack-neutral.
bool CallGlobalString(void *L, const char *name, const char *arg);
} // namespace Lua
// Developer-console command system — the `~` console available when the
@@ -249,16 +646,17 @@ void PushLocalizedFormatInt(void *L, const char *globalName,
// section in CLAUDE.md for the underlying offsets and ABI.
namespace Console {
// Console-command handler ABI: `args` is the command-line text after
// the command name (empty string when invoked bare). The engine
// ignores the return value; return 1 by convention.
using CommandHandler = int(__fastcall *)(void *unused, const char *args);
// Console-command handler ABI — 4.3.4's `COMMANDHANDLER(command,
// arguments)`. `command` is the name the command was invoked by, which
// is how one handler serves several names: every CVar is registered with
// the shared FUN_CONSOLE_CVAR_COMMAND_HANDLER, which looks the CVar up by
// `command`. `args` is the text after the name (empty string when
// invoked bare). The engine ignores the return value; return 1.
using CommandHandler = int(__fastcall *)(const char *command, const char *args);
// Help-grouping categories — the engine's `help` enumerates these nine
// (in this order). Cosmetic: the value only affects which group `help`
// lists the command under; the engine doesn't validate it. Values are
// sequential table indices (graphics=1 confirmed via FUN_0066F6C0, the
// rest follow the displayed order).
// Help-grouping categories — 4.3.4's `CATEGORY` enum, which matches the
// nine-entry table the 1.12 `help` command lists (VAR_CONSOLE_CATEGORY_TABLE).
// Cosmetic: only `help` grouping reads it; the registrar doesn't validate it.
enum Category {
CATEGORY_DEBUG = 0,
CATEGORY_GRAPHICS = 1,
@@ -280,9 +678,30 @@ enum Category {
void RegisterCommand(const char *name, CommandHandler handler, int category,
const char *description);
// Line colour types — 4.3.4's `COLOR_T`, indexing the nine-entry
// VAR_CONSOLE_COLORS table. The engine's `help` writes WARNING (yellow),
// its failures ERROR (red), and its plain output DEFAULT.
enum Color {
COLOR_DEFAULT = 0,
COLOR_INPUT = 1,
COLOR_ECHO = 2,
COLOR_ERROR = 3,
COLOR_WARNING = 4,
COLOR_GLOBAL = 5,
COLOR_ADMIN = 6,
COLOR_HIGHLIGHT = 7,
COLOR_BACKGROUND = 8,
};
// Writes a line to the console output buffer. No-ops cleanly when the
// console isn't active, so it's always safe to call.
void Write(const char *line);
void Write(const char *line, Color color = COLOR_DEFAULT);
// The engine's own `ConsolePrintf` (FUN_CONSOLE_PRINTF): formats with
// Storm's printf into a 1024-byte buffer, then writes it in
// COLOR_DEFAULT. Exposed as the engine's entry itself rather than a
// wrapper, because a cdecl varargs call cannot be forwarded.
extern void(__cdecl *const Printf)(const char *format, ...);
} // namespace Console
@@ -321,19 +740,24 @@ void RunGlueModuleRegistrations();
// Declarative MinHook registration. Each feature module declares a
// file-scope `static const Game::HookAutoRegister _hookreg{target,
// &hook_fn, reinterpret_cast<void**>(&original_fn)};` and DllMain's
// `RunHookRegistrations` walks the list once after `MH_Initialize`,
// installing each hook with `MH_CreateHook` + `MH_EnableHook`.
// &hook_fn, reinterpret_cast<void**>(&original_fn)};` and the installer
// (`InstallHooks` in DllMain.cpp) walks the list once after
// `MH_Initialize`, creating each hook and QUEUE-enabling it; a single
// `MH_ApplyQueued` then activates them all in one thread-freeze.
//
// The install runs OFF the loader lock (via the `Load` export or the
// fallback worker thread — see DllMain.cpp), never inside DllMain, so
// the thread-freeze can't deadlock or stall the loader.
//
// Same lifetime rules as ModuleAutoRegister: constructors chain onto
// a static-init list before DllMain runs, the linker keeps the OBJ
// because the constructor has side effects, and order across TUs is
// undefined but doesn't matter here (hooks are independent).
//
// Use only for feature hooks. The three core engine-init hooks in
// Use only for feature hooks. The four core engine-init hooks in
// DllMain (FrameScript_Initialize / LoadScriptFunctions /
// Frame::RegisterEvent) have inline logic that interleaves with the
// hook chain and stays in DllMain.
// LoadGlueScriptFunctions / Frame::RegisterEvent) have inline logic that
// interleaves with the hook chain and stays with the installer.
struct HookAutoRegister {
HookAutoRegister(uintptr_t target, void *hook, void **original);
uintptr_t target;
@@ -342,8 +766,46 @@ struct HookAutoRegister {
HookAutoRegister *next;
};
// Installs every registered hook. Returns `false` and stops on first
// failure — caller (DllMain) should propagate by returning FALSE.
// Creates and QUEUE-enables every registered hook (no `MH_ApplyQueued`
// here — the caller applies the whole batch at once). Returns `false`
// 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.
//
// It runs AFTER the frames are gone: CGGameUI::Shutdown destroys every frame
// (and each Model frame's scene with every model in it) before
// CGGameUI::Initialize resets the Lua state. So a cleanup here only FORGETS
// pointers; it never releases an engine object tied to a frame. Release those
// when the frame dies (Model::Teardown for Model frames).
//
// 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
+98 -110
View File
@@ -11,7 +11,10 @@
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
#include "HookSecureFunc.h"
#include "Game.h"
#include "Offsets.h"
#include <cstring>
@@ -19,14 +22,18 @@ namespace HookSecureFunc {
namespace {
// Names that must not be hooked when targeting `_G`. Hooking any of these
// would either break taint propagation (the "secure" functions) or replace
// core Lua language primitives whose behavior the engine depends on
// internally — e.g. `pairs` is called from C in the iterator path; if Lua
// `pairs` is replaced with a wrapper closure, the engine still gets the
// original via its own table-method dispatch, but Lua-side iteration goes
// through our wrapper, and the two diverging is a footgun. Modern WoW
// rejects the hook outright; we mirror that. Sorted alphabetically.
// Names that must not be hooked when targeting `_G`. This is the client's
// own list, VERBATIM: patch 11.0.0 (The War Within, 2024-07-23) made
// `hooksecurefunc` refuse exactly these 23 names with a "Cannot hook
// function" error — the taint-relevant primitives (the "secure" family plus
// the Lua primitives secure code paths run through). It is deliberately NOT
// "every base-library function": 11.0 leaves `tostring`, `error`,
// `loadstring`, `assert`, `collectgarbage`, … hookable, and includes names
// that are not base-library functions at all. So do not derive this from
// the engine's `luaopen_base` table (`0x00811E28`, 36 entries — see
// BlizzardScriptAPI.md §3); that is a different set with a different
// purpose. Names with no 1.12 counterpart (the secure family does not
// exist) stay for parity of the error an addon sees. Sorted alphabetically.
const char *const kUnhookableNames[] = {
"getfenv", "getmetatable", "hooksecurefunc", "ipairs", "issecurevalue",
"issecurevariable", "next", "pairs", "pcall", "pcallwithenv", "rawget",
@@ -45,138 +52,113 @@ bool IsUnhookable(const char *name) {
return false;
}
} // namespace
// Wrapper closure body — called when the hooked function is invoked.
// Stack contains the wrapper's args (`[arg1..argN]`); the closure's
// upvalues hold `(orig, callback)`.
// upvalues hold `(orig, callback)`. 4.3.4's FrameScript_HookWrapper, less
// its taint bookkeeping (1.12 has no taint):
//
// Modern `hooksecurefunc` semantics: original runs first, callback
// runs after with the same args (returns ignored), original's
// results propagate to the caller. No cap on return count. A buggy
// callback must NOT prevent the original's results from reaching
// the caller — that's why step (3) uses pcall.
//
// Stack-shuffling mirrors 3.3.5's `FUN_00817050` so the args sit at
// the top for both calls without copying them twice; results sink
// to the bottom and end up as the wrapper's natural return frame.
int __fastcall HookWrapper(void *L) {
// 1. orig(...) with lua_call — an error in the original propagates to
// the caller, as it would unhooked.
// 2. Results sink below the args, so they end up as the wrapper's
// return frame without being copied again.
// 3. callback(...) through lua_pcall with the engine's frame-script
// message handler as errfunc: a broken hook is REPORTED the way any
// script error is (the error frame / geterrorhandler), and the
// original's results still reach the caller.
int __fastcall Wrapper(void *L) {
const int nargs = Game::Lua::GetTop(L);
// (1) orig(...) — pops orig + nargs args (copies), pushes results.
// Stack after: `[arg1..argN, res1..resM]`.
Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(1));
// (1) Stack after: `[arg1..argN, res1..resM]`.
for (int i = 1; i <= nargs; ++i)
Game::Lua::PushValue(L, i);
Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(1));
Game::Lua::Insert(L, nargs + 1);
Game::Lua::Call(L, nargs, Game::Lua::MULTRET);
const int nresults = Game::Lua::GetTop(L) - nargs;
// (2) Shuffle results below the saved args. Each `Insert(L, 1)`
// moves the current top down to position 1; running it
// nresults times rotates the results block beneath the args.
// (2) Each `Insert(L, 1)` moves the top value to the bottom; nresults
// of them rotate the results block beneath the args.
// Stack after: `[res1..resM, arg1..argN]`.
for (int i = 0; i < nresults; ++i)
Game::Lua::Insert(L, 1);
// (3) callback(...) via pcall — errors are caught and dropped so
// the original's return values always reach the caller. This
// is the load-bearing safety property of hooksecurefunc on
// 3.x; on 1.12 it just means a buggy hook can't break the
// hooked path. errfunc=0 → no traceback (3.3.5 uses
// `registry["_TRACEBACK"]`, not a 1.12 convention; we'd be
// discarding the formatted message anyway).
// (3) Stack: `[res1..resM, errfunc, callback, arg1..argN]`. The
// handler ref is the one every engine script pcall passes; 0 (not
// yet set) falls back to no handler rather than a bad index.
Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(2));
Game::Lua::Insert(L, nresults + 1);
if (Game::Lua::PCall(L, nargs, 0, 0) != 0) {
// pcall failure leaves the error message on top; drop it.
Game::Lua::Remove(L, -1);
int errIdx = 0;
const int errRef = Game::Read<int>(
static_cast<uintptr_t>(Offsets::VAR_FRAMESCRIPT_ERROR_HANDLER_REF));
if (errRef > 0) {
Game::Lua::RawGetI(L, Game::Lua::REGISTRY_INDEX, errRef);
Game::Lua::Insert(L, nresults + 1);
errIdx = nresults + 1;
}
Game::Lua::PCall(L, nargs, 0, errIdx);
// Stack: `[res1..resM]` — return the original's results verbatim.
// Drop the handler and any error value — `[res1..resM]` remains.
Game::Lua::SetTop(L, nresults);
return nresults;
}
// `hooksecurefunc(name, callback)` — hooks a global by name, target
// table is `_G`.
// `hooksecurefunc(table, name, callback)` — hooks `table[name]`.
//
// In both cases the original function runs first and its results
// propagate; `callback` runs after with the same args (returns
// discarded). The "secure" label refers to taint propagation in
// 3.x+; on 1.12 it's just a post-hook with return preservation.
void PushWrapper(void *L) {
Game::Lua::PushCClosure(L, &Wrapper, 2);
}
namespace {
// `hooksecurefunc([table,] "function", hookfunc)` — replaces
// `table[name]` (default `_G`) with a wrapper that runs the original, then
// `hookfunc` with the same args, and returns the original's results.
// 4.3.4's Script_hooksecurefunc, less taint:
// * a non-table first argument means `_G` is inserted at index 1, so
// both forms share one index layout;
// * the name only has to pass lua_isstring, so a number works (and is
// looked up as its string, the same as lua_tostring makes it);
// * the original is read with lua_gettable (inherited methods resolve
// through __index) but the wrapper is written with lua_rawset, so a
// target's __newindex never runs;
// * the error texts are 4.3.4's.
// The one addition is the 11.0 unhookable-name check for the `_G` form.
int __fastcall Script_HookSecureFunc(void *L) {
int targetIdx, nameIdx, callbackIdx;
const int t1 = Game::Lua::Type(L, 1);
const bool implicitGlobals = Game::Lua::Type(L, 1) != Game::Lua::TYPE_TABLE;
if (implicitGlobals) {
Game::Lua::PushValue(L, Game::Lua::GLOBALS_INDEX);
Game::Lua::Insert(L, 1);
}
if (t1 == Game::Lua::TYPE_TABLE) {
// Three-arg form: (table, name, callback)
targetIdx = 1;
nameIdx = 2;
callbackIdx = 3;
} else if (t1 == Game::Lua::TYPE_STRING) {
// Two-arg form: (name, callback) — target = _G via pseudo-
// index. Don't push _G with `lua_pushvalue(GLOBALS_INDEX)`:
// it crashes (the pushvalue → setobj2s chain dereferences a
// bad TValue pointer for that pseudo-index). `lua_gettable` /
// `lua_settable` accept GLOBALS_INDEX as the table arg
// directly, so we use it that way without pushing.
targetIdx = Game::Lua::GLOBALS_INDEX;
nameIdx = 1;
callbackIdx = 2;
} else {
Game::Lua::Error(L,
"hooksecurefunc(table, name, callback) or hooksecurefunc(name, callback)");
if (!Game::Lua::IsString(L, 2) ||
Game::Lua::Type(L, 3) != Game::Lua::TYPE_FUNCTION) {
Game::Lua::Error(L, "Usage: hooksecurefunc([table,] \"function\", hookfunc)");
return 0;
}
Game::Lua::SetTop(L, 3); // [t, name, hookfunc]
// Converts a number name to its string in place; the string stays on
// the stack, so the pointer outlives every use below.
const char *name = Game::Lua::ToString(L, 2);
// Block the hook when targeting `_G` implicitly and the name is in the
// unhookable set. Not applied to the three-arg form (table targets):
// hooking `MyLib.pairs` is fine even if Lua's global `pairs` is not,
// and a caller who passes `_G` explicitly is opting in deliberately.
if (implicitGlobals && IsUnhookable(name)) {
Game::Lua::Error(L, "hooksecurefunc: function is unhookable");
return 0;
}
if (Game::Lua::Type(L, nameIdx) != Game::Lua::TYPE_STRING) {
Game::Lua::Error(L, "hooksecurefunc: name must be a string");
return 0;
}
if (Game::Lua::Type(L, callbackIdx) != Game::Lua::TYPE_FUNCTION) {
Game::Lua::Error(L, "hooksecurefunc: callback must be a function");
return 0;
}
// Block the hook when targeting `_G` and the name is in the unhookable
// set. We don't apply this to the three-arg form (table targets):
// hooking `MyLib.pairs` is fine even if Lua's global `pairs` is not —
// the blacklist is specifically about `_G[name]`. A user who passes
// `_G` explicitly as the table target is opting in deliberately and we
// don't second-guess it.
if (targetIdx == Game::Lua::GLOBALS_INDEX) {
const char *name = Game::Lua::ToString(L, nameIdx);
if (IsUnhookable(name)) {
Game::Lua::Error(L,
"hooksecurefunc: function is unhookable");
return 0;
}
}
// Fetch target[name] — the original function. `gettable` uses
// metamethods, so frame methods (resolved via the frame
// metatable's __index) come back as callable closures, exactly
// what we want to wrap.
Game::Lua::PushValue(L, nameIdx);
Game::Lua::GetTable(L, targetIdx);
Game::Lua::PushValue(L, 2);
Game::Lua::GetTable(L, 1); // [t, name, hookfunc, orig]
if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_FUNCTION) {
Game::Lua::Error(L, "hooksecurefunc: target field is not a function");
Game::Lua::Error(L, "hooksecurefunc(): %s is not a function", name);
return 0;
}
// Push callback as the second upvalue; orig is already on top
// from the GetTable above.
Game::Lua::PushValue(L, callbackIdx);
// Build the wrapper as a C closure with (orig, callback) as the
// two upvalues. PushCClosure pops the upvalues from the stack
// and pushes the closure.
Game::Lua::PushCClosure(L, &HookWrapper, 2);
// Install: target[name] = wrapper. SetTable expects the value
// on top and the key just below; push them in that order.
Game::Lua::PushValue(L, nameIdx);
Game::Lua::PushValue(L, -2); // duplicate the closure
Game::Lua::SetTable(L, targetIdx);
Game::Lua::Insert(L, 3); // [t, name, orig, hookfunc]
PushWrapper(L); // [t, name, wrapper]
Game::Lua::RawSet(L, 1); // t[name] = wrapper
return 0;
}
@@ -185,7 +167,13 @@ int __fastcall Script_HookSecureFunc(void *L) {
static void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("hooksecurefunc", &Script_HookSecureFunc);
}
// 4.3.4 registers it from FrameScript_Initialize, which runs for the glue
// state (Client.cpp) as well as the world (GameUI.cpp).
static void RegisterGlueFunctions() {
Game::Lua::RegisterGlueFunction("hooksecurefunc", &Script_HookSecureFunc);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
static const Game::GlueModuleAutoRegister _autoregGlue{&RegisterGlueFunctions};
} // namespace HookSecureFunc
+32
View File
@@ -0,0 +1,32 @@
// 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
// The one hook wrapper `hooksecurefunc` and `Frame:HookScript` both install —
// 4.3.4 uses its FrameScript_HookWrapper for both, so a hooked function and a
// hooked script behave the same way.
namespace HookSecureFunc {
// The wrapper closure body. Upvalue 1 = the original, upvalue 2 = the hook.
// Runs the original with the wrapper's args (its errors propagate), then the
// hook with the same args under the engine's script error handler, and
// returns the original's results. Exposed so readers can recognize the
// closure by its C function.
int __fastcall Wrapper(void *L);
// Pops the hook (top) and the original (below it) and pushes the wrapper
// closure over them.
void PushWrapper(void *L);
} // namespace HookSecureFunc
+9875 -521
View File
File diff suppressed because it is too large Load Diff
+90
View File
@@ -0,0 +1,90 @@
// 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/>.
// `IsItemAction(slot)` / `HasBonusActionBar()` — the action-bar predicates
// from the newer clients' ActionBarFrame_Scripts, read off the same engine
// state the 1.12 readers use.
//
// IsItemAction 1 when the 1-based slot holds an item, else nil; a
// non-number slot is a usage error. The item kind is
// the 0x80000000 tag in VAR_ACTION_TABLE.
// HasBonusActionBar 1 while a bonus bar is active, else nil: the offset
// GetBonusBarOffset returns is nonzero.
#include "Game.h"
#include "Offsets.h"
#include <cstdint>
namespace Action::Bar {
namespace {
int PushFlag(void *L, bool on) {
if (on)
Game::Lua::PushNumber(L, 1.0);
else
Game::Lua::PushNil(L);
return 1;
}
int __fastcall Script_IsItemAction(void *L) {
if (!Game::Lua::IsNumber(L, 1)) {
Game::Lua::Error(L, "Usage: IsItemAction(slot)");
return 0;
}
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
return PushFlag(L, false);
const auto *table = reinterpret_cast<const uint32_t *>(
static_cast<uintptr_t>(Offsets::VAR_ACTION_TABLE));
return PushFlag(L, (table[slot0] & Offsets::ACTION_TYPE_MASK) ==
Offsets::ACTION_TYPE_ITEM_BY_ID);
}
int __fastcall Script_HasBonusActionBar(void *L) {
return PushFlag(L, Game::Read<uint32_t>(Offsets::VAR_BONUS_BAR_OFFSET) != 0);
}
// --- Documentation ----------------------------------------------------------
const Game::Doc::Field kSlotArgs[] = {
Game::Doc::Req("slot", "number", "The action slot, 1 to 120."),
};
const Game::Doc::Field kIsItemRets[] = {
Game::Doc::Opt("isItem", "number", nullptr, "1 if the slot holds an item, else nil."),
};
const Game::Doc::Function kIsItemAction{
"Returns 1 if an action slot holds an item.",
kSlotArgs, kIsItemRets, "ActionBar"};
const Game::Doc::Field kHasBonusRets[] = {
Game::Doc::Opt("hasBonusBar", "number", nullptr,
"1 if a bonus action bar is active, else nil."),
};
const Game::Doc::Function kHasBonusActionBar{
"Returns 1 if a bonus action bar is active, for example in a stance or form.",
{}, kHasBonusRets, "ActionBar"};
} // namespace
static void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("IsItemAction", &Script_IsItemAction, &kIsItemAction);
Game::Lua::RegisterGlobalFunction("HasBonusActionBar", &Script_HasBonusActionBar,
&kHasBonusActionBar);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace Action::Bar
+178
View File
@@ -0,0 +1,178 @@
// 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/>.
// Where a spell sits on the bars.
//
// FindSpellActionButtons(spell [, set]) the 1-based slots holding the
// spell as a spell action, or nothing when none does.
// HasSpellActionButtons(spell [, set]) whether any slot does.
// IsOnBarOrSpecialBar(spell [, set]) the same, or the spell is on the
// shapeshift bar or the pet bar.
//
// A slot matches on the spell ID it stores, as 4.3.4's PutActionInSlot
// compares (IsSpell && GetSpell == spellId): a macro or an item that casts
// the spell is not the spell, and a rank matches only itself. The special
// bars are the engine's own lists — the shapeshift bar's spell array that
// GetShapeshiftFormInfo reads, and the pet bar's spell entries
// (GetPetActionInfo's types 1-5) while a pet bar is up.
//
// `set` is Enum.ActionBarSet, a mask whose Mkb bit is the one set of slots
// this client has; Gamepad alone finds no slot.
#include "Game.h"
#include "Offsets.h"
#include "spell/Arg.h"
#include <cstdint>
namespace Action::Find {
namespace {
constexpr int ACTION_BAR_SET_MKB = 1;
constexpr int ACTION_BAR_SET_GAMEPAD = 2;
constexpr int ACTION_BAR_SET_ALL = ACTION_BAR_SET_MKB | ACTION_BAR_SET_GAMEPAD;
// The spell at stack[1] and whether the set at stack[2] (default All)
// covers this client's slots. 0 when the spell does not resolve.
int Args(void *L, bool *searchSlots) {
const int set = Game::Lua::IsNumber(L, 2) ? static_cast<int>(Game::Lua::ToNumber(L, 2))
: ACTION_BAR_SET_ALL;
*searchSlots = (set & ACTION_BAR_SET_MKB) != 0;
return Spell::Arg::ResolveSpellID(L, 1);
}
bool SlotHolds(int slot0, int spellID) {
const uint32_t entry = reinterpret_cast<const uint32_t *>(
static_cast<uintptr_t>(Offsets::VAR_ACTION_TABLE))[slot0];
return (entry & Offsets::ACTION_TYPE_MASK) == Offsets::ACTION_TYPE_SPELL &&
entry == static_cast<uint32_t>(spellID);
}
bool AnySlotHolds(int spellID) {
for (int slot0 = 0; slot0 < Offsets::ACTION_TABLE_MAX_SLOTS; ++slot0) {
if (SlotHolds(slot0, spellID))
return true;
}
return false;
}
bool OnShapeshiftBar(int spellID) {
const int count = Game::Read<int>(Offsets::VAR_SHAPESHIFT_BAR_SPELL_COUNT);
const auto *spells = Game::Read<const uint32_t *>(Offsets::VAR_SHAPESHIFT_BAR_SPELLS);
if (spells == nullptr)
return false;
for (int i = 0; i < count; ++i) {
if (spells[i] == static_cast<uint32_t>(spellID))
return true;
}
return false;
}
bool OnPetBar(int spellID) {
if (Game::Read<uint64_t>(Offsets::VAR_PET_GUID) == 0)
return false;
const auto *slots = reinterpret_cast<const uint32_t *>(
static_cast<uintptr_t>(Offsets::VAR_PET_ACTION_SLOTS));
for (int i = 0; i < Offsets::PET_ACTION_SLOT_COUNT; ++i) {
const uint32_t type = (slots[i] >> 24) & 0x3F;
if (type >= Offsets::PET_ACTION_TYPE_SPELL_FIRST &&
type <= Offsets::PET_ACTION_TYPE_SPELL_LAST &&
(slots[i] & 0xFFFF) == static_cast<uint32_t>(spellID))
return true;
}
return false;
}
int __fastcall Script_FindSpellActionButtons(void *L) {
bool searchSlots;
const int spellID = Args(L, &searchSlots);
if (spellID <= 0 || !searchSlots || !AnySlotHolds(spellID))
return 0;
Game::Lua::NewTable(L);
int index = 0;
for (int slot0 = 0; slot0 < Offsets::ACTION_TABLE_MAX_SLOTS; ++slot0) {
if (!SlotHolds(slot0, spellID))
continue;
Game::Lua::PushNumber(L, static_cast<double>(++index));
Game::Lua::PushNumber(L, static_cast<double>(slot0 + 1));
Game::Lua::RawSet(L, -3);
}
return 1;
}
int __fastcall Script_HasSpellActionButtons(void *L) {
bool searchSlots;
const int spellID = Args(L, &searchSlots);
Game::Lua::PushBool(L, spellID > 0 && searchSlots && AnySlotHolds(spellID));
return 1;
}
int __fastcall Script_IsOnBarOrSpecialBar(void *L) {
bool searchSlots;
const int spellID = Args(L, &searchSlots);
Game::Lua::PushBool(L, spellID > 0 && ((searchSlots && AnySlotHolds(spellID)) ||
OnShapeshiftBar(spellID) || OnPetBar(spellID)));
return 1;
}
// --- Documentation ----------------------------------------------------------
const Game::Doc::Field kArgs[] = {
Game::Doc::Req("spellID", "SpellIdentifier", "A spell ID, spell link, or spell name."),
Game::Doc::Opt("setToSearch", "ActionBarSet", "All"),
};
const Game::Doc::Field kFindRets[] = {
Game::Doc::Req("slots", "table", "The 1-based action slots; nothing when no slot "
"holds the spell."),
};
const Game::Doc::Function kFindSpellActionButtons{
"The action slots that hold the spell as a spell action.",
kArgs, kFindRets};
const Game::Doc::Field kHasRets[] = {
Game::Doc::Req("hasSpellActionButtons", "bool"),
};
const Game::Doc::Function kHasSpellActionButtons{
"Whether any action slot holds the spell as a spell action.",
kArgs, kHasRets};
const Game::Doc::Field kOnBarRets[] = {
Game::Doc::Req("isOnBarOrSpecialBar", "bool"),
};
const Game::Doc::Function kIsOnBarOrSpecialBar{
"Whether the spell is in an action slot, on the shapeshift bar, or on the pet bar.",
kArgs, kOnBarRets};
const Game::Lua::EnumIntegerEntry kActionBarSet[] = {
{"None", 0},
{"Mkb", ACTION_BAR_SET_MKB},
{"Gamepad", ACTION_BAR_SET_GAMEPAD},
{"All", ACTION_BAR_SET_ALL},
};
} // namespace
static void RegisterLuaFunctions() {
Game::Lua::RegisterTableFunction("C_ActionBar", "FindSpellActionButtons",
&Script_FindSpellActionButtons, &kFindSpellActionButtons);
Game::Lua::RegisterTableFunction("C_ActionBar", "HasSpellActionButtons",
&Script_HasSpellActionButtons, &kHasSpellActionButtons);
Game::Lua::RegisterTableFunction("C_ActionBar", "IsOnBarOrSpecialBar",
&Script_IsOnBarOrSpecialBar, &kIsOnBarOrSpecialBar);
Game::Lua::RegisterIntegerEnum("Enum", "ActionBarSet", kActionBarSet, "ActionBar");
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace Action::Find
+97 -53
View File
@@ -12,41 +12,50 @@
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
// `GetActionInfo(slot)` — modern-WoW-style action descriptor lookup.
// Returns `actionType, id, subType` for the slot, or nil if empty.
// Returns `actionType, id, subType` for the slot, or nothing if the slot
// holds nothing the descriptor can describe (4.3.4 returns nothing there
// too, rather than a nil).
//
// The vanilla 1.12.1 engine stores action descriptors as packed
// uint32s in `VAR_ACTION_TABLE` (`0x00BC6980`, 120 slots). Top 4 bits
// are the type tag; the `0x40000000` tag is ambiguous between
// macros and bag-items and is disambiguated by checking the per-
// character macro-slot map at `VAR_MACRO_SLOT_MAP` (36 entries).
// are the type tag — the server's ACTION_BUTTON_* values shifted into the
// top byte: 0x00 spell, 0x40 macro, 0x80 item.
//
// empty slot: nil
// spell action: "spell", spellID, "spell"
// macro: "macro", macroIndex (1-based)
// bag item: "item", nil (see note below)
// item-by-id: "item", itemID
// item: "item", itemID
// equipment set: "equipmentset", setName
//
// The subType is always "spell" for spell-type entries — the engine
// helper hardcodes pet=0 for entries on this table. Pet-bar actions
// live in a separate table; that's `PetHasActionBar` + the pet-action
// helpers, not this function.
//
// The macro discriminator is the same trick SuperWoWhook uses in its
// modified `GetActionText`: walk the 36-entry macro-slot map and check
// whether `entry & 0xBFFFFFFF` matches one of those macro IDs. If yes,
// the slot holds a macro; if no, it's a bag-item.
// A 0x40 entry is a macro only while its macroID is in the macro-slot map
// (`FUN_ACTION_IS_MACRO`, which every engine reader gates its macro branch
// on). One that is not — a macro deleted out from under its button — is
// nothing, as in 4.3.4: its IsItem and IsMacro are both false, so it falls
// through to an empty return. There is no bag-item tag: items are always
// by-itemID (0x80), and an earlier reading of the 0x40 "miss" as a bag item
// was wrong.
//
// **Bag-item itemID note.** For real bag items (top-4 bits = `0x4`
// and the payload isn't in the macro-slot map), the engine stores a
// bag-instance key, not the itemID. Resolving to itemID requires
// walking the per-character action-item hash table at `[0x00BDCC54]`
// and reading a struct field whose offset we haven't fully derived
// yet. For now we report the action *type* ("item") but return nil
// for the id. Callers that need it can fall back to
// `GetActionTexture` + Lua-side item lookups.
// `C_ActionBar.GetSpell(slot)` — the spell the slot stands for, 0 for none.
// It is the engine's own resolver (FUN_ACTION_SLOT_TO_SPELL), which every
// action reader (cooldown, usable, range, current) goes through: a spell
// action is its spell, a macro is its cached primary spell, and an item is
// its first on-use spell — retail's ActionButton.lua calls GetSpell for
// exactly that item case. The spellbook flag it also hands back is not part
// of the answer.
//
// `C_ActionBar.IsMacroActionWithShowTooltip(slot)` — the slot holds a macro
// whose body carries `#showtooltip`, by the parse `Macro::ShowTooltip` hands
// the tooltip over on. `#show` is not it.
#include "Game.h"
#include "Offsets.h"
#include "action/Slot.h"
#include "equipmentset/Data.h"
#include "macro/ShowTooltip.h"
#include <cstdint>
@@ -62,19 +71,6 @@ uint32_t ReadEntry(int slot0) {
return base[slot0];
}
// Returns 1-based macro slot index if `key` matches any entry in the
// macro-slot map, or 0 if no match. `key` is the action entry with the
// `0x40000000` type bit stripped (i.e. `entry & 0xBFFFFFFF`).
int FindMacroSlot(uint32_t key) {
auto *map = reinterpret_cast<const uint32_t *>(
static_cast<uintptr_t>(Offsets::VAR_MACRO_SLOT_MAP));
for (int i = 0; i < Offsets::MACRO_SLOT_MAP_COUNT; ++i) {
if (map[i] == key)
return i + 1;
}
return 0;
}
int __fastcall Script_GetActionInfo(void *L) {
if (!Game::Lua::IsNumber(L, 1)) {
Game::Lua::Error(L, "Usage: GetActionInfo(slot)");
@@ -82,16 +78,12 @@ int __fastcall Script_GetActionInfo(void *L) {
}
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS) {
Game::Lua::PushNil(L);
return 1;
}
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
return 0;
const uint32_t entry = ReadEntry(slot0);
if (entry == 0) {
Game::Lua::PushNil(L);
return 1;
}
if (entry == 0)
return 0;
const uint32_t type = entry & Offsets::ACTION_TYPE_MASK;
@@ -104,10 +96,8 @@ int __fastcall Script_GetActionInfo(void *L) {
static_cast<uintptr_t>(Offsets::FUN_ACTION_SLOT_TO_SPELL));
uint32_t petFlag = 0;
const uint32_t spellID = fn(static_cast<uint32_t>(slot0), &petFlag);
if (spellID == 0) {
Game::Lua::PushNil(L);
return 1;
}
if (spellID == 0)
return 0;
(void)petFlag; // hardcoded 0 in the engine helper for this table
Game::Lua::PushString(L, "spell");
Game::Lua::PushNumber(L, static_cast<double>(spellID));
@@ -117,18 +107,13 @@ int __fastcall Script_GetActionInfo(void *L) {
if (type == Offsets::ACTION_TYPE_BAG_OR_MACRO) {
const uint32_t key = entry & Offsets::ACTION_PAYLOAD_MASK_BAG_OR_MACRO;
const int macroSlot = FindMacroSlot(key);
const int macroSlot = Action::Slot::MacroSlotForID(key);
if (macroSlot > 0) {
Game::Lua::PushString(L, "macro");
Game::Lua::PushNumber(L, static_cast<double>(macroSlot));
return 2;
}
// Not a macro — it's a bag item. We know the type but extracting
// the itemID from the bag-instance hash needs more reversing;
// see the file-level comment.
Game::Lua::PushString(L, "item");
Game::Lua::PushNil(L);
return 2;
return 0; // a macro button whose macro is gone — see the file comment
}
if (type == Offsets::ACTION_TYPE_ITEM_BY_ID) {
@@ -138,15 +123,74 @@ int __fastcall Script_GetActionInfo(void *L) {
return 2;
}
// Unknown type tag — surface as nil so callers don't get garbage.
Game::Lua::PushNil(L);
if (type == Offsets::ACTION_TYPE_EQUIPMENT_SET) {
// 3.3.5 `Script_GetActionInfo` (`FUN_005a8f10`): the type and the
// set's name.
const EquipmentSet::Set *set = EquipmentSet::Data::FindByID(
entry & ~static_cast<uint32_t>(Offsets::ACTION_TYPE_EQUIPMENT_SET));
if (set == nullptr)
return 0;
Game::Lua::PushString(L, "equipmentset");
Game::Lua::PushString(L, set->name.c_str());
return 2;
}
// Unknown type tag — nothing, so callers don't get garbage.
return 0;
}
int __fastcall Script_GetSpell(void *L) {
if (!Game::Lua::IsNumber(L, 1)) {
Game::Lua::Error(L, "Usage: C_ActionBar.GetSpell(actionID)");
return 0;
}
// The resolver bounds-checks the slot itself and answers 0 outside it.
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
uint32_t petFlag = 0;
const uint32_t spellID = reinterpret_cast<SlotToSpell_t>(
static_cast<uintptr_t>(Offsets::FUN_ACTION_SLOT_TO_SPELL))(
static_cast<uint32_t>(slot0), &petFlag);
Game::Lua::PushNumber(L, static_cast<double>(spellID));
return 1;
}
int __fastcall Script_IsMacroActionWithShowTooltip(void *L) {
if (!Game::Lua::IsNumber(L, 1)) {
Game::Lua::Error(L, "Usage: C_ActionBar.IsMacroActionWithShowTooltip(actionID)");
return 0;
}
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
const uint32_t macroID = Action::Slot::MacroIDForSlot(slot0);
Game::Lua::PushBool(L, macroID != 0 && Macro::ShowTooltip::HasShowTooltipDirective(macroID));
return 1;
}
const Game::Doc::Field kGetSpellArgs[] = {
Game::Doc::Req("actionID", "luaIndex"),
};
const Game::Doc::Field kGetSpellRets[] = {
Game::Doc::Req("spellID", "number"),
};
const Game::Doc::Function kGetSpellDoc{
"The spell an action stands for: a spell's own ID, a macro's spell, or an item's "
"on-use spell; 0 when there is none.",
kGetSpellArgs, kGetSpellRets};
const Game::Doc::Field kIsMacroActionWithShowTooltipRets[] = {
Game::Doc::Req("isMacroActionWithShowTooltip", "bool"),
};
const Game::Doc::Function kIsMacroActionWithShowTooltipDoc{
"Whether the action is a macro with an explicit #showtooltip line.",
kGetSpellArgs, kIsMacroActionWithShowTooltipRets};
} // namespace
static void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("GetActionInfo", &Script_GetActionInfo);
Game::Lua::RegisterTableFunction("C_ActionBar", "GetSpell", &Script_GetSpell, &kGetSpellDoc);
Game::Lua::RegisterTableFunction("C_ActionBar", "IsMacroActionWithShowTooltip",
&Script_IsMacroActionWithShowTooltip,
&kIsMacroActionWithShowTooltipDoc);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+117
View File
@@ -0,0 +1,117 @@
// 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/>.
// `GetActionCooldown` / `GetActionCount` / `IsConsumableAction` for macro
// slots whose `#showtooltip` / `#show` resolved to an ITEM. A spell
// resolution needs none of this — the engine reads a macro slot's spell from
// its primary-spell cache, which `Macro::ShowTooltip` writes — but the engine
// has no per-macro item field, so the item forms of these three are answered
// here, each with the engine's own helper for the item-by-ID slot case:
//
// - cooldown → `FUN_ITEM_QUERY_COOLDOWN` via `Item::Cooldown::PushCooldown`
// (the same triple `GetContainerItemCooldown` returns);
// - count → `FUN_ACTION_ITEM_COUNT`, the value `UseAction` caches per
// item-by-ID slot;
// - consumable → the rule of the inner `IsConsumableAction` (`0x004E5250`):
// ammo / thrown, or any on-use spell slot with negative
// charges.
//
// Registered in front of the engine globals (last registration wins) and a
// strict superset of them: every other slot tail-calls the engine function
// with the untouched stack.
#include "Game.h"
#include "Offsets.h"
#include "item/Cooldown.h"
#include "item/Record.h"
#include "macro/ShowTooltip.h"
#include <cstdint>
namespace Action::ItemState {
namespace {
using ScriptFn_t = int(__fastcall *)(void *L);
using ItemCount_t = uint32_t(__fastcall *)(uint32_t itemID);
int Engine(uintptr_t fn, void *L) {
return reinterpret_cast<ScriptFn_t>(fn)(L);
}
// True (and fills `info`) when stack[1] is a slot whose macro resolved to an item.
bool ItemTarget(void *L, Macro::ShowTooltip::Info *info) {
if (!Game::Lua::IsNumber(L, 1))
return false;
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
return Macro::ShowTooltip::ForSlot(slot0, info) &&
info->target == Macro::ShowTooltip::Target::Item;
}
int __fastcall Script_GetActionCooldown(void *L) {
Macro::ShowTooltip::Info info;
if (!ItemTarget(L, &info))
return Engine(Offsets::FUN_SCRIPT_GET_ACTION_COOLDOWN, L);
Item::Cooldown::PushCooldown(L, info.itemID);
return 3;
}
int __fastcall Script_GetActionCount(void *L) {
Macro::ShowTooltip::Info info;
if (!ItemTarget(L, &info))
return Engine(Offsets::FUN_SCRIPT_GET_ACTION_COUNT, L);
const uint32_t count = reinterpret_cast<ItemCount_t>(Offsets::FUN_ACTION_ITEM_COUNT)(
static_cast<uint32_t>(info.itemID));
Game::Lua::PushNumber(L, static_cast<double>(count));
return 1;
}
bool IsConsumable(int itemID) {
const uint8_t *record = Item::PeekRecord(static_cast<uint32_t>(itemID));
if (record == nullptr)
return false;
const uint32_t invType = Game::Read<uint32_t>(record, Offsets::OFF_ITEMSTATS_INVENTORY_TYPE);
if (invType == Offsets::INVTYPE_AMMO || invType == Offsets::INVTYPE_THROWN)
return true;
for (int i = 0; i < Offsets::ITEMSTATS_SPELL_SLOT_COUNT; ++i) {
const uint32_t spellID = Game::Read<uint32_t>(record, Offsets::OFF_ITEMSTATS_SPELL_ID + i * 4);
const uint32_t trigger = Game::Read<uint32_t>(record, Offsets::OFF_ITEMSTATS_SPELL_TRIGGER + i * 4);
const int32_t charges = Game::Read<int32_t>(record, Offsets::OFF_ITEMSTATS_SPELL_CHARGES + i * 4);
if (spellID != 0 && trigger == Offsets::ITEM_SPELLTRIGGER_ON_USE && charges < 0)
return true;
}
return false;
}
int __fastcall Script_IsConsumableAction(void *L) {
Macro::ShowTooltip::Info info;
if (!ItemTarget(L, &info))
return Engine(Offsets::FUN_SCRIPT_IS_CONSUMABLE_ACTION, L);
if (IsConsumable(info.itemID))
Game::Lua::PushNumber(L, 1.0);
else
Game::Lua::PushNil(L);
return 1;
}
void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("GetActionCooldown", &Script_GetActionCooldown);
Game::Lua::RegisterGlobalFunction("GetActionCount", &Script_GetActionCount);
Game::Lua::RegisterGlobalFunction("IsConsumableAction", &Script_IsConsumableAction);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace
} // namespace Action::ItemState
+54
View File
@@ -0,0 +1,54 @@
// 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/>.
// Dropping a spell on a slot that already holds it — 4.3.4's
// CGActionBar::PutActionInSlot:
//
// else if (CGActionBar::IsSpell(slot) && CGActionBar::GetSpell(slot, petSpell) == spellId)
// CGGameUI::DropCursorSpell();
//
// 1.12's FUN_ACTION_PLACE runs the same compare without the IsSpell gate,
// and FUN_ACTION_SLOT_TO_SPELL resolves a macro slot to the macro's spell.
// So a spell dropped on a `/cast <that spell>` macro was taken for a
// duplicate: the cursor cleared and the macro stayed. The gate is one call
// redirect: a slot that is not a spell action has no spell to match.
#include "Common.h"
#include "Game.h"
#include "Offsets.h"
#include <cstdint>
namespace Action::Place {
namespace {
using SlotToSpell_t = uint32_t(__fastcall *)(uint32_t slot0, uint32_t *outPetFlag);
uint32_t __fastcall SpellSlotSpell(uint32_t slot0, uint32_t *outPetFlag) {
const uint32_t action = reinterpret_cast<const uint32_t *>(Offsets::VAR_ACTION_TABLE)[slot0];
if (action == 0 || (action & Offsets::ACTION_TYPE_MASK) != Offsets::ACTION_TYPE_SPELL)
return 0;
return reinterpret_cast<SlotToSpell_t>(Offsets::FUN_ACTION_SLOT_TO_SPELL)(slot0, outPetFlag);
}
void Register() {
Common::RedirectCall(Offsets::CALL_ACTION_PLACE_SAME_SPELL, Offsets::FUN_ACTION_SLOT_TO_SPELL,
reinterpret_cast<const void *>(&SpellSlotSpell));
}
const Game::ModuleAutoRegister _autoreg{&Register};
} // namespace
} // namespace Action::Place
+114
View File
@@ -0,0 +1,114 @@
// 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/>.
// The range answer of an action button whose macro is aimed at a unit.
//
// 4.3.4 keeps that unit on the macro (MACRONODE::m_target: the `[@unit]` of
// the clause its display resolved from, or the target SetMacroSpell /
// SetMacroItem named), and CGActionBar::HasValidTarget range-checks the slot's
// spell against it in place of the current target. 1.12's slot range function
// FUN_ACTION_SLOT_RANGE already takes the unit as a GUID for its range check,
// and always passes 0, the selection. `Macro::ShowTooltip` keeps the unit (its
// `Info::unit`), and this answers for those slots with that GUID, in the
// engine's order: the range check, then the implicit-target test, where the
// unit standing in for the selection must exist. Every other slot goes to the
// engine function unchanged.
//
// The function's one caller, Script_IsActionInRange, is redirected rather than
// the function hooked.
#include "action/Range.h"
#include "Common.h"
#include "Game.h"
#include "Offsets.h"
#include "action/Slot.h"
#include "macro/ShowTooltip.h"
#include "object/Resolve.h"
#include "spell/Lookup.h"
#include "unit/Identity.h"
#include <cstdint>
namespace Action::Range {
namespace {
using SlotRange_t = int(__fastcall *)(int slot0, int *inRange);
using SlotToSpell_t = int(__fastcall *)(int slot0, uint32_t *outPetFlag);
using CheckRange_t = uint8_t(__fastcall *)(const void *caster, const uint8_t *record,
uint32_t guidLo, uint32_t guidHi, uint32_t report);
// The first implicit targets the engine answers for: case 0 of its table.
bool TakesUnitTarget(int32_t implicitTarget) {
switch (implicitTarget) {
case 6: case 21: case 23: case 25: case 26: case 35: case 45: case 57: case 61:
return true;
default:
return false;
}
}
uint64_t MacroUnit(int slot0) {
const uint32_t macroID = Action::Slot::MacroIDForSlot(slot0);
Macro::ShowTooltip::Info info{};
// Passive: this runs inside a Lua call, from a button's OnUpdate.
if (macroID == 0 || !Macro::ShowTooltip::LookupPassive(macroID, &info))
return 0;
return info.unit;
}
int __fastcall SlotRange_h(int slot0, int *inRange) {
const auto original = reinterpret_cast<SlotRange_t>(Offsets::FUN_ACTION_SLOT_RANGE);
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
return original(slot0, inRange);
const uint64_t unit = MacroUnit(slot0);
if (unit == 0)
return original(slot0, inRange);
const uint8_t *player = Unit::Identity::PlayerObject();
if (player == nullptr)
return 0;
uint32_t pet = 0;
const int spellID =
reinterpret_cast<SlotToSpell_t>(Offsets::FUN_ACTION_SLOT_TO_SPELL)(slot0, &pet);
const uint8_t *record = ::Spell::Lookup::RecordForID(spellID);
if (record == nullptr || pet != 0)
return 0;
if (!reinterpret_cast<CheckRange_t>(Offsets::FUN_CHECK_SPELL_TARGET_RANGE)(
player, record, static_cast<uint32_t>(unit), static_cast<uint32_t>(unit >> 32), 0)) {
*inRange = 0;
return 1;
}
const int32_t implicitTarget =
Game::Read<int32_t>(record, Offsets::OFF_SPELL_RECORD_EFFECT_IMPLICIT_TARGET_A);
if (!TakesUnitTarget(implicitTarget) || Object::ByGuid(Offsets::TYPEMASK_UNIT, unit) == nullptr)
return 0;
*inRange = 1;
return 1;
}
void Register() {
Common::RedirectCall(Offsets::CALL_IS_ACTION_IN_RANGE_SLOT_RANGE,
Offsets::FUN_ACTION_SLOT_RANGE,
reinterpret_cast<const void *>(&SlotRange_h));
}
const Game::ModuleAutoRegister _autoreg{&Register};
} // namespace
int Answer(int slot0, int *inRange) { return SlotRange_h(slot0, inRange); }
} // namespace Action::Range
+24
View File
@@ -0,0 +1,24 @@
// 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 Action::Range {
// IsActionInRange's answer for a slot (0-based, 0..119): 0 when it has none
// (IsActionInRange's nil), else 1 with `*inRange` 0 or 1. A macro aimed at a
// unit is checked against that unit.
int Answer(int slot0, int *inRange);
} // namespace Action::Range
+144
View File
@@ -0,0 +1,144 @@
// 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/>.
// `C_ActionBar.EnableActionRangeCheck(slot, enable)` and
// `ACTION_RANGE_CHECK_UPDATE(slot, isInRange, checksRange)`.
//
// Nothing in the client reacts to a distance (see Unit::InRangeEvent), so the
// enabled slots are checked every world tick, while a frame is registered for
// the event, and a slot fires when its answer changes. The answer is
// IsActionInRange's (Action::Range::Answer), macro unit included, so a slot
// whose action changes fires when the new action's answer differs.
//
// Enabling is counted per slot, as retail's ActionBarButtonRangeCheckFrame
// expects: it enables once for each button on a slot and disables once as
// each button leaves. Retail's buttons never call IsActionInRange; they take
// their first state from this event. So each enable makes the slot's next
// check fire, changed or not. A new Lua state (`/reload`) starts with no slot
// enabled.
#include "Game.h"
#include "Offsets.h"
#include "action/Range.h"
#include "event/Custom.h"
#include "tick/WorldTick.h"
#include <cstdint>
namespace Action::RangeCheck {
namespace {
enum class State : uint8_t { NoCheck, OutOfRange, InRange };
struct Slot {
int refs = 0;
bool pending = false; // fire on the next check, changed or not
State last = State::NoCheck;
};
Slot g_slots[Offsets::ACTION_TABLE_MAX_SLOTS];
const Game::Doc::Field kPayload[] = {
Game::Doc::Req("slot", "luaIndex"),
Game::Doc::Req("isInRange", "bool",
"Whether the action's target is in range. Should not be used if checksRange "
"is false."),
Game::Doc::Req("checksRange", "bool",
"False when no range check was made, for example when there is no target."),
};
const Game::Doc::Event kDoc{
"ActionBar",
"Fires when an action that has EnableActionRangeCheck on goes in or out of range of its "
"target.",
kPayload};
const Event::Custom::AutoReserve kEvent{"ACTION_RANGE_CHECK_UPDATE", &kDoc};
State Evaluate(int slot0) {
int inRange = 0;
if (Action::Range::Answer(slot0, &inRange) == 0)
return State::NoCheck;
return inRange != 0 ? State::InRange : State::OutOfRange;
}
void OnWorldTick() {
const int event = kEvent.Slot();
if (!Event::Custom::HasListeners(event))
return;
void *L = Game::Lua::State();
if (L == nullptr)
return;
const int top = Game::Lua::GetTop(L);
for (int slot0 = 0; slot0 < Offsets::ACTION_TABLE_MAX_SLOTS; ++slot0) {
Slot &slot = g_slots[slot0];
if (slot.refs == 0)
continue;
const State state = Evaluate(slot0);
if (!slot.pending && state == slot.last)
continue;
slot.pending = false;
slot.last = state;
Game::Lua::PushNumber(L, static_cast<double>(slot0 + 1));
Game::Lua::PushBool(L, state == State::InRange);
Game::Lua::PushBool(L, state != State::NoCheck);
Event::Custom::FireValues(event, L, top + 1, 3);
Game::Lua::SetTop(L, top);
}
}
const Tick::WorldTick::AutoSubscribe _tick{&OnWorldTick};
// --- C_ActionBar.EnableActionRangeCheck(slot, enable) -----------------------
int __fastcall Script_EnableActionRangeCheck(void *L) {
if (!Game::Lua::IsNumber(L, 1)) {
Game::Lua::Error(L, "Usage: C_ActionBar.EnableActionRangeCheck(slot, enable)");
return 0;
}
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
return 0;
Slot &slot = g_slots[slot0];
if (Game::Lua::ToBoolean(L, 2) != 0) {
++slot.refs;
slot.pending = true;
} else if (slot.refs > 0) {
--slot.refs;
}
return 0;
}
const Game::Doc::Field kEnableArgs[] = {
Game::Doc::Req("slot", "luaIndex"),
Game::Doc::Req("enable", "bool",
"True if changes in range for the action should dispatch "
"ACTION_RANGE_CHECK_UPDATE. False if the action no longer needs the event."),
};
const Game::Doc::Function kEnableDoc{
"Used with ACTION_RANGE_CHECK_UPDATE to be informed when an action goes in or out of range "
"of its target.",
kEnableArgs};
void RegisterLuaFunctions() {
for (Slot &slot : g_slots)
slot = Slot{};
Game::Lua::RegisterTableFunction("C_ActionBar", "EnableActionRangeCheck",
&Script_EnableActionRangeCheck, &kEnableDoc);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace
} // namespace Action::RangeCheck
+42
View File
@@ -0,0 +1,42 @@
// 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 "action/Slot.h"
#include "Offsets.h"
namespace Action::Slot {
int MacroSlotForID(uint32_t macroID) {
if (macroID == 0)
return 0;
// The engine's own scan: the 0-based slot, or 0xFFFFFFFF on a miss.
using IdToSlot_t = uint32_t(__fastcall *)(int macroID);
const uint32_t slot0 = reinterpret_cast<IdToSlot_t>(
static_cast<uintptr_t>(Offsets::FUN_MACRO_ID_TO_SLOT))(static_cast<int>(macroID));
return slot0 == 0xFFFFFFFFu ? 0 : static_cast<int>(slot0) + 1;
}
uint32_t MacroIDForSlot(int slot0) {
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
return 0;
auto *table = reinterpret_cast<const uint32_t *>(
static_cast<uintptr_t>(Offsets::VAR_ACTION_TABLE));
const uint32_t entry = table[slot0];
if (entry == 0 || (entry & Offsets::ACTION_TYPE_MASK) != Offsets::ACTION_TYPE_BAG_OR_MACRO)
return 0;
const uint32_t key = entry & Offsets::ACTION_PAYLOAD_MASK_BAG_OR_MACRO;
return MacroSlotForID(key) != 0 ? key : 0;
}
} // namespace Action::Slot
+36
View File
@@ -0,0 +1,36 @@
// 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
#include <cstdint>
// Action-slot ↔ macro decoding shared by every module that has to answer
// "which macro sits in this action slot" (`GetActionInfo`, the
// `#showtooltip` display overrides). The action table stores macroIDs under
// the `0x40000000` tag; the macro-slot map says which of those ids still
// name a macro (the rest are buttons whose macro is gone). Pure C — no Lua
// stack.
namespace Action::Slot {
// 1-based macro slot holding `macroID` — the same linear scan of
// `VAR_MACRO_SLOT_MAP` the engine's `FUN_MACRO_ID_TO_SLOT` does — or 0 when
// no macro has that id (0 is never a macroID).
int MacroSlotForID(uint32_t macroID);
// The macroID in action slot `slot0` (0-based, `< ACTION_TABLE_MAX_SLOTS`),
// or 0 when the slot is empty, isn't `0x40000000`-tagged, or its macro is gone.
uint32_t MacroIDForSlot(int slot0);
} // namespace Action::Slot
+148
View File
@@ -0,0 +1,148 @@
// 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/>.
// The item behind an action slot, 4.3.4's CGActionBar::GetItem: an item-by-ID
// action's item, or the item a macro's `#showtooltip` / `#show` resolved to
// (1.12 keeps no item per macro, so `Macro::ShowTooltip` holds it). Both
// readers below peek the item cache and never query it, as 4.3.4 does.
//
// IsStackableAction the item's max stack is more than 1 —
// 4.3.4's IsStackableAucItem. The global
// answers 1/nil, the C_ActionBar form a bool.
// GetItemActionOnEquipSpellID the item's first on-equip spell (trigger 1),
// nil when it has none.
#include "Game.h"
#include "Offsets.h"
#include "item/Record.h"
#include "macro/ShowTooltip.h"
#include <cstdint>
namespace Action::SlotItem {
namespace {
uint32_t ItemForSlot(int slot0) {
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
return 0;
const uint32_t entry = reinterpret_cast<const uint32_t *>(
static_cast<uintptr_t>(Offsets::VAR_ACTION_TABLE))[slot0];
if ((entry & Offsets::ACTION_TYPE_MASK) == Offsets::ACTION_TYPE_ITEM_BY_ID)
return entry & Offsets::ACTION_PAYLOAD_MASK_ITEM_BY_ID;
Macro::ShowTooltip::Info info;
if (Macro::ShowTooltip::ForSlot(slot0, &info) &&
info.target == Macro::ShowTooltip::Target::Item)
return static_cast<uint32_t>(info.itemID);
return 0;
}
// Reads the 1-based slot at stack[1]; false (after the usage error) when it
// is not a number.
bool SlotArg(void *L, const char *usage, int *slot0) {
if (!Game::Lua::IsNumber(L, 1)) {
Game::Lua::Error(L, usage);
return false;
}
*slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
return true;
}
bool IsStackable(int slot0) {
const uint8_t *record = ::Item::PeekRecord(ItemForSlot(slot0));
return record != nullptr && Game::Read<uint32_t>(record, Offsets::OFF_ITEMSTATS_STACKABLE) > 1;
}
int __fastcall Script_IsStackableAction(void *L) {
int slot0;
if (!SlotArg(L, "Usage: IsStackableAction(slot)", &slot0))
return 0;
if (IsStackable(slot0))
Game::Lua::PushNumber(L, 1.0);
else
Game::Lua::PushNil(L);
return 1;
}
int __fastcall Script_C_IsStackableAction(void *L) {
int slot0;
if (!SlotArg(L, "Usage: C_ActionBar.IsStackableAction(actionID)", &slot0))
return 0;
Game::Lua::PushBool(L, IsStackable(slot0));
return 1;
}
int __fastcall Script_GetItemActionOnEquipSpellID(void *L) {
int slot0;
if (!SlotArg(L, "Usage: C_ActionBar.GetItemActionOnEquipSpellID(actionID)", &slot0))
return 0;
const uint8_t *record = ::Item::PeekRecord(ItemForSlot(slot0));
if (record == nullptr)
return 0;
for (int i = 0; i < Offsets::ITEMSTATS_SPELL_SLOT_COUNT; ++i) {
const uint32_t spellID = Game::Read<uint32_t>(record, Offsets::OFF_ITEMSTATS_SPELL_ID + i * 4);
const uint32_t trigger = Game::Read<uint32_t>(record, Offsets::OFF_ITEMSTATS_SPELL_TRIGGER + i * 4);
if (spellID != 0 && trigger == Offsets::ITEM_SPELLTRIGGER_ON_EQUIP) {
Game::Lua::PushNumber(L, static_cast<double>(spellID));
return 1;
}
}
return 0;
}
// --- Documentation ----------------------------------------------------------
const Game::Doc::Field kSlotArgs[] = {
Game::Doc::Req("slot", "number", "The action slot, 1 to 120."),
};
const Game::Doc::Field kIsStackableRets[] = {
Game::Doc::Opt("isStackable", "number", nullptr,
"1 if the slot's item stacks, else nil."),
};
const Game::Doc::Function kIsStackableAction{
"Returns 1 if an action slot holds an item that stacks.",
kSlotArgs, kIsStackableRets, "ActionBar"};
const Game::Doc::Field kActionIDArgs[] = {
Game::Doc::Req("actionID", "luaIndex"),
};
const Game::Doc::Field kCIsStackableRets[] = {
Game::Doc::Req("isStackableAction", "bool"),
};
const Game::Doc::Function kCIsStackableAction{
"Whether the action's item stacks.",
kActionIDArgs, kCIsStackableRets};
const Game::Doc::Field kOnEquipRets[] = {
Game::Doc::Opt("onEquipSpellID", "number", nullptr,
"Nil when the action has no item or its item has no on-equip spell."),
};
const Game::Doc::Function kGetItemActionOnEquipSpellID{
"The spell the action's item grants while equipped.",
kActionIDArgs, kOnEquipRets};
} // namespace
static void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("IsStackableAction", &Script_IsStackableAction,
&kIsStackableAction);
Game::Lua::RegisterTableFunction("C_ActionBar", "IsStackableAction",
&Script_C_IsStackableAction, &kCIsStackableAction);
Game::Lua::RegisterTableFunction("C_ActionBar", "GetItemActionOnEquipSpellID",
&Script_GetItemActionOnEquipSpellID,
&kGetItemActionOnEquipSpellID);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace Action::SlotItem
+125
View File
@@ -0,0 +1,125 @@
// 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/>.
// `ACTION_USABLE_CHANGED(changes)` — the slots whose usable / noMana pair
// changed, as `{ slot, usable, noMana }` entries.
//
// The engine's bulk refresh FUN_ACTION_UPDATE_USABLE already finds them: it
// computes each slot with FUN_ACTION_SLOT_USABLE, compares the pair against
// the caches IsUsableAction reads, stores a changed pair, and signals the
// argument-less ACTIONBAR_UPDATE_USABLE once when any changed. Two of its
// calls are redirected. The per-slot call records the slots whose pair differs
// from the caches, the same compare the engine makes next. The signal sends
// ACTIONBAR_UPDATE_USABLE unchanged, then this event with the recorded slots.
//
// The per-slot refresh in FUN_ACTION_SLOT_CHANGED_NOTIFY stores its pair
// without this event; it signals ACTIONBAR_SLOT_CHANGED for the slot instead.
#include "Common.h"
#include "Game.h"
#include "Offsets.h"
#include "event/Custom.h"
#include <cstdint>
#include <cstring>
namespace Action::UsableChanged {
namespace {
using SlotUsable_t = uint32_t(__fastcall *)(uint32_t slot0, uint32_t *outNoMana);
using FireEvent_t = void(__fastcall *)(int eventID);
struct Change {
uint32_t slot0;
bool usable;
bool noMana;
};
// This refresh's changes. The loop runs slots 0..119 in order, so slot 0
// starts a new list.
Change g_changes[Offsets::ACTION_TABLE_MAX_SLOTS];
int g_count = 0;
const Game::Doc::Field kStateFields[] = {
Game::Doc::Req("slot", "luaIndex"),
Game::Doc::Req("usable", "bool"),
Game::Doc::Req("noMana", "bool"),
};
const Game::Doc::Structure kState{"ActionUsableState", "ActionBar", kStateFields};
const Game::Doc::Field kPayload[] = {
Game::Doc::Req("changes", "table", "An ActionUsableState for each slot that changed."),
};
const Game::Doc::Event kDoc{
"ActionBar", "Fires when the usable or noMana state of one or more action slots changes.",
kPayload};
const Event::Custom::AutoReserve kEvent{"ACTION_USABLE_CHANGED", &kDoc};
uint32_t __fastcall SlotUsable_h(uint32_t slot0, uint32_t *outNoMana) {
const uint32_t usable =
reinterpret_cast<SlotUsable_t>(Offsets::FUN_ACTION_SLOT_USABLE)(slot0, outNoMana);
if (slot0 == 0)
g_count = 0;
const auto *usableCache =
reinterpret_cast<const uint32_t *>(static_cast<uintptr_t>(Offsets::VAR_ACTION_USABLE));
const auto *noManaCache =
reinterpret_cast<const uint32_t *>(static_cast<uintptr_t>(Offsets::VAR_ACTION_NO_MANA));
if (slot0 < static_cast<uint32_t>(Offsets::ACTION_TABLE_MAX_SLOTS) &&
g_count < Offsets::ACTION_TABLE_MAX_SLOTS &&
(usable != usableCache[slot0] || *outNoMana != noManaCache[slot0]))
g_changes[g_count++] = {slot0, usable != 0, *outNoMana != 0};
return usable;
}
void __fastcall FireUsable_h(int eventID) {
// Copied first: the handlers below can run another refresh.
Change changes[Offsets::ACTION_TABLE_MAX_SLOTS];
const int count = g_count;
std::memcpy(changes, g_changes, sizeof(Change) * count);
g_count = 0;
reinterpret_cast<FireEvent_t>(Offsets::FUN_FIRE_EVENT_NO_ARGS)(eventID);
const int event = kEvent.Slot();
void *L = Game::Lua::State();
if (count == 0 || !Event::Custom::HasListeners(event) || L == nullptr)
return;
const int top = Game::Lua::GetTop(L);
Game::Lua::NewTable(L);
for (int i = 0; i < count; ++i) {
Game::Lua::PushNumber(L, static_cast<double>(i + 1));
Game::Lua::NewTable(L);
Game::Lua::SetFieldNumber(L, "slot", static_cast<double>(changes[i].slot0 + 1));
Game::Lua::SetFieldBool(L, "usable", changes[i].usable);
Game::Lua::SetFieldBool(L, "noMana", changes[i].noMana);
Game::Lua::RawSet(L, -3);
}
Game::Lua::SetN(L, -1, count);
Event::Custom::FireValues(event, L, top + 1, 1);
Game::Lua::SetTop(L, top);
}
void Register() {
Common::RedirectCall(Offsets::CALL_UPDATE_USABLE_SLOT_USABLE, Offsets::FUN_ACTION_SLOT_USABLE,
reinterpret_cast<const void *>(&SlotUsable_h));
Common::RedirectCall(Offsets::CALL_UPDATE_USABLE_FIRE, Offsets::FUN_FIRE_EVENT_NO_ARGS,
reinterpret_cast<const void *>(&FireUsable_h));
}
const Game::ModuleAutoRegister _autoreg{&Register};
} // namespace
} // namespace Action::UsableChanged
+37
View File
@@ -0,0 +1,37 @@
// This file is part of ClassicAPI.
//
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
// The `ActionButtonUseKeyDown` cvar — registered by 4.3.4's engine
// (GameUI_CVar.cpp, "Activate the action button on a keydown") and read only
// by FrameXML's action-button key handlers, which this project's addon ports
// (Util/ActionButton.lua). The engine half is the registration. The default
// is 0, keeping 1.12's action buttons firing on key release; 4.3.4 shipped 1.
#include "Game.h"
#include "Offsets.h"
#include "cvar/Factory.h"
namespace Action::UseKeyDown {
namespace {
void Register() {
CVar::Factory::Register("ActionButtonUseKeyDown", "Activate the action button on a keydown",
Offsets::CVAR_CATEGORY_GAME, "0");
}
const Game::ModuleAutoRegister _autoreg{&Register};
} // namespace
} // namespace Action::UseKeyDown
+346 -225
View File
@@ -11,31 +11,51 @@
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
// Embedded `!!!ClassicAPI` addon fallback. When the user doesn't have
// the addon installed on disk, this module makes the engine think it
// does — without writing anything to the filesystem.
// Embedded addons. When the user doesn't have an addon installed on disk,
// this module makes the engine think they do — without writing anything
// to the filesystem. The addons are `Manifest::kAddons` (the `ADDONS`
// list in CMakeLists.txt): `!!!ClassicAPI`, which loads at login, and
// `ClassicAPI_DebugTools` and `ClassicAPI_EventTrace`, which are
// `## LoadOnDemand` behind the `/dump` / `/fstack` / `/etrace` stubs in
// `!!!ClassicAPI` — retail's chat-frame + Blizzard_DebugTools /
// Blizzard_EventTrace split. (The `Blizzard_` name is not
// available to us: the engine moves loose `Interface\AddOns\Blizzard*`
// folders aside at startup, `MoveAsideLooseInterface`, and refuses a
// `Blizzard_*` TOC without a signature.)
//
// How:
//
// 1. The CMake build embeds every file under `AddOns/!!!ClassicAPI/`
// into a generated header (`embedded_classicapi.h`) as a byte
// array per file plus a `{path, data, size}` manifest.
// 1. The CMake build embeds each listed addon as one RCDATA resource,
// a gzipped pack of its files, plus a generated
// `{path, resourceId, index}` manifest (`embedded_resources.h`).
//
// 2. We hook the engine's file-read function at `FUN_FILE_READ`.
// When the engine asks for a path under
// `Interface\AddOns\!!!ClassicAPI\`, we allocate a Storm buffer
// `Interface\AddOns\<embedded addon>\`, we allocate a Storm buffer
// via the same allocator the engine itself uses, copy the
// embedded content in, and hand it back. The caller's normal
// `SMemFree` reclaims it on completion — no special lifetime.
// A TOC then goes through `AddOns::TocRewrite`, as an installed
// addon's does, so its file lines can carry `[AllowLoadGameType ...]`
// / `[ExcludeLoadGameType ...]` conditions.
//
// 3. We post-hook the engine's `FUN_ADDON_INIT`. After the engine's
// own `Interface\AddOns\` scan finishes, we call the TOC parser
// directly with `"!!!ClassicAPI"`. The parser opens its TOC via
// our hooked read function and registers the addon as a normal
// entry. The TOC parser is dedup-safe: if the user already has
// the addon on disk, the engine's scan picked it up, the
// hash-table lookup hits, and our call is a no-op. So the
// conditional "only if not on disk" behavior is free.
// 3. We hook the exists-check `FUN_FILE_EXISTS` so it answers the same
// way for the same paths. Without it every embedded file reads fine
// but reports as missing — the per-addon loader would skip an
// embedded `Bindings.xml`, and `Xml::ScriptPath` would never find an
// embedded `<Script file="sub\x.lua">`.
//
// 4. We pre-hook the engine's `FUN_ADDON_SCAN_FULL` and call the TOC
// parser with each embedded name before the scan runs. The registry
// is empty there (the login init resets it just before), so our
// entries are the first records and the load pass — which walks the
// records in registration order — loads `!!!ClassicAPI` first. The
// scan's own `## LoadWith:` pass then sees them like any disk addon.
// The parser is dedup-safe: when the user also has an addon on disk,
// the scan's call for that folder hits the hash table and is a no-op.
//
// Every embedded addon is hidden from the addon list and force-enabled,
// the way Blizzard's own addons are always available and never listed.
//
// Same pattern WeirdUtils.dll uses (we reverse-engineered it from
// `0x10015A74` while figuring this out). The addon load pass then
@@ -43,11 +63,20 @@
// `Compat.lua`, `Util\Print.lua`, etc. all surface from
// embedded buffers.
#include "embedded_classicapi.h"
#include "embedded_resources.h"
#include "Common.h"
#include "Game.h"
#include "Offsets.h"
#include "addons/Embedded.h"
#include "addons/EngineIO.h"
#include "addons/FlavorBindings.h"
#include "addons/FlavorToc.h"
#include "addons/Registry.h"
#include "addons/Toc.h"
#include "addons/TocRewrite.h"
#include "bindings/Inject.h"
#include "embed/Resource.h"
#include <cstdint>
#include <cstdio>
@@ -57,77 +86,80 @@ namespace Addons::Embedded {
namespace {
constexpr const char *kAddonName = "!!!ClassicAPI";
constexpr const char *kAddonTocFile = "!!!ClassicAPI.toc";
using Manifest::kAddonCount;
using Manifest::kAddons;
// `Interface\AddOns\!!!ClassicAPI\` — the prefix the engine
// constructs for any of our addon's files. Comparing case-
// Developer marker. When this file exists in an on-disk addon folder,
// the disk copy of that addon wins unconditionally (see
// `DiskHasDevMarker` / `DecideSource`). It is gitignored, excluded from
// the embed, and the release ships only the DLL — so it can only exist
// where a developer deliberately created it, never in a normal user's
// install.
constexpr const char *kDevMarkerFile = ".classicapi-dev";
// `Interface\AddOns\` — the prefix the engine constructs for any addon
// file; the manifest paths are relative to it. Comparing case-
// insensitively because the TOC parser uses `Interface\AddOns\%s\…`
// where %s comes from the on-disk directory name, and Windows file
// paths are case-insensitive.
constexpr const char *kAddonPathPrefix = "Interface\\AddOns\\!!!ClassicAPI\\";
constexpr size_t kAddonPathPrefixLen = 30; // length of the literal above
constexpr const char *kAddOnsPrefix = "Interface\\AddOns\\";
char NormalizeChar(char c) {
if (c == '/') return '\\';
if (c >= 'A' && c <= 'Z') return static_cast<char>(c + 32);
return c;
}
bool PathEqualsCI(const char *a, const char *b) {
while (*a && *b) {
if (NormalizeChar(*a) != NormalizeChar(*b)) return false;
++a; ++b;
// `path` with the case-insensitive `prefix` stripped, NULL when it does
// not start with it.
const char *StripPrefixCI(const char *path, const char *prefix) {
while (*prefix) {
if (*path == '\0') return nullptr;
if (Common::FoldPathChar(*path) != Common::FoldPathChar(*prefix)) return nullptr;
++path; ++prefix;
}
return *a == *b;
return path;
}
// Strip the `Interface\AddOns\!!!ClassicAPI\` prefix and return the
// suffix (e.g. `Util\Print.lua`) on a match, NULL otherwise.
const char *StripAddonPrefix(const char *path) {
if (path == nullptr) return nullptr;
const char *p = path;
const char *q = kAddonPathPrefix;
while (*q) {
if (*p == '\0') return nullptr;
if (NormalizeChar(*p) != NormalizeChar(*q)) return nullptr;
++p; ++q;
int IndexOfAddon(const char *name) {
for (size_t i = 0; i < kAddonCount; ++i) {
if (Common::SamePath(name, kAddons[i]))
return static_cast<int>(i);
}
return p;
return -1;
}
const ClassicAPIFiles::File *LookupEmbedded(const char *suffix) {
for (size_t i = 0; i < ClassicAPIFiles::kFileCount; ++i) {
if (PathEqualsCI(suffix, ClassicAPIFiles::kFiles[i].path))
return &ClassicAPIFiles::kFiles[i];
// The embedded addon `path` lies in (`Interface\AddOns\<addon>\…`), or -1.
// `*relPath` gets the manifest-relative part (`<addon>\Util\Print.lua`).
int MatchAddonPath(const char *path, const char **relPath) {
if (path == nullptr) return -1;
const char *rel = StripPrefixCI(path, kAddOnsPrefix);
if (rel == nullptr) return -1;
for (size_t i = 0; i < kAddonCount; ++i) {
const char *rest = StripPrefixCI(rel, kAddons[i]);
if (rest != nullptr && Common::FoldPathChar(*rest) == '\\') {
*relPath = rel;
return static_cast<int>(i);
}
}
return nullptr;
return -1;
}
// Storm allocator — same one `FUN_FILE_READ` uses internally. Buffer
// allocated here is freed cleanly by the caller's standard `SMemFree`
// (`FUN_STORM_SMEM_FREE`). `__stdcall` per the function's `RET 0x10`
// (4 args × 4 bytes = 16) epilogue.
// __stdcall void *SMemAlloc(size_t size, const char *file, int line, int flags)
using SMemAlloc_t = void *(__stdcall *)(size_t size, const char *file, int line, int flags);
// The embedded bytes for manifest path `relPath`; `data` is NULL when it
// is not embedded.
Embed::Bytes LookupEmbedded(const char *relPath) {
const Manifest::File *file = Embed::FindFile(Manifest::kFiles, relPath);
if (file == nullptr)
return {nullptr, 0};
return Embed::File(file->resourceId, file->index);
}
// `FUN_FILE_READ` — same shape derived from the Octo decompile.
// Calling convention is `__stdcall` (callee cleans 28 bytes via
// `RET 0x1C`), not `__cdecl` — confirmed via the function epilogue.
// Getting this wrong silently corrupts the caller's stack frame.
// __stdcall int FileRead(int unused, const char *path, void **outBuf,
// size_t *outSize, size_t extraBytes,
// int flag1, int flag2)
using FileRead_t = int(__stdcall *)(int unused, const char *path, void **outBuf,
size_t *outSize, size_t extraBytes,
int flag1, int flag2);
FileRead_t FileRead_o = nullptr;
// Engine file I/O + Storm allocator — see addons/EngineIO.h for the shapes and
// the __stdcall / ESP-drift hazard. A buffer we SMemAlloc here is freed cleanly
// by the caller's standard SMemFree in turn.
using AddOns::EngineIO::FileExistsFn;
using AddOns::EngineIO::FileReadFn;
using AddOns::EngineIO::SMemAllocFn;
using AddOns::EngineIO::SMemFreeFn;
// Storm-allocator free. Used to release the disk-TOC buffer after we
// scrape its version line — same path the engine itself uses when
// `FileRead_o` succeeded and the caller's done with the result.
// __stdcall void SMemFree(void *buf, const char *file, int line, int flags)
using SMemFree_t = void(__stdcall *)(void *buf, const char *file, int line, int flags);
// The trampolines to the original FUN_FILE_READ / FUN_FILE_EXISTS (installed
// by the co-hooks below).
FileReadFn FileRead_o = nullptr;
FileExistsFn FileExists_o = nullptr;
// Extracts the value of the `## Version: X` line from a TOC byte
// buffer. Writes into `out` (size `outSize`) and returns true on
@@ -135,38 +167,35 @@ using SMemFree_t = void(__stdcall *)(void *buf, const char *file, int line, int
// sensitive on the key. Returns false if no Version line is found.
bool ExtractTocVersion(const char *content, size_t size,
char *out, size_t outSize) {
static const char kKey[] = "## Version:";
constexpr size_t kKeyLen = sizeof(kKey) - 1;
for (size_t i = 0; i + kKeyLen <= size; ++i) {
const bool atLineStart = (i == 0) || content[i - 1] == '\n';
if (!atLineStart) continue;
if (std::memcmp(content + i, kKey, kKeyLen) != 0) continue;
const char *p = content + i + kKeyLen;
const char *end = content + size;
while (p < end && (*p == ' ' || *p == '\t')) ++p;
size_t j = 0;
while (p < end && *p != '\r' && *p != '\n' && j + 1 < outSize) {
out[j++] = *p++;
}
while (j > 0 && (out[j - 1] == ' ' || out[j - 1] == '\t')) --j;
out[j] = '\0';
return j > 0;
const char *v = nullptr;
size_t n = 0;
if (outSize == 0)
return false;
if (!AddOns::Toc::FindValue(content, size, "Version", &v, &n) || n == 0) {
out[0] = '\0';
return false;
}
if (outSize > 0) out[0] = '\0';
return false;
if (n >= outSize)
n = outSize - 1;
std::memcpy(out, v, n);
out[n] = '\0';
return true;
}
// Returns -1/0/+1 for `a < b` / `a == b` / `a > b`. "DEV" is a
// sentinel meaning "newer than any real release" — local dev builds
// always win against installed-on-disk versions. Otherwise the two
// strings are walked as dot-separated numeric semver components
// Returns -1/0/+1 for `a < b` / `a == b` / `a > b`. "DEV" is the
// local-build sentinel: two DEV builds are equal, but a DEV build sorts
// BELOW any real release. Dev-over-release precedence is signalled
// explicitly by the `.classicapi-dev` marker now — NOT by the toc
// version — so a stray `## Version: DEV` disk copy (repo clone / old
// bundle) never silently shadows a newer embedded release. Otherwise
// the two strings are walked as dot-separated numeric semver components
// (`1.2` < `1.10`).
int CompareVersions(const char *a, const char *b) {
const bool aDev = std::strcmp(a, "DEV") == 0;
const bool bDev = std::strcmp(b, "DEV") == 0;
if (aDev && bDev) return 0;
if (aDev) return 1;
if (bDev) return -1;
if (aDev) return -1;
if (bDev) return 1;
while (*a || *b) {
int va = 0, vb = 0;
while (*a >= '0' && *a <= '9') { va = va * 10 + (*a - '0'); ++a; }
@@ -181,47 +210,63 @@ int CompareVersions(const char *a, const char *b) {
return 0;
}
// Pre-extracted embedded TOC version, populated lazily on first
// FileRead_h call under our prefix. Empty until populated.
char g_embeddedVersion[64] = "";
// Which source wins the embed-vs-disk comparison, decided once on
// first relevant file read.
// Which source wins the embed-vs-disk comparison, decided per addon once
// on its first file read.
enum class Source { Undecided, Disk, Embedded };
Source g_source = Source::Undecided;
Source g_source[kAddonCount] = {};
void EnsureEmbeddedVersionExtracted() {
if (g_embeddedVersion[0] != '\0') return;
for (size_t i = 0; i < ClassicAPIFiles::kFileCount; ++i) {
if (PathEqualsCI(kAddonTocFile, ClassicAPIFiles::kFiles[i].path)) {
ExtractTocVersion(
reinterpret_cast<const char *>(ClassicAPIFiles::kFiles[i].data),
ClassicAPIFiles::kFiles[i].size,
g_embeddedVersion, sizeof(g_embeddedVersion));
return;
}
}
// True iff addon `addon`'s on-disk folder contains the `.classicapi-dev`
// marker. Asked of the ORIGINAL `FUN_FILE_EXISTS` (bypassing our embed
// hook), so it reflects a real file on disk / in an MPQ — never an
// embedded copy. That makes it a clean "is this a developer working
// tree" signal: the marker is gitignored + excluded from the embed and
// the release ships only the DLL, so a normal user's install can't
// carry it.
bool DiskHasDevMarker(int addon) {
char fullPath[256];
std::snprintf(fullPath, sizeof(fullPath), "%s%s\\%s", kAddOnsPrefix,
kAddons[addon], kDevMarkerFile);
return FileExists_o(fullPath, 1) != 0;
}
// Decide whether disk or embedded should serve all reads for this
// addon. Called on the first FileRead_h call with a matching prefix.
// Reads the on-disk TOC via the original `FUN_FILE_READ` (bypassing
// our hook), parses its version, compares to the embedded version,
// and caches the winner. If disk has no TOC at all, embedded wins by
// default.
void DecideSource() {
if (g_source != Source::Undecided) return;
EnsureEmbeddedVersionExtracted();
// Decide whether disk or embedded should serve all reads for addon
// `addon`. Called on the first FileRead_h / FileExists_h call under its
// folder. The `.classicapi-dev` marker forces disk unconditionally
// (explicit developer override). Otherwise reads the on-disk TOC via the
// original `FUN_FILE_READ` (bypassing our hook), parses its version,
// compares to the embedded version, and caches the newer. If disk has no
// TOC at all, embedded wins by default.
void DecideSource(int addon) {
if (g_source[addon] != Source::Undecided) return;
// Explicit developer override: disk wins regardless of version. This
// is how a dev keeps disk precedence when running local Lua against a
// *released* DLL (where the embedded version would otherwise be newer
// and win). Dev intent lives in this marker, decoupled from the toc
// version — so users never get silently shadowed by a stray copy.
if (DiskHasDevMarker(addon)) {
g_source[addon] = Source::Disk;
return;
}
char embeddedVersion[64] = "";
char tocRelPath[256];
std::snprintf(tocRelPath, sizeof(tocRelPath), "%s\\%s.toc",
kAddons[addon], kAddons[addon]);
const Embed::Bytes toc = LookupEmbedded(tocRelPath);
if (toc.data != nullptr)
ExtractTocVersion(reinterpret_cast<const char *>(toc.data), toc.size,
embeddedVersion, sizeof(embeddedVersion));
char fullPath[256];
std::snprintf(fullPath, sizeof(fullPath), "%s%s",
kAddonPathPrefix, kAddonTocFile);
std::snprintf(fullPath, sizeof(fullPath), "%s%s", kAddOnsPrefix,
tocRelPath);
void *diskBuf = nullptr;
size_t diskSize = 0;
const int ok = FileRead_o(0, fullPath, &diskBuf, &diskSize, 1, 1, 0);
if (ok == 0 || diskBuf == nullptr) {
g_source = Source::Embedded;
g_source[addon] = Source::Embedded;
return;
}
@@ -232,18 +277,61 @@ void DecideSource() {
// Free the disk buffer we just borrowed — we only needed it for
// the version-line scrape. The actual content for the engine's
// TOC read comes through the regular hook path below.
auto SMemFree = reinterpret_cast<SMemFree_t>(Offsets::FUN_STORM_SMEM_FREE);
auto SMemFree = reinterpret_cast<SMemFreeFn>(Offsets::FUN_STORM_SMEM_FREE);
SMemFree(diskBuf, __FILE__, __LINE__, 0);
// Missing or unparseable disk version → assume it's older than
// anything we ship, embedded wins.
if (diskVersion[0] == '\0') {
g_source = Source::Embedded;
g_source[addon] = Source::Embedded;
return;
}
const int cmp = CompareVersions(g_embeddedVersion, diskVersion);
g_source = (cmp > 0) ? Source::Embedded : Source::Disk;
const int cmp = CompareVersions(embeddedVersion, diskVersion);
g_source[addon] = (cmp > 0) ? Source::Embedded : Source::Disk;
}
// Serves one file of embedded addon `addon` from whichever source won
// DecideSource.
int ReadAddonFile(int addon, const char *relPath, int unused, const char *path,
void **outBuf, size_t *outSize, size_t extraBytes, int flag1,
int flag2) {
DecideSource(addon);
if (g_source[addon] == Source::Disk) {
// Disk version is at least as new — serve disk. If disk
// doesn't have this specific file (e.g. embedded has files
// disk doesn't), fall through and try embedded.
const int diskResult = FileRead_o(unused, path, outBuf, outSize,
extraBytes, flag1, flag2);
if (diskResult != 0) return diskResult;
}
// Source::Embedded path, OR Source::Disk-but-file-missing fallback.
// Look up the embedded version and synthesize a Storm buffer the
// caller can free normally.
const Embed::Bytes entry = LookupEmbedded(relPath);
if (entry.data == nullptr) {
// Not in our embedded set either — let the engine try disk
// one more time (returns 0 if that also fails). Covers
// pathological cases like an empty disk install + embedded
// missing some file.
return FileRead_o(unused, path, outBuf, outSize, extraBytes,
flag1, flag2);
}
auto SMemAlloc = reinterpret_cast<SMemAllocFn>(
Offsets::FUN_STORM_SMEM_ALLOC);
const size_t totalSize = entry.size + extraBytes;
void *buf = SMemAlloc(totalSize, __FILE__, __LINE__, 0);
if (buf == nullptr) return 0;
std::memcpy(buf, entry.data, entry.size);
if (extraBytes > 0) {
std::memset(static_cast<uint8_t *>(buf) + entry.size, 0, extraBytes);
}
if (outBuf != nullptr) *outBuf = buf;
if (outSize != nullptr) *outSize = entry.size;
return 1;
}
int __stdcall FileRead_h(int unused, const char *path, void **outBuf,
@@ -257,111 +345,130 @@ int __stdcall FileRead_h(int unused, const char *path, void **outBuf,
return 1;
}
const char *suffix = StripAddonPrefix(path);
if (suffix == nullptr) {
// Path isn't under `Interface\AddOns\!!!ClassicAPI\` — straight
// pass-through, we don't care.
return FileRead_o(unused, path, outBuf, outSize, extraBytes,
flag1, flag2);
const char *relPath = nullptr;
const int addon = MatchAddonPath(path, &relPath);
if (addon < 0) {
// Not an embedded addon. If this is a base-TOC read for a multi-flavor
// addon that ships only `<Name>_Turtle.toc` / `_ClassicAPI.toc`, serve
// that in place of the missing `<Name>.toc` so it registers and loads
// (see addons/FlavorToc.h).
int result;
if (AddOns::FlavorToc::TryHandle(unused, path, outBuf, outSize,
extraBytes, flag1, flag2, FileRead_o)) {
result = 1;
} else if (AddOns::FlavorBindings::TryHandle(unused, path, outBuf, outSize,
extraBytes, flag1, flag2,
FileRead_o)) {
// Flavor-specific addon keybindings: serve `Bindings_Turtle.xml` /
// `Bindings_ClassicAPI.xml` for a `…\AddOns\<Name>\Bindings.xml`
// read (see addons/FlavorBindings.h). The paired exists-check
// co-hook lives in that module.
result = 1;
} else {
result = FileRead_o(unused, path, outBuf, outSize, extraBytes,
flag1, flag2);
}
// Per-line TOC directives: evaluate `[Condition]` and expand
// `[Variable]` tokens on this addon TOC's file lines so the load
// pass sees clean paths (see addons/TocRewrite.h). No-op unless
// `path` is an addon `.toc` that actually contains directives.
if (result != 0)
AddOns::TocRewrite::Transform(path, outBuf, outSize);
return result;
}
DecideSource();
if (g_source == Source::Disk) {
// Disk version is at least as new — serve disk. If disk
// doesn't have this specific file (e.g. embedded has files
// disk doesn't), fall through and try embedded.
const int diskResult = FileRead_o(unused, path, outBuf, outSize,
extraBytes, flag1, flag2);
if (diskResult != 0) return diskResult;
}
// Source::Embedded path, OR Source::Disk-but-file-missing fallback.
// Look up the embedded version and synthesize a Storm buffer the
// caller can free normally.
const auto *entry = LookupEmbedded(suffix);
if (entry == nullptr) {
// Not in our embedded set either — let the engine try disk
// one more time (returns 0 if that also fails). Covers
// pathological cases like an empty disk install + embedded
// missing some file.
return FileRead_o(unused, path, outBuf, outSize, extraBytes,
flag1, flag2);
}
auto SMemAlloc = reinterpret_cast<SMemAlloc_t>(
Offsets::FUN_STORM_SMEM_ALLOC);
const size_t totalSize = entry->size + extraBytes;
void *buf = SMemAlloc(totalSize, __FILE__, __LINE__, 0);
if (buf == nullptr) return 0;
std::memcpy(buf, entry->data, entry->size);
if (extraBytes > 0) {
std::memset(static_cast<uint8_t *>(buf) + entry->size, 0, extraBytes);
}
if (outBuf != nullptr) *outBuf = buf;
if (outSize != nullptr) *outSize = entry->size;
return 1;
// An embedded addon's TOC takes the same per-line directives as an
// installed addon's, whichever source serves it.
const int result = ReadAddonFile(addon, relPath, unused, path, outBuf, outSize,
extraBytes, flag1, flag2);
if (result != 0)
AddOns::TocRewrite::Transform(path, outBuf, outSize);
return result;
}
// `FUN_ADDON_INIT` — `__fastcall(accountName)`. We post-hook it: let
// the engine's normal `Interface\AddOns\` scan run first, then call
// the TOC parser with `"!!!ClassicAPI"`. Dedup-safe — see file header.
using AddonInit_t = void(__fastcall *)(const char *accountName);
AddonInit_t AddonInit_o = nullptr;
// The exists-check counterpart of FileRead_h: the same source decision and
// the same fallbacks, so a path reports as existing exactly when FileRead_h
// would serve it. Other paths go to FlavorBindings (flavor-only addon
// Bindings.xml), then to the original.
int __stdcall FileExists_h(const char *path, int mode) {
const char *relPath = nullptr;
const int addon = MatchAddonPath(path, &relPath);
if (addon < 0) {
if (FileExists_o(path, mode) != 0)
return 1;
return AddOns::FlavorBindings::TryExists(path, mode, FileExists_o) ? 1 : 0;
}
DecideSource(addon);
if (g_source[addon] == Source::Disk && FileExists_o(path, mode) != 0)
return 1;
if (LookupEmbedded(relPath).data != nullptr)
return 1;
return FileExists_o(path, mode);
}
// `FUN_ADDON_SCAN_FULL` — `void __cdecl()`. We pre-hook it: register the
// embedded addons into the empty registry, then let the engine's scan
// run. Dedup-safe — see file header.
using AddonScan_t = void(__cdecl *)();
AddonScan_t AddonScan_o = nullptr;
using TocParser_t = void(__fastcall *)(const char *name);
using ListInsert_t = void(__thiscall *)(void *listCtrl, void *entry,
int position, int anchor);
// `FUN_TOC_PARSER` appends new entries to the *tail* of the addon
// registry's linked list, and the engine's addon-load pass at
// `FUN_0051F600` walks that list in *insertion order* (NOT
// alphabetical order — the alphabetical sort only applies to the
// flat array `GetAddOnInfo(i)` reads from). So our post-hook
// injection lands at the very end of the load order, after every
// disk-scanned addon. Addons that consume our globals from their
// main chunk (idTip's `FrameWatcher`, etc.) would see `nil` and
// hard-error during their boot.
// `entry + OFF_ADDON_ENTRY_FILTER_OUT` is the "filter-out" byte. The
// flat display-array builder `FUN_0051da70` walks the linked list and
// copies an entry into `GetNumAddOns`/`GetAddOnInfo`'s array ONLY when
// this byte is 0, so setting it hides an embedded addon from the
// character-select AddOns list — there's no checkbox, so it can't be
// toggled off. The builder only ever *writes* this byte on the
// secure/SMSG path (`entry+0x28 != 0`); our entry is non-secure, so a
// manual `1` here is stable across rebuilds. Hiding does NOT stop
// loading (the load pass `FUN_0051f600` never reads `+0x29`) and does
// NOT break dependency resolution or by-name queries (those use the
// addon hash table, which keeps the entry regardless — `LoadAddOn` of a
// hidden load-on-demand entry still works).
//
// Fix: walk the linked list, find our entry by name, and re-link
// it to the head via `FUN_INTRUSIVE_LIST_INSERT(position=1)`. The
// engine's own insert helper handles remove-then-insert atomically,
// so it's safe to call on an entry that's already in the list.
//
// Entries are pointed to by `[VAR_ADDON_LIST_HEAD]` (`0x00BE1B6C`),
// with the next-pointer field at `entry + 0x10` (computed as
// `*(value-at-VAR_ADDON_LIST_CTRL) + entry + 4` = `0xC + entry + 4`
// = `entry + 0x10`). Low-bit-1 means "sentinel" (end of list).
// Name pointer lives at `entry + 0x14`.
constexpr uintptr_t VAR_ADDON_LIST_HEAD = 0x00BE1B6C;
constexpr int OFF_ADDON_ENTRY_NAME_PTR = 0x14;
// DefaultState (`+0x2b`) needs no write: the entry constructor
// `FUN_00520550` stores 1 there, our tocs have no `## DefaultState:`, and
// the resolver co-hook below forces enabled anyway.
void MoveEmbeddedToListHead() {
uintptr_t entry = *reinterpret_cast<uintptr_t *>(VAR_ADDON_LIST_HEAD);
const int linkOffset = *reinterpret_cast<const int *>(
static_cast<uintptr_t>(Offsets::VAR_ADDON_LIST_CTRL));
while ((entry & 1) == 0 && entry != 0) {
// Post-registration finalize for the embedded entries: hide them from the
// addon list. Combined with the `FUN_ADDON_ENABLE_RESOLVE` co-hook, an
// embedded addon is always loadable and never appears as a toggleable
// entry.
void FinalizeEmbeddedEntries() {
Addons::ForEachEntry([](uintptr_t entry) {
const char *name = *reinterpret_cast<const char *const *>(
entry + OFF_ADDON_ENTRY_NAME_PTR);
if (name != nullptr && std::strcmp(name, kAddonName) == 0) {
auto fn = reinterpret_cast<ListInsert_t>(
Offsets::FUN_INTRUSIVE_LIST_INSERT);
fn(reinterpret_cast<void *>(
static_cast<uintptr_t>(Offsets::VAR_ADDON_LIST_CTRL)),
reinterpret_cast<void *>(entry),
/*position=*/ 1, /*anchor=*/ 0);
return;
}
entry = *reinterpret_cast<const uintptr_t *>(
entry + linkOffset + 4);
}
entry + Offsets::OFF_ADDON_ENTRY_NAME_PTR);
if (name != nullptr && IndexOfAddon(name) >= 0)
*reinterpret_cast<uint8_t *>(
entry + Offsets::OFF_ADDON_ENTRY_FILTER_OUT) = 1;
});
}
void __fastcall AddonInit_h(const char *accountName) {
AddonInit_o(accountName);
void __cdecl AddonScan_h() {
auto TocParser = reinterpret_cast<TocParser_t>(Offsets::FUN_TOC_PARSER);
TocParser(kAddonName);
MoveEmbeddedToListHead();
for (size_t i = 0; i < kAddonCount; ++i)
TocParser(kAddons[i]);
FinalizeEmbeddedEntries();
AddonScan_o();
}
// `FUN_ADDON_ENABLE_RESOLVE` — per-character enable resolver. We
// co-hook it to force-enable the embedded addons regardless of
// DefaultState or any stale WTF disable-override, so hiding them from
// the addon list can never leave one stuck off. Returns 2 ("enabled for
// all"); the load-pass gate only tests `!= 0`. Every other addon falls
// through to the original untouched. See the Offsets.h note for the ABI.
using AddonEnableResolve_t =
uint32_t(__fastcall *)(const char *name, const char *account, char resolveAll);
AddonEnableResolve_t AddonEnableResolve_o = nullptr;
uint32_t __fastcall AddonEnableResolve_h(const char *name, const char *account,
char resolveAll) {
if (name != nullptr && IndexOfAddon(name) >= 0)
return 2;
return AddonEnableResolve_o(name, account, resolveAll);
}
const Game::HookAutoRegister _hookFileRead{
@@ -369,11 +476,25 @@ const Game::HookAutoRegister _hookFileRead{
reinterpret_cast<void *>(&FileRead_h),
reinterpret_cast<void **>(&FileRead_o)};
const Game::HookAutoRegister _hookAddonInit{
Offsets::FUN_ADDON_INIT,
reinterpret_cast<void *>(&AddonInit_h),
reinterpret_cast<void **>(&AddonInit_o)};
const Game::HookAutoRegister _hookFileExists{
Offsets::FUN_FILE_EXISTS,
reinterpret_cast<void *>(&FileExists_h),
reinterpret_cast<void **>(&FileExists_o)};
const Game::HookAutoRegister _hookAddonScan{
Offsets::FUN_ADDON_SCAN_FULL,
reinterpret_cast<void *>(&AddonScan_h),
reinterpret_cast<void **>(&AddonScan_o)};
const Game::HookAutoRegister _hookEnableResolve{
Offsets::FUN_ADDON_ENABLE_RESOLVE,
reinterpret_cast<void *>(&AddonEnableResolve_h),
reinterpret_cast<void **>(&AddonEnableResolve_o)};
} // namespace
bool IsEmbedded(const char *name) {
return name != nullptr && IndexOfAddon(name) >= 0;
}
} // namespace Addons::Embedded
+23
View File
@@ -0,0 +1,23 @@
// 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 Addons::Embedded {
// True when `name` is one of the addons embedded in the DLL (compared
// ignoring case). Their registry entries are owned by `Addons::Embedded`:
// registered first, hidden from the addon list, force-enabled.
bool IsEmbedded(const char *name);
} // namespace Addons::Embedded
+41
View File
@@ -0,0 +1,41 @@
// 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
#include <cstddef>
// One home for the engine file-I/O and Storm-allocator function-pointer types
// the addon modules call. These are ABI-critical: FUN_FILE_READ /
// FUN_FILE_EXISTS / the Storm allocator are all `__stdcall` (callee cleans the
// stack), and declaring one `__cdecl` by mistake drifts ESP a few bytes per
// call and kills the process with no crash log. The shape lived in ~6 copies
// across the addon files; centralize it so the convention cannot drift.
namespace AddOns::EngineIO {
// FUN_FILE_READ (0x00648620) — __stdcall, callee cleans 28 bytes (RET 0x1C).
// arg0 is an optional archive handle (0 = merged VFS); outSize may be null.
using FileReadFn = int(__stdcall *)(int unused, const char *path, void **outBuf,
size_t *outSize, size_t extraBytes,
int flag1, int flag2);
// FUN_FILE_EXISTS (0x00648A30) — __stdcall, RET 8.
using FileExistsFn = int(__stdcall *)(const char *path, int mode);
// FUN_STORM_SMEM_ALLOC / FUN_STORM_SMEM_FREE — __stdcall, RET 0x10. Buffers
// FUN_FILE_READ hands out are freed with SMemFreeFn; a buffer we allocate with
// SMemAllocFn is freed cleanly by the engine's own SMemFree in turn.
using SMemAllocFn = void *(__stdcall *)(size_t size, const char *file, int line, int flags);
using SMemFreeFn = void(__stdcall *)(void *buf, const char *file, int line, int flags);
} // namespace AddOns::EngineIO
+112
View File
@@ -0,0 +1,112 @@
// 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 "addons/EngineIO.h"
#include "addons/FlavorBindings.h"
#include "addons/Toc.h"
#include "turtle/Detect.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
namespace AddOns::FlavorBindings {
namespace {
using AddOns::Toc::EqCI;
using AddOns::Toc::Lower;
constexpr size_t NPOS = static_cast<size_t>(-1);
// If `path` is an addon Bindings read (`…\AddOns\<Name>\Bindings.xml`, CI),
// return the length of the prefix up to the `Bindings.xml` filename (so a
// flavor filename can be appended in its place); else NPOS.
size_t AddonBindingsPrefix(const char *path) {
if (path == nullptr) return NPOS;
const size_t len = std::strlen(path);
const char *kFile = "bindings.xml"; // 12 chars, compared case-insensitively
const size_t flen = 12;
if (len < flen + 1) return NPOS;
for (size_t i = 0; i < flen; ++i)
if (Lower(path[len - flen + i]) != kFile[i]) return NPOS;
const size_t prefixLen = len - flen;
if (path[prefixLen - 1] != '\\' && path[prefixLen - 1] != '/')
return NPOS; // "Bindings.xml" must be a whole path segment
for (size_t i = 0; i + 8 <= len; ++i)
if (EqCI(path + i, 8, "\\AddOns\\")) return prefixLen;
return NPOS;
}
// Write `<prefix><flavorFile>` (e.g. `…\AddOns\Foo\Bindings_Turtle.xml`) into
// `out`. Returns false if it would not fit.
bool BuildFlavorPath(const char *path, size_t prefixLen, const char *flavorFile,
char *out, size_t outSize) {
const size_t flen = std::strlen(flavorFile);
if (prefixLen + flen + 1 > outSize) return false;
std::memcpy(out, path, prefixLen);
std::memcpy(out + prefixLen, flavorFile, flen + 1); // incl. NUL
return true;
}
// Fills `order` with the flavor filenames to probe, most specific first, and
// returns the count. `Bindings_Turtle.xml` only on a Turtle client.
int FlavorOrder(const char *(&order)[2]) {
int count = 0;
if (Turtle::Detected())
order[count++] = "Bindings_Turtle.xml";
order[count++] = "Bindings_ClassicAPI.xml";
return count;
}
} // namespace
bool TryExists(const char *path, int mode, FileExistsFn orig) {
const size_t prefixLen = AddonBindingsPrefix(path);
if (prefixLen == NPOS)
return false;
const char *order[2];
const int count = FlavorOrder(order);
char cand[512];
for (int i = 0; i < count; ++i) {
if (BuildFlavorPath(path, prefixLen, order[i], cand, sizeof cand) &&
orig(cand, mode) != 0)
return true;
}
return false;
}
bool TryHandle(int unused, const char *path, void **outBuf, size_t *outSize,
size_t extraBytes, int flag1, int flag2, FileReadFn orig) {
const size_t prefixLen = AddonBindingsPrefix(path);
if (prefixLen == NPOS)
return false;
const char *order[2];
const int count = FlavorOrder(order);
char cand[512];
for (int i = 0; i < count; ++i) {
if (!BuildFlavorPath(path, prefixLen, order[i], cand, sizeof cand))
continue;
// Serve the flavor file in place of Bindings.xml (a selected flavor
// wins over a plain Bindings.xml). No recursion: `orig` is the original
// reader passed by the FUN_FILE_READ hook.
if (orig(unused, cand, outBuf, outSize, extraBytes, flag1, flag2) != 0)
return true;
}
return false; // no flavor variant — caller reads the base Bindings.xml
}
} // namespace AddOns::FlavorBindings
+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/>.
#pragma once
#include <cstddef>
#include "addons/EngineIO.h"
namespace AddOns::FlavorBindings {
using EngineIO::FileExistsFn;
using EngineIO::FileReadFn;
// Flavor-specific addon Bindings selection — the Bindings.xml analog of
// AddOns::FlavorToc.
//
// A modern addon can ship a flavor-specific keybinding file
// (`Bindings_Turtle.xml` / `Bindings_ClassicAPI.xml`) instead of / alongside a
// plain `Bindings.xml`. The per-addon loader `FUN_0051f240` only ever builds
// `Interface\AddOns\<Name>\Bindings.xml`, gates it on an exists-check
// (`FUN_00648a30`), and — when that passes — loads it via `FUN_004b6f70`, which
// reads the file through `FUN_FILE_READ`. Two pieces make flavor files work:
//
// 1. This TryHandle, called from the FUN_FILE_READ hook: when `path` is an
// addon `…\AddOns\<Name>\Bindings.xml` read, serve a flavor variant in its
// place if one exists (a selected flavor wins over a plain `Bindings.xml`,
// matching FlavorToc). Probe order `Bindings_Turtle.xml` (only when
// Turtle::Detected) then `Bindings_ClassicAPI.xml`.
// 2. TryExists, called from the exists-check `FUN_FILE_EXISTS` hook: report
// `Bindings.xml` as existing when the base is absent but a flavor variant
// is present — otherwise the loader is never called for a flavor-only
// addon.
//
// Only `_Turtle` / `_ClassicAPI` are selected — never `_Vanilla` / `_Classic`
// (which target the 1.15 Classic Era build; its bindings reference handlers
// that build defines and this client does not load, so they would bind to
// missing functions). Both suffixes are ClassicAPI conventions, opt-in by the
// addon author, and mirror FlavorToc.
//
// Returns false when `path` is not an addon Bindings.xml read or no flavor
// variant exists — the caller then performs the normal base read.
bool TryHandle(int unused, const char *path, void **outBuf, size_t *outSize,
size_t extraBytes, int flag1, int flag2, FileReadFn orig);
// True when `path` is an addon `…\AddOns\<Name>\Bindings.xml` and a flavor
// variant exists through `orig` (the original exists-check). The caller asks
// `orig` about the base path itself; this answers only the flavor case.
bool TryExists(const char *path, int mode, FileExistsFn orig);
} // namespace AddOns::FlavorBindings
+108
View File
@@ -0,0 +1,108 @@
// 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 "addons/FlavorToc.h"
#include "turtle/Detect.h"
#include <cstring>
namespace AddOns::FlavorToc {
namespace {
// If `path` is `…\AddOns\<Name>\<Name>.toc` (case-insensitive), set `*prefixLen`
// to the byte length of the path up to and including the base `<Name>` filename
// (so a `_Vanilla.toc` suffix can be appended in place) and return true.
bool ParseBaseToc(const char *path, size_t *prefixLen) {
const size_t len = std::strlen(path);
if (len < 5 || _strnicmp(path + len - 4, ".toc", 4) != 0)
return false;
// Last separator -> "<Name>.toc" file part.
size_t lastSep = static_cast<size_t>(-1);
for (size_t i = len; i-- > 0;)
if (path[i] == '\\' || path[i] == '/') { lastSep = i; break; }
if (lastSep == static_cast<size_t>(-1))
return false;
const char *file = path + lastSep + 1; // "<Name>.toc"
const size_t nameLen = (len - (lastSep + 1)) - 4; // strip ".toc"
if (nameLen == 0)
return false;
// Previous separator -> "<Name>" folder segment; it must equal the base name.
size_t prevSep = static_cast<size_t>(-1);
for (size_t i = lastSep; i-- > 0;)
if (path[i] == '\\' || path[i] == '/') { prevSep = i; break; }
if (prevSep == static_cast<size_t>(-1))
return false;
const char *folder = path + prevSep + 1;
const size_t folderLen = lastSep - (prevSep + 1);
if (folderLen != nameLen || _strnicmp(folder, file, nameLen) != 0)
return false;
// Grandparent segment must be "AddOns" (so FrameXML/other .toc reads pass through).
size_t prev2Sep = static_cast<size_t>(-1);
for (size_t i = prevSep; i-- > 0;)
if (path[i] == '\\' || path[i] == '/') { prev2Sep = i; break; }
if (prev2Sep == static_cast<size_t>(-1))
return false;
const char *gp = path + prev2Sep + 1;
const size_t gpLen = prevSep - (prev2Sep + 1);
if (gpLen != 6 || _strnicmp(gp, "AddOns", 6) != 0)
return false;
*prefixLen = lastSep + 1 + nameLen; // "…\AddOns\<Name>\<Name>"
return true;
}
} // namespace
bool TryHandle(int unused, const char *path, void **outBuf, size_t *outSize,
size_t extraBytes, int flag1, int flag2, FileReadFn orig) {
if (path == nullptr)
return false;
size_t prefixLen = 0;
if (!ParseBaseToc(path, &prefixLen))
return false;
char cand[512];
if (prefixLen + 16 >= sizeof cand) // "_ClassicAPI.toc" + NUL is 16 (longest)
return false; // pathological path length — let base read run
std::memcpy(cand, path, prefixLen);
// Only flavors that describe THIS environment, most specific first:
// `_Turtle` — Turtle client/content, only when Turtle is detected;
// `_ClassicAPI` — 1.12 + ClassicAPI, ALWAYS (ClassicAPI is present by
// definition — it is the code doing this redirect).
// Deliberately NOT `_Vanilla`/`_Classic` (those target the 1.15 Classic Era
// client — a modern engine + full modern API — which this 1.12 +
// partial-backport client is not), nor `_Mainline`/`_Cata`/etc.
const char *order[2];
int count = 0;
if (Turtle::Detected())
order[count++] = "_Turtle.toc";
order[count++] = "_ClassicAPI.toc";
for (int i = 0; i < count; ++i) {
std::memcpy(cand + prefixLen, order[i], std::strlen(order[i]) + 1); // incl. NUL
if (orig(unused, cand, outBuf, outSize, extraBytes, flag1, flag2) != 0)
return true; // served the flavor TOC in place of the base
}
// No matching flavor TOC — fall through: the caller reads the base path,
// which chains through any other FUN_FILE_READ hooker before the engine.
return false;
}
} // namespace AddOns::FlavorToc
+60
View File
@@ -0,0 +1,60 @@
// 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
#include <cstddef>
#include "addons/EngineIO.h"
namespace AddOns::FlavorToc {
using EngineIO::FileReadFn;
// Modern-client multi-flavor TOC selection, backported.
//
// A modern addon that targets several game flavors from one folder ships
// `<Name>_Vanilla.toc` / `_Mainline.toc` / `_Cata.toc` / … and often NO plain
// `<Name>.toc`. Vanilla 1.12 only ever opens `<Name>\<Name>.toc`, so such an
// addon never registers — it is invisible, not merely mis-loaded.
//
// Called from the FUN_FILE_READ hook. If `path` is an addon base-TOC read
// (`…\AddOns\<Name>\<Name>.toc`), probe the flavor TOCs that describe THIS
// environment and, if one exists, serve it via `orig` (as if it were the base
// TOC) and return true. Order, most specific first:
// `<Name>_Turtle.toc` — Turtle client/content, ONLY when Turtle is
// detected (Turtle::Detected); a ClassicAPI extension;
// `<Name>_ClassicAPI.toc` — 1.12 + ClassicAPI, ALWAYS (ClassicAPI is present
// by definition — it is the code doing this redirect).
// Both are ClassicAPI conventions, not retail flavors. We deliberately do NOT
// map to `_Vanilla`/`_Classic` (those target the 1.15 Classic Era client — a
// modern engine + full modern API — which a 1.12 + partial-backport client is
// not), nor `_Mainline`/`_Cata`/etc. A selected flavor wins over an existing
// base `<Name>.toc`. If neither flavor exists, TryHandle returns false and the
// caller does the normal base read — which chains through any other DLL that
// hooked FUN_FILE_READ before reaching the engine.
//
// The redirect fires at BOTH the registration scan (glue/char-select) and the
// in-world load pass, which must agree on the flavor. `Turtle::Detected()` is
// therefore consistent across both: it reads the in-world `TURTLE_WOW_VERSION`
// global AND Turtle's glue-time `TURTLE_*` GlueXML globals, so it returns true
// at the glue scan too (see turtle/Detect.h).
//
// Returns false when `path` is not a base-TOC read, or no vanilla flavor TOC
// exists — the caller then performs the normal base read. Because the redirect
// is at the read layer, the addon scan (FUN_0051C9B0), the load pass
// (FUN_006edb90) and GetAddOnMetadata all see the same selected TOC.
bool TryHandle(int unused, const char *path, void **outBuf, size_t *outSize,
size_t extraBytes, int flag1, int flag2, FileReadFn orig);
} // namespace AddOns::FlavorToc
+73 -56
View File
@@ -26,6 +26,8 @@
#include "Game.h"
#include "Offsets.h"
#include "addons/LoadState.h"
#include "addons/Registry.h"
#include <cstdint>
@@ -34,6 +36,7 @@ namespace AddOns::Info {
namespace {
using GetByIndex_t = void *(__fastcall *)(int idx0Based);
using GetAddOnCount_t = int(__fastcall *)();
using FieldByName_t = const char *(__fastcall *)(const char *name);
using EntryByteFn_t = uint8_t(__fastcall *)(const uint8_t *entry);
using GetSecurityIndex_t = uint32_t(__fastcall *)(const uint8_t *entry);
@@ -42,9 +45,8 @@ using CanLoadFn_t = uint8_t(__fastcall *)(const uint8_t *entry, char fullCheck,
const char *accountName);
using GetAccountName_t = const char *(*)();
// Hash-lookup by name → the matched record's RequiredDeps descriptor
// (`record + 0x48`), NULL on miss. Accepts an entry pointer too (its
// first bytes are the inline name). We use it only to recover the
// record base for string input; see `Script_GetAddOnOptionalDependencies`.
// (`record + 0x48`), NULL on miss. We use it only to recover the
// record base; see `Script_GetAddOnOptionalDependencies`.
using ResolveReqDeps_t = uint8_t *(__fastcall *)(const char *nameOrEntry);
// Resolves the user's arg to a `const uint8_t *` that the engine's
@@ -52,8 +54,7 @@ using ResolveReqDeps_t = uint8_t *(__fastcall *)(const char *nameOrEntry);
// a NUL-terminated string starting at the input pointer and case-
// insensitively match it against the registry, so either of these
// shapes works:
// - an AddOnEntry pointer from `GetByIndex` (the entry's first
// 12 bytes ARE the inline name buffer)
// - the name pointer `GetByIndex` returns (`[entry+0x14]`)
// - a raw `const char *` to a Lua string
//
// Mirrors `Script_GetAddOnInfo`'s own input handling exactly — it
@@ -251,19 +252,22 @@ int __fastcall Script_GetAddOnSecurity(void *L) {
// `C_AddOns.IsAddOnLoaded(indexOrName)` → `(loadedOrLoading, loaded)`.
//
// Modern WoW distinguishes "load-in-progress" from "fully loaded" —
// matters for LoD addons whose load is split across multiple
// `LoadAddOn` callbacks. Vanilla 1.12's `FUN_0051F240` is fully
// synchronous: the loaded byte at `entry+0x18` flips from 0 → 1
// inside a single call, so the "loading" state is never observable
// from Lua. We return the same boolean twice — `loadedOrLoading`
// and `loaded` are identical here.
// Modern WoW distinguishes "load-in-progress" from "fully loaded", and
// the two really are distinguishable here: the engine's loaded byte
// (`entry+0x18`) is set at the START of a load, before the addon's files
// run, so the byte alone answers `loadedOrLoading`, not `loaded`. The
// window is reachable from Lua — an addon's own file-scope code, and any
// dependency pulled in during it, run while the byte already reads set.
//
// So `loadedOrLoading` is the engine's byte, and `loaded` additionally
// requires the addon not to be mid-load, which `AddOns::LoadState`
// tracks from the loader itself.
//
// Resolves both numeric indices (via `FUN_ADDON_GET_BY_INDEX`) and
// string names. `IS_LOADED` accepts an entry pointer as its name arg
// because the entry's first 12 bytes are the inline NUL-terminated
// directory name (same as the other per-field accessors), so we can
// feed it either an entry or a Lua-side string transparently.
// string names. `FUN_ADDON_GET_BY_INDEX` returns the entry's name
// pointer, so `IS_LOADED` (like the other per-field accessors) takes
// either that or a Lua-side string transparently — and that same
// pointer is the name `LoadState` matches on.
int __fastcall Script_IsAddOnLoaded(void *L) {
const uint8_t *entry = ResolveAddOnName(L);
if (entry == nullptr) {
@@ -273,8 +277,11 @@ int __fastcall Script_IsAddOnLoaded(void *L) {
}
auto isLoaded = reinterpret_cast<EntryByteFn_t>(
Offsets::FUN_ADDON_IS_LOADED);
const bool loaded = isLoaded(entry) != 0;
Game::Lua::PushBool(L, loaded);
const bool loadedOrLoading = isLoaded(entry) != 0;
const bool loaded =
loadedOrLoading &&
!AddOns::LoadState::IsLoading(reinterpret_cast<const char *>(entry));
Game::Lua::PushBool(L, loadedOrLoading);
Game::Lua::PushBool(L, loaded);
return 2;
}
@@ -303,46 +310,20 @@ int __fastcall Script_DoesAddOnExist(void *L) {
// `C_AddOns.GetAddOnOptionalDependencies(indexOrName)` — the addon's
// `## OptionalDeps:` names as multiple return values, in declared order.
// The exact shape of the stock `GetAddOnDependencies`, but reading the
// *optional* dep array instead of the required one. No optional deps →
// returns nothing.
// *optional* dep array instead of the required one. No optional deps or
// an unknown name → returns nothing.
//
// Vanilla parses `## OptionalDeps:` in the TOC parser `FUN_0051c9b0`
// into a `{cap, count, data, quantum}` name-array descriptor at
// `record+0x38` (count@+0x3C, data@+0x40), but ships no getter for it.
//
// Arg/error handling mirrors stock `Script_GetAddOnDependencies`
// (`0x0048E5E0`): numeric out-of-range or a non-string/non-number arg
// raises the usage error; an unknown *name* string returns nothing
// (no error), matching the engine's own not-found path.
//
// Resolution mirrors stock `Script_GetAddOnDependencies` exactly: the
// arg is first turned into a name-usable pointer (`ResolveAddOnName` —
// numeric via `FUN_ADDON_GET_BY_INDEX`, string is the raw string), then
// routed through the by-name hash lookup `FUN_ADDON_RESOLVE_REQ_DEPS`
// to reach the deps-bearing record. `FUN_ADDON_GET_BY_INDEX` returns a
// *name pointer*, NOT the record — reading dep offsets off it lands in
// string memory and crashes (a numeric-path caller like pfUI's addon
// list hit exactly that). The resolver returns the RequiredDeps
// descriptor at `record+0x48`; subtract to recover the base. An unknown
// name yields NULL → return nothing (no error), like stock.
// Like stock, `lua_checkstack(count)` before the pushes — a C function
// is only guaranteed LUA_MINSTACK (20) free slots.
int __fastcall Script_GetAddOnOptionalDependencies(void *L) {
static constexpr const char *kUsage =
"Usage: C_AddOns.GetAddOnOptionalDependencies(index or \"name\")";
// NULL ⇒ out-of-range numeric index or a non-string/non-number arg;
// stock raises the usage error in both cases.
const uint8_t *nameOrEntry = ResolveAddOnName(L);
if (nameOrEntry == nullptr) {
Game::Lua::Error(L, "%s", kUsage);
const uint8_t *record = Addons::ResolveRecord(
L, "Usage: C_AddOns.GetAddOnOptionalDependencies(index or \"name\")");
if (record == nullptr)
return 0;
}
auto resolve = reinterpret_cast<ResolveReqDeps_t>(
Offsets::FUN_ADDON_RESOLVE_REQ_DEPS);
uint8_t *reqDesc = resolve(reinterpret_cast<const char *>(nameOrEntry));
if (reqDesc == nullptr)
return 0; // unknown addon name — no error, push nothing
const uint8_t *record = reqDesc - Offsets::OFF_ADDON_REQDEPS_DESC;
const uint32_t count = *reinterpret_cast<const uint32_t *>(
record + Offsets::OFF_ADDON_OPTIONALDEPS_COUNT);
@@ -352,11 +333,30 @@ int __fastcall Script_GetAddOnOptionalDependencies(void *L) {
record + Offsets::OFF_ADDON_OPTIONALDEPS_ARRAY);
if (names == nullptr)
return 0;
Game::Lua::CheckStack(L, static_cast<int>(count));
for (uint32_t i = 0; i < count; ++i)
Game::Lua::PushString(L, names[i]); // NULL → pushnil, per engine
return static_cast<int>(count);
}
// `C_AddOns.GetAddOnInterfaceVersion(indexOrName)` — the `## Interface:`
// number the engine parsed into `record+0x1C`, the same value its
// loadability check compares against the client version. A comma-list
// is already reduced to retail's pick (closest value at or below the
// client version) by `AddOns::TocRewrite` before the parser sees it.
// nil for an unknown name.
int __fastcall Script_GetAddOnInterfaceVersion(void *L) {
const uint8_t *record = Addons::ResolveRecord(
L, "Usage: C_AddOns.GetAddOnInterfaceVersion(index or \"name\")");
if (record == nullptr) {
Game::Lua::PushNil(L);
return 1;
}
Game::Lua::PushNumber(L, static_cast<double>(*reinterpret_cast<const uint32_t *>(
record + Offsets::OFF_ADDON_INTERFACE_VERSION)));
return 1;
}
// `Enum.AddOnSecurityStatus` — what `C_AddOns.GetAddOnSecurity`
// returns. Slots 0..2 match the engine's own ordering at
// `VAR_ADDON_SECURITY_TABLE`; slot 3 is our addition for
@@ -368,6 +368,18 @@ constexpr Game::Lua::EnumIntegerEntry kAddOnSecurityStatusEntries[] = {
{"NotAvailable", 3},
};
const Game::Doc::Field kInterfaceVersionArgs[] = {
Game::Doc::Req("name", "uiAddon", "An addon index or folder name."),
};
const Game::Doc::Field kInterfaceVersionRets[] = {
Game::Doc::Opt("interfaceVersion", "number", nullptr,
"The ## Interface: value from the TOC, or nil for an unknown name."),
};
const Game::Doc::Function kGetAddOnInterfaceVersion{
"Returns the Interface directive of an addon TOC. For a comma-separated list, "
"returns the closest value at or below the client interface version.",
kInterfaceVersionArgs, kInterfaceVersionRets};
} // namespace
static void RegisterLuaFunctions() {
@@ -385,13 +397,18 @@ static void RegisterLuaFunctions() {
&Script_DoesAddOnExist);
Game::Lua::RegisterTableFunction("C_AddOns", "IsAddOnLoaded",
&Script_IsAddOnLoaded);
// The stock global, mirrored into the namespace — the engine's own
// handler already has the Lua C ABI and the modern return shape.
Game::Lua::RegisterTableFunction(
"C_AddOns", "LoadAddOn",
reinterpret_cast<Game::Lua::CFunction>(
static_cast<uintptr_t>(Offsets::FUN_SCRIPT_LOAD_ADDON)));
Game::Lua::RegisterTableFunction("C_AddOns", "GetAddOnOptionalDependencies",
&Script_GetAddOnOptionalDependencies);
Game::Lua::RegisterIntegerEnum(
"Enum", "AddOnSecurityStatus",
kAddOnSecurityStatusEntries,
sizeof(kAddOnSecurityStatusEntries) /
sizeof(kAddOnSecurityStatusEntries[0]));
Game::Lua::RegisterTableFunction("C_AddOns", "GetAddOnInterfaceVersion",
&Script_GetAddOnInterfaceVersion,
&kGetAddOnInterfaceVersion);
Game::Lua::RegisterIntegerEnum("Enum", "AddOnSecurityStatus", kAddOnSecurityStatusEntries);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
+90
View File
@@ -0,0 +1,90 @@
// 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/>.
// Tracks in-progress addon loads so `C_AddOns.IsAddOnLoaded` can report
// `loadedOrLoading` and `loaded` separately. See `LoadState.h` for why the
// engine's own byte can't answer both.
//
// Loads nest — an addon's dependencies load inside its own call — so this
// keeps a stack rather than a single name. The name is copied rather than
// stored by pointer: `LoadAddOn` passes a Lua string, which does not
// outlive the call.
#include "addons/LoadState.h"
#include "Common.h"
#include "Game.h"
#include "Offsets.h"
namespace AddOns::LoadState {
namespace {
// Dependency chains are shallow; anything deeper simply isn't tracked
// (the depth counter still balances, so the stack can't desync).
constexpr int kMaxDepth = 16;
constexpr int kMaxName = 64;
char g_stack[kMaxDepth][kMaxName];
int g_depth = 0;
bool EqualsIgnoreCase(const char *a, const char *b) {
for (; *a != '\0' && *b != '\0'; ++a, ++b) {
char ca = *a;
char cb = *b;
if (ca >= 'A' && ca <= 'Z')
ca = static_cast<char>(ca - 'A' + 'a');
if (cb >= 'A' && cb <= 'Z')
cb = static_cast<char>(cb - 'A' + 'a');
if (ca != cb)
return false;
}
return *a == *b;
}
using LoadOne_t = unsigned int(__fastcall *)(const char *name, char flag,
void *progressCtx);
LoadOne_t s_loadOne_o = nullptr;
unsigned int __fastcall LoadOne_h(const char *name, char flag, void *progressCtx) {
const int slot = g_depth;
if (slot >= 0 && slot < kMaxDepth)
Common::BoundedCopy(g_stack[slot], name, kMaxName);
++g_depth;
const unsigned int result = s_loadOne_o(name, flag, progressCtx);
--g_depth;
if (g_depth < 0)
g_depth = 0; // defensive: never let the stack run negative
return result;
}
const Game::HookAutoRegister _hookLoadOne{
Offsets::FUN_ADDON_LOAD_ONE,
reinterpret_cast<void *>(&LoadOne_h),
reinterpret_cast<void **>(&s_loadOne_o)};
} // namespace
bool IsLoading(const char *name) {
if (name == nullptr || *name == '\0')
return false;
const int depth = (g_depth < kMaxDepth) ? g_depth : kMaxDepth;
for (int i = 0; i < depth; ++i)
if (EqualsIgnoreCase(g_stack[i], name))
return true;
return false;
}
} // namespace AddOns::LoadState
+33
View File
@@ -0,0 +1,33 @@
// This file is part of ClassicAPI.
//
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
#pragma once
// `AddOns::LoadState` — tracks which addons are mid-load.
//
// The engine's own "loaded" byte (`entry+0x18`) is set at the START of a
// load, before the addon's files run, so on its own it can't tell
// "loading" from "loaded". That distinction is observable: an addon's
// file-scope code, and every dependency pulled in during it, execute
// while the byte already reads set.
//
// A co-hook on the per-addon loader keeps a stack of the names currently
// being loaded, which is the missing half of
// `C_AddOns.IsAddOnLoaded`'s `(loadedOrLoading, loaded)` pair.
namespace AddOns::LoadState {
// True while `name` is inside the engine's per-addon load call. Matching
// is case-insensitive, as addon-name matching is everywhere else.
bool IsLoading(const char *name);
} // namespace AddOns::LoadState
+132
View File
@@ -0,0 +1,132 @@
// 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/>.
// `C_AddOns.GetAddOnLocalTable(name)` — the public, gated view of an addon's
// private namespace table (the `local _, addonTable = ...` second vararg each
// addon file is called with; see luasyntax/AddonNamespace.h).
//
// Retail added this in 11.0 alongside the `## AllowAddOnTableAccess` TOC
// directive: one addon can read another's local table ONLY when the target
// opts in. We mirror that gate:
// 1. the named addon is currently LOADED, and
// 2. its `.toc` declares `## AllowAddOnTableAccess: 1`.
// Either check failing returns nil. An addon receiving its OWN table is a
// different, ungated path (its files are called with it at load) — an addon
// never needs permission for its own namespace.
//
// Directive spelling verified against the 1.15.8 Classic Era binary (both the
// `AllowAddOnTableAccess:` TOC key and the `GetAddOnLocalTable` name are
// present there). The vanilla 1.12 TOC parser drops unknown `##` directives,
// so we scan the `.toc` ourselves via `FUN_FILE_READ`.
#include "Game.h"
#include "Offsets.h"
#include "addons/EngineIO.h"
#include "addons/Toc.h"
#include "luasyntax/AddonNamespace.h"
#include <cstddef>
#include <cstdint>
#include <cstdio>
namespace AddOns::LocalTable {
namespace {
// IS_LOADED is a by-name hash lookup returning the loaded byte (`entry+0x18`);
// passing the name string works because the lookup hashes it. See Offsets.h.
using IsLoadedFn_t = uint8_t(__fastcall *)(const char *name);
// FUN_FILE_READ / the Storm free (see addons/EngineIO.h). Calling the raw
// FUN_FILE_READ address routes through Embedded's file-read hook, which forwards
// every non-`!!!ClassicAPI` path to the original untouched — what we want here.
using AddOns::EngineIO::FileReadFn;
using AddOns::EngineIO::SMemFreeFn;
// True iff the addon's `.toc` has a line `## AllowAddOnTableAccess: <nonzero>`.
// The value is read as a TOC boolean flag: parse the leading integer, true iff
// non-zero (so `1` opts in, `0`/absent do not) — matching WoW's numeric TOC
// flag semantics. Not cached: GetAddOnLocalTable is not a hot path.
bool TocAllowsTableAccess(const char *name) {
// A registered, loaded addon name never carries a path separator; reject
// any that does so the read stays bounded to the addon's own folder.
for (const char *p = name; *p; ++p)
if (*p == '\\' || *p == '/')
return false;
char path[300];
std::snprintf(path, sizeof path, "Interface\\AddOns\\%s\\%s.toc", name, name);
void *buf = nullptr;
size_t size = 0;
auto fileRead = reinterpret_cast<FileReadFn>(Offsets::FUN_FILE_READ);
if (fileRead(0, path, &buf, &size, 1, 1, 0) == 0 || buf == nullptr)
return false;
const char *v = nullptr;
size_t n = 0;
bool allowed = false;
if (AddOns::Toc::FindValue(static_cast<const char *>(buf), size,
"AllowAddOnTableAccess", &v, &n)) {
int value = 0;
bool anyDigit = false;
for (size_t k = 0; k < n && v[k] >= '0' && v[k] <= '9'; ++k) {
value = value * 10 + (v[k] - '0');
anyDigit = true;
}
allowed = anyDigit && value != 0;
}
auto smemFree = reinterpret_cast<SMemFreeFn>(Offsets::FUN_STORM_SMEM_FREE);
smemFree(buf, __FILE__, __LINE__, 0);
return allowed;
}
// `C_AddOns.GetAddOnLocalTable(name)` -> table, or nil.
//
// Name (string) input only — the local table is a by-name concept (one addon
// asking for another by name), and the namespace map is name-keyed. Numeric
// index is not accepted (returns nil); no addon references another's table by
// load order.
int __fastcall Script_GetAddOnLocalTable(void *L) {
const char *name = Game::Lua::ToString(L, 1);
if (name == nullptr || *name == '\0') {
Game::Lua::PushNil(L);
return 1;
}
auto isLoaded = reinterpret_cast<IsLoadedFn_t>(Offsets::FUN_ADDON_IS_LOADED);
if (isLoaded(name) == 0) { // not loaded (covers "does not exist")
Game::Lua::PushNil(L);
return 1;
}
if (!TocAllowsTableAccess(name)) { // opted out / no directive
Game::Lua::PushNil(L);
return 1;
}
LuaSyntax::PushAddonNamespace(L, name);
return 1;
}
void RegisterLuaFunctions() {
Game::Lua::RegisterTableFunction("C_AddOns", "GetAddOnLocalTable",
&Script_GetAddOnLocalTable);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace
} // namespace AddOns::LocalTable
+184
View File
@@ -0,0 +1,184 @@
// 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/>.
// `UpdateAddOnMemoryUsage()` / `GetAddOnMemoryUsage(index or "name")` —
// 3.3.5's `Script_UpdateAddOnMemoryUsage` (0x00511510) and
// `Script_GetAddOnMemoryUsage` (0x00511530) over `Gc::Tag`.
//
// An addon's tag is its registry name pointer `[entry+0x14]`: the exact
// pointer `FUN_ADDON_LOAD_ONE` installs as the context word while the
// addon's files run (and the one 3.3.5's `GetAddOnName` returns), so the
// lookup is a pointer match like 3.3.5's `luaC_getsize`. Secure addons run
// under context 0, are never tagged, and read 0 — as in 3.3.5.
//
// 3.3.5's `LoadAddOn` also pins `lua_gctag` to the addon for its whole
// file / Bindings / SavedVariables window, so objects made there stay the
// addon's even when its code switches the context word (calling into another
// addon's function or table makes that addon's word current). The 1.12 loader
// has the same window; two 5-byte call patches open and close a `Gc::Tag` pin
// at its edges (SITE_ADDON_LOAD_WINDOW_OPEN / _CLOSE).
#include "Common.h"
#include "Game.h"
#include "Offsets.h"
#include "addons/Registry.h"
#include "gc/Tag.h"
#include <cstdint>
#include <cstdio>
namespace AddOns::MemoryUsage {
namespace {
constexpr uintptr_t addrExecContextDepth = Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH;
// The loader's own context value: the name for an insecure addon, 0 for a
// secure one (3.3.5's `addon->m_status ? addonName : nullptr`). A 0 pin means
// "no override", so a secure addon's window keeps following the context word.
void __fastcall OpenLoadWindow(const uint8_t *entry) {
const bool insecure = Game::Read<uint32_t>(entry, Offsets::OFF_ADDON_ENTRY_STATUS) != 0;
Gc::Tag::PushPin(insecure ? Game::Read<const char *>(entry, Offsets::OFF_ADDON_ENTRY_NAME_PTR)
: nullptr);
}
void CloseLoadWindow() { Gc::Tag::PopPin(); }
// Stands in for `xor eax,eax; lea ecx,[ebp-0x18]` at the window's open.
// EBX = the entry; EBP is the loader's frame.
__declspec(naked) void LoadWindowOpenThunk() {
__asm {
pushad
mov ecx, ebx
call OpenLoadWindow
popad
xor eax, eax
lea ecx, [ebp - 18h]
ret
}
}
// Stands in for `mov eax,[VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH]` at the close.
__declspec(naked) void LoadWindowCloseThunk() {
__asm {
pushad
call CloseLoadWindow
popad
mov eax, addrExecContextDepth
mov eax, [eax]
ret
}
}
void PatchLoadWindow() {
static const uint8_t kOpen[5] = {0x33, 0xC0, 0x8D, 0x4D, 0xE8};
static const uint8_t kClose[5] = {0xA1, 0xC4, 0xEA, 0xCE, 0x00};
Common::ReplaceWithCall(Offsets::SITE_ADDON_LOAD_WINDOW_OPEN, kOpen, sizeof kOpen,
reinterpret_cast<const void *>(&LoadWindowOpenThunk));
Common::ReplaceWithCall(Offsets::SITE_ADDON_LOAD_WINDOW_CLOSE, kClose, sizeof kClose,
reinterpret_cast<const void *>(&LoadWindowCloseThunk));
}
int __fastcall Script_UpdateAddOnMemoryUsage(void *L) {
Gc::Tag::UpdateUsage(L);
return 0;
}
int __fastcall Script_GetAddOnMemoryUsage(void *L) {
const uint8_t *record =
Addons::ResolveRecord(L, "Usage: GetAddOnMemoryUsage(index or \"name\")");
const char *tag =
record != nullptr
? Game::Read<const char *>(record, Offsets::OFF_ADDON_ENTRY_NAME_PTR)
: nullptr;
const uint64_t bytes = tag != nullptr ? Gc::Tag::Usage(tag) : 0;
Game::Lua::PushNumber(L, static_cast<double>(bytes) * (1.0 / 1024.0));
return 1;
}
// `_classicapi_LuaHeapAudit()` → objectBytes, nblocks, taggedObjects.
// Sums `Gc::Tag::SizeOf` over every collectable object the engine can
// reach. `objectBytes` should sit just under `nblocks` (the engine's own
// byte count): the gap is what is not a GC object (string-table buckets,
// the main thread and its stack, buffers). A gap that grows with the heap
// means a size formula is wrong.
int __fastcall Script_LuaHeapAudit(void *L) {
uint64_t bytes = 0;
Gc::Tag::ForEachObject(L, [&bytes](const void *object) { bytes += Gc::Tag::SizeOf(object); });
const uint8_t *g = Game::Read<const uint8_t *>(L, Offsets::OFF_LUA_STATE_G);
Game::Lua::PushNumber(L, static_cast<double>(bytes));
Game::Lua::PushNumber(L, static_cast<double>(Game::Read<uint32_t>(g, Offsets::OFF_LUA_G_NBLOCKS)));
Game::Lua::PushNumber(L, static_cast<double>(Gc::Tag::TaggedCount()));
return 3;
}
// `_classicapi_GcTagOf(value)` → the owner tag of a table / function /
// userdata / thread: the addon's name when the tag is an addon's, else the
// raw context word as "0x…" (e.g. RunScript's), nil when untagged.
int __fastcall Script_GcTagOf(void *L) {
const char *tag = Gc::Tag::Of(Game::Lua::ToPointer(L, 1));
if (tag == nullptr) {
Game::Lua::PushNil(L);
return 1;
}
const char *name = nullptr;
Addons::ForEachEntry([&](uintptr_t entry) {
if (Game::Read<const char *>(entry + Offsets::OFF_ADDON_ENTRY_NAME_PTR) != tag)
return true;
name = tag;
return false;
});
if (name != nullptr) {
Game::Lua::PushString(L, name);
} else {
char buf[16];
std::snprintf(buf, sizeof buf, "0x%08X", static_cast<unsigned>(reinterpret_cast<uintptr_t>(tag)));
Game::Lua::PushString(L, buf);
}
return 1;
}
const Game::Doc::Function kUpdateAddOnMemoryUsage{
"Recounts the memory each addon uses; GetAddOnMemoryUsage returns the result of the "
"last recount.",
{}, {}, "AddOnsGlobals"};
const Game::Doc::Field kGetArgs[] = {
Game::Doc::Req("name", "uiAddon", "An addon index or folder name."),
};
const Game::Doc::Field kGetRets[] = {
Game::Doc::Req("memory", "number",
"Kilobytes of Lua memory the addon's code allocated, as of the last "
"UpdateAddOnMemoryUsage."),
};
const Game::Doc::Function kGetAddOnMemoryUsage{
"Returns the Lua memory an addon uses, in kilobytes, as of the last "
"UpdateAddOnMemoryUsage.",
kGetArgs, kGetRets, "AddOnsGlobals"};
} // namespace
static void RegisterLuaFunctions() {
// Each pass runs before the load pass; the patch is idempotent.
PatchLoadWindow();
Game::Lua::RegisterGlobalFunction("UpdateAddOnMemoryUsage", &Script_UpdateAddOnMemoryUsage,
&kUpdateAddOnMemoryUsage);
Game::Lua::RegisterGlobalFunction("GetAddOnMemoryUsage", &Script_GetAddOnMemoryUsage,
&kGetAddOnMemoryUsage);
Game::Lua::RegisterGlobalFunction("_classicapi_LuaHeapAudit", &Script_LuaHeapAudit);
Game::Lua::RegisterGlobalFunction("_classicapi_GcTagOf", &Script_GcTagOf);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace AddOns::MemoryUsage
+63
View File
@@ -0,0 +1,63 @@
// 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 "addons/Registry.h"
#include "Game.h"
namespace Addons {
namespace {
using GetByIndex_t = void *(__fastcall *)(int idx0Based);
using GetAddOnCount_t = int(__fastcall *)();
using ResolveReqDeps_t = uint8_t *(__fastcall *)(const char *name);
} // namespace
// Either input is routed through the by-name hash lookup
// `FUN_ADDON_RESOLVE_REQ_DEPS` to reach the record.
// `FUN_ADDON_GET_BY_INDEX` returns a *name pointer*, NOT the record —
// reading record offsets off it lands in string memory and crashes (a
// numeric-path caller like pfUI's addon list hit exactly that). The
// resolver returns the RequiredDeps descriptor at `record+0x48`;
// subtract to recover the base.
const uint8_t *ResolveRecord(void *L, const char *usage) {
const char *name;
if (Game::Lua::IsNumber(L, 1)) {
const int idx = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
auto byIndex = reinterpret_cast<GetByIndex_t>(Offsets::FUN_ADDON_GET_BY_INDEX);
name = static_cast<const char *>(byIndex(idx));
if (name == nullptr) {
auto count = reinterpret_cast<GetAddOnCount_t>(Offsets::FUN_ADDON_GET_COUNT);
Game::Lua::Error(L, reinterpret_cast<const char *>(static_cast<uintptr_t>(
Offsets::VAR_ADDON_INDEX_RANGE_ERROR_FMT)),
count());
return nullptr;
}
} else if (Game::Lua::IsString(L, 1)) {
name = Game::Lua::ToString(L, 1);
} else {
Game::Lua::Error(L, usage);
return nullptr;
}
auto resolve = reinterpret_cast<ResolveReqDeps_t>(
Offsets::FUN_ADDON_RESOLVE_REQ_DEPS);
uint8_t *reqDesc = resolve(name);
if (reqDesc == nullptr)
return nullptr;
return reqDesc - Offsets::OFF_ADDON_REQDEPS_DESC;
}
} // namespace Addons
+59
View File
@@ -0,0 +1,59 @@
// 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
#include "Offsets.h"
#include <cstdint>
#include <type_traits>
namespace Addons {
// Walk the engine's intrusive AddOn-registry linked list, calling `fn(entry)`
// for each `AddOnEntry *`. Head at `[VAR_ADDON_LIST_HEAD]`; the next-pointer
// field is at `entry + [VAR_ADDON_LIST_CTRL] + 4` (= `entry + 0x10`); a
// low-bit-1 sentinel or NULL terminates. This is the same traversal the
// engine's own load pass (`FUN_0051F600`) and scan tail loop use.
//
// `fn` may return `void` (always continue) or `bool` (return `false` to STOP
// early, e.g. once a by-name search finds its entry). A visitor must not
// unlink the entry it is given and then continue: the walk reads that
// entry's next-pointer after the call. Shared by `Addons::Embedded` (find the
// embedded entry) and `Addons::Rescan` (snapshot / diff / fix-up passes).
template <typename Fn> void ForEachEntry(Fn fn) {
const int linkOffset = *reinterpret_cast<const int *>(
static_cast<uintptr_t>(Offsets::VAR_ADDON_LIST_CTRL));
uintptr_t entry = *reinterpret_cast<const uintptr_t *>(
static_cast<uintptr_t>(Offsets::VAR_ADDON_LIST_HEAD));
while ((entry & 1) == 0 && entry != 0) {
if constexpr (std::is_void_v<decltype(fn(entry))>) {
fn(entry);
} else {
if (!fn(entry))
return;
}
entry = *reinterpret_cast<const uintptr_t *>(entry + linkOffset + 4);
}
}
// Resolves Lua arg 1 (index or name) to the addon's registry record, with
// the arg handling of stock `Script_GetAddOnDependencies` (`0x0048E5E0`) —
// the same shape 3.3.5 gives every `(index or "name")` addon global:
// `lua_isnumber` first (so a numeric string like `"3"` is an index), an
// out-of-range index raises the engine's own range error with the addon
// count, anything else non-string raises `usage`, and an unknown *name*
// returns nullptr with no error.
const uint8_t *ResolveRecord(void *L, const char *usage);
} // namespace Addons
+479
View File
@@ -0,0 +1,479 @@
// 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/>.
// Retail-like `/reload`: pick up new addon folders and new files without
// restarting the client. Two independent engine limitations block that on
// a stock 1.12 client, each fixed here with the engine's own machinery:
//
// 1. FILE VISIBILITY. Every relative-path read resolves through a
// loose-file hash index (see Offsets.h, `FUN_VFS_INDEX_CLEAR`);
// a file created after the index was built — a new addon's TOC, a
// new .lua in an existing addon — is invisible until it is rebuilt.
// We call the engine's own clear, the same one the engine calls
// after writing a new SavedVariables file: the next lookup rebuilds
// the index from disk as boot does, so new files appear and deleted
// ones drop out. New files in EXISTING addons need nothing more —
// the per-addon loader `FUN_0051F240` re-reads the TOC from disk on
// every load pass, so once the files are visible they load.
//
// 2. REGISTRY MEMBERSHIP. The addon registry is built once at login;
// new folders are never walked. We replay the login scan's disk
// walk verbatim (`FUN_ADDON_SCAN_DISK_DIRS` with the engine's own
// per-directory callback, which feeds the dedup-safe TOC parser),
// so new folders register as completely normal entries — then
// mirror the two registry structures the scan's OTHER passes would
// have filled: the reverse-LoadWith lists (scan tail loop) and the
// flat `GetNumAddOns` display array (`FUN_0051DA70` phase 2).
//
// 3. METADATA IMMUTABILITY. The parser's dedup guard makes a
// registered entry's `##` metadata read-once: an edited
// `## SavedVariables:` / `## Dependencies:` / any `##` line never
// re-parses. The engine's own complete per-entry destructor
// (`FUN_ADDON_ENTRY_DESTROY` — frees every owned allocation and
// self-unlinks from both the list and the hash; see Offsets.h)
// makes evict + re-register safe: destroy the entry so the dedup
// guard MISSES, re-feed the name to `FUN_TOC_PARSER`, and the
// entry rebuilds from the edited TOC exactly like a fresh
// registration. Gated on an actual `##` change (hash of the TOC's
// `##` lines only — file-reference edits load natively and never
// trigger the evict path). A TOC that no longer reads at all
// (folder deleted) evicts without re-registering — the deletion
// analog; a folder the scan still finds simply re-registers.
//
// Runs from the `ModuleAutoRegister` callback — LoadScriptFunctions
// post-hook, which fires inside FrameXML init (`FUN_0048FBF0`) BEFORE
// the AddOns.txt enable-state re-read, the load-progress count, and the
// addon load pass, on both login and every /reload. The engine then
// loads new entries natively: dep ordering, Bindings.xml, flavor TOCs,
// SavedVariables, ADDON_LOADED, the load-screen "Loading add-on %s".
// The window is also what makes eviction safe: the unload pass already
// ran (SavedVariables written from the OLD entry's SV lists, loaded
// bytes cleared), and the load pass hasn't — nothing holds entry state.
//
// Excluded from the evict path (everything else is fair game):
// - the embedded addons — `Addons::Embedded` owns their entries
// (registered first + filter byte);
// - `## Secure:` / SMSG-managed entries — the parser cannot restore
// packet-delivered state (see OFF_ADDON_ENTRY_SECURE).
//
// NOTE the surgical discipline. A previous attempt re-invoked the
// login-only teardown+rescan (`LoadAddOnsForAccount`, `0x0051C740`)
// mid-/reload and corrupted the registry (duplicate loads + Lua memory explosion on the
// NEXT login). This module never runs bulk teardown; the only entry
// mutation beyond what a login scan produces is the per-entry evict
// above, which is (a) the engine's own complete destructor, (b) always
// preceded by the reverse-LoadWith scrub (the one reference the dtor
// can't clean), and (c) always followed by the same fix-ups a new
// registration gets. New entries come from the same parser call
// `Addons::Embedded` has exercised every login.
//
// Thread note: the loose-file index has no lock in 1.12. We clear it on
// the main thread during the reload loading screen — the same context
// in which the engine's own unload pass clears it.
#include "Game.h"
#include "Offsets.h"
#include "addons/Embedded.h"
#include "addons/EngineIO.h"
#include "addons/Registry.h"
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <unordered_map>
#include <vector>
namespace Addons::Rescan {
namespace {
// ── Engine entry points (all verified by disassembly; see Offsets.h) ──
using IndexClear_t = void(__cdecl *)();
using ScanDiskDirs_t = int(__fastcall *)(const char *basePath,
const char *pattern, void *callback,
void *userParam, int includeHidden);
using ResolveByName_t = void *(__fastcall *)(const char *name);
using DescGrow_t = void(__thiscall *)(void *desc, uint32_t newCap);
using QuantumCalc_t = uint32_t(__thiscall *)(void *desc, uint32_t needed);
using Qsort_t = void(__cdecl *)(void *base, uint32_t num, uint32_t width,
void *compare);
using TocParser_t = void(__fastcall *)(const char *name);
using EntryDestroy_t = void(__stdcall *)(void *entry);
// The engine's ubiquitous growable-array descriptor.
struct Desc {
uint32_t cap;
uint32_t count;
uint32_t *data;
uint32_t quantum;
};
// Append one dword to a descriptor, mirroring the engine's inline
// grow-and-append (the scan tail loop and `FUN_0051DA70` phase 2 share
// it): round the needed cap up to the quantum — computed by the
// engine's own `FUN_DESC_QUANTUM_CALC` when the desc has none — grow
// via the site's grow instantiation (which reallocs `data` and writes
// `cap`), then `data[count++] = value`.
void DescAppend(Desc *desc, uint32_t value, DescGrow_t grow) {
uint32_t needed = desc->count + 1;
if (desc->cap < needed) {
uint32_t quantum = desc->quantum;
if (quantum == 0) {
auto calc =
reinterpret_cast<QuantumCalc_t>(Offsets::FUN_DESC_QUANTUM_CALC);
quantum = calc(desc, needed);
}
if (needed % quantum != 0)
needed += quantum - needed % quantum;
grow(desc, needed);
}
desc->data[desc->count++] = value;
}
// The registry linked-list walk lives in `addons/Registry.h`
// (`Addons::ForEachEntry`), shared with `Addons::Embedded`.
// By-name registry lookup via the engine's own hash resolver (returns
// the entry's RequiredDeps desc, so subtract its offset — same recovery
// `Addons::Info` uses).
uintptr_t ResolveEntryByName(const char *name) {
auto resolve =
reinterpret_cast<ResolveByName_t>(Offsets::FUN_ADDON_RESOLVE_REQ_DEPS);
const uintptr_t desc = reinterpret_cast<uintptr_t>(resolve(name));
return desc != 0 ? desc - Offsets::OFF_ADDON_REQDEPS_DESC : 0;
}
// ── Step 1: loose-file index refresh ──────────────────────────────────
// Drop the loose-file index; the next file lookup rebuilds it from disk.
void RefreshLooseFileIndex() {
reinterpret_cast<IndexClear_t>(Offsets::FUN_VFS_INDEX_CLEAR)();
}
// ── Step 1.5: `##` metadata refresh (evict + re-register on change) ──
// name → FNV-1a hash of the addon's `##` lines, as last parsed.
// Per-process on purpose: the registry persists across /reload, and a
// stale hash after a full re-login scan only causes one harmless
// re-parse of already-current metadata.
std::unordered_map<std::string, uint32_t> g_metaHash;
// Read `<name>`'s base TOC exactly as the parser does — through the
// (hooked) `FUN_FILE_READ`, so flavor selection and TOC rewriting are
// reflected in what gets hashed. Caller frees `*buf` via Storm.
bool ReadToc(const char *name, void **buf, size_t *size) {
char path[260];
std::snprintf(path, sizeof(path), "Interface\\AddOns\\%s\\%s.toc", name,
name);
auto read = reinterpret_cast<AddOns::EngineIO::FileReadFn>(
static_cast<uintptr_t>(Offsets::FUN_FILE_READ));
*buf = nullptr;
*size = 0;
return read(0, path, buf, size, 1, 1, 0) != 0 && *buf != nullptr;
}
// FNV-1a over the TOC's `##` lines only. File-reference lines are
// excluded on purpose — the load pass re-reads those from disk every
// /reload anyway, so an edit there must not trigger the evict path.
// Line terminators are excluded (a CRLF↔LF conversion is not a
// metadata change); a per-line separator keeps adjacent lines from
// concatenating into the same hash. The BOM skip mirrors the parser.
uint32_t HashTocMetadata(const char *buf, size_t size) {
uint32_t h = 2166136261u;
size_t i = 0;
if (size >= 3 && static_cast<uint8_t>(buf[0]) == 0xEF &&
static_cast<uint8_t>(buf[1]) == 0xBB &&
static_cast<uint8_t>(buf[2]) == 0xBF)
i = 3;
while (i < size) {
size_t end = i;
while (end < size && buf[end] != '\n')
++end;
size_t stop = end;
while (stop > i && buf[stop - 1] == '\r')
--stop;
if (stop - i >= 2 && buf[i] == '#' && buf[i + 1] == '#') {
for (size_t k = i; k < stop; ++k) {
h ^= static_cast<uint8_t>(buf[k]);
h *= 16777619u;
}
h ^= '\n';
h *= 16777619u;
}
i = end + 1;
}
return h;
}
// True when the entry never takes the evict path: the embedded addons
// (owned by `Addons::Embedded` — registered first + filter byte) and
// SMSG-managed secure entries (the parser cannot restore packet-delivered
// state).
bool IsRefreshExempt(uintptr_t entry, const char *name) {
return name == nullptr || Addons::Embedded::IsEmbedded(name) ||
*reinterpret_cast<const uint8_t *>(
entry + Offsets::OFF_ADDON_ENTRY_SECURE) != 0;
}
// Read + hash `<name>`'s `##` lines. False when the TOC doesn't read.
bool TryHashToc(const char *name, uint32_t *outHash) {
void *buf = nullptr;
size_t size = 0;
if (!ReadToc(name, &buf, &size))
return false;
*outHash = HashTocMetadata(static_cast<const char *>(buf), size);
reinterpret_cast<AddOns::EngineIO::SMemFreeFn>(
static_cast<uintptr_t>(Offsets::FUN_STORM_SMEM_FREE))(
buf, __FILE__, __LINE__, 0);
return true;
}
// Remove every pointer to `victim` from the OTHER entries'
// reverse-LoadWith lists — the one reference `FUN_ADDON_ENTRY_DESTROY`
// cannot clean (it frees the victim's own list, not the victim's
// presence in others'). Without this, the loader's post-ADDON_LOADED
// loop dereferences freed memory.
void ScrubReverseLoadWith(uintptr_t victim) {
ForEachEntry([victim](uintptr_t entry) {
if (entry == victim)
return;
auto *desc = reinterpret_cast<Desc *>(
entry + Offsets::OFF_ADDON_REVLOADWITH_DESC);
uint32_t w = 0;
for (uint32_t r = 0; r < desc->count; ++r)
if (desc->data[r] != static_cast<uint32_t>(victim))
desc->data[w++] = desc->data[r];
desc->count = w;
});
}
// The refresh pass. Walks the registry comparing each entry's current
// `##` hash against the last-parsed one; on change (or an unreadable
// TOC — deleted folder), evicts via the engine's own destructor and,
// for changes, re-feeds the name to the parser. Re-registered entries
// are appended to `refreshed` so they join the same reverse-LoadWith /
// display-array fix-ups a new folder gets. Returns true when anything
// was actually evicted (the display array holds a freed name pointer
// until it's rebuilt).
//
// Victims are collected during the walk and processed after it — the
// destructor unlinks the entry the iterator stands on (its next-pointer
// is zeroed), so evicting mid-walk would silently truncate the walk.
// Names are copied for the same reason: the dtor frees the entry's
// name string. `g_metaHash` is committed only once the re-registration
// actually happened — updating it during the walk would absorb the edit
// forever if any later step failed, with no retry on the next /reload.
bool RefreshChangedMetadata(std::vector<uintptr_t> &refreshed) {
struct Victim {
std::string name;
uint32_t newHash;
bool reRegister; // false: TOC unreadable — evict only
};
std::vector<Victim> victims;
ForEachEntry([&victims](uintptr_t entry) {
const char *name = *reinterpret_cast<const char *const *>(
entry + Offsets::OFF_ADDON_ENTRY_NAME_PTR);
if (IsRefreshExempt(entry, name))
return;
uint32_t h = 0;
if (!TryHashToc(name, &h)) {
victims.push_back({name, 0, false});
return;
}
auto it = g_metaHash.find(name);
if (it == g_metaHash.end())
g_metaHash.emplace(name, h); // first sighting — seed only
else if (it->second != h)
victims.push_back({name, h, true});
});
bool anyEvicted = false;
auto destroy =
reinterpret_cast<EntryDestroy_t>(Offsets::FUN_ADDON_ENTRY_DESTROY);
auto parse = reinterpret_cast<TocParser_t>(Offsets::FUN_TOC_PARSER);
for (const Victim &v : victims) {
const uintptr_t entry = ResolveEntryByName(v.name.c_str());
if (entry == 0)
continue;
ScrubReverseLoadWith(entry);
destroy(reinterpret_cast<void *>(entry));
anyEvicted = true;
if (!v.reRegister) {
g_metaHash.erase(v.name);
continue;
}
// The parser appends the fresh entry at the list TAIL, so a
// refreshed addon's position in the load pass changes for this
// reload. Declared dependencies still force-load first; only
// undeclared load-order assumptions between unrelated addons
// could observe the difference.
parse(v.name.c_str());
const uintptr_t fresh = ResolveEntryByName(v.name.c_str());
if (fresh != 0) {
refreshed.push_back(fresh);
g_metaHash[v.name] = v.newHash;
} else {
// Evicted but the parse didn't restore it (TOC became
// unreadable between hash and parse) — treat as deleted so
// a reappearing folder re-seeds instead of diffing against
// a hash the registry never absorbed.
g_metaHash.erase(v.name);
}
}
return anyEvicted;
}
// ── Step 2: registry rescan + mirrored fix-ups ────────────────────────
// The scan tail loop's reverse-LoadWith build, restricted to pairs
// involving a newly registered entry. Login already linked old→old
// pairs; a pair is missing exactly when one side is new (the login
// walk skipped `## LoadWith:` names that didn't resolve, and new
// entries were never walked at all) — so appending just those pairs
// reproduces what a login scan would have built, with no duplicates in
// the engine's no-dedup lists.
void FixupReverseLoadWith(const std::vector<uintptr_t> &added) {
auto isNew = [&added](uintptr_t e) {
return std::find(added.begin(), added.end(), e) != added.end();
};
auto grow =
reinterpret_cast<DescGrow_t>(Offsets::FUN_ADDON_REVLOADWITH_GROW);
ForEachEntry([&](uintptr_t entry) {
const bool entryIsNew = isNew(entry);
const uint32_t count = *reinterpret_cast<const uint32_t *>(
entry + Offsets::OFF_ADDON_LOADWITH_COUNT);
auto names = *reinterpret_cast<const char *const *const *>(
entry + Offsets::OFF_ADDON_LOADWITH_ARRAY);
for (uint32_t i = 0; i < count; ++i) {
const uintptr_t target = ResolveEntryByName(names[i]);
if (target == 0 || (!entryIsNew && !isNew(target)))
continue;
DescAppend(reinterpret_cast<Desc *>(
target + Offsets::OFF_ADDON_REVLOADWITH_DESC),
static_cast<uint32_t>(entry), grow);
}
});
}
// `FUN_0051DA70` phase 2, mirrored (never call that function itself —
// its phase 1 consumes an SMSG_ADDON_INFO packet): rebuild the
// `GetNumAddOns`/`GetAddOnInfo(i)` name-pointer array from the linked
// list, skipping filtered entries (keeps the embedded addons hidden), then
// sort with the engine's own comparator to restore alphabetical order.
void RebuildDisplayArray() {
auto desc = reinterpret_cast<Desc *>(
static_cast<uintptr_t>(Offsets::VAR_ADDON_ARRAY_CAP));
auto grow = reinterpret_cast<DescGrow_t>(Offsets::FUN_ADDON_ARRAY_GROW);
desc->count = 0;
ForEachEntry([&](uintptr_t entry) {
if (*reinterpret_cast<const uint8_t *>(
entry + Offsets::OFF_ADDON_ENTRY_FILTER_OUT) != 0)
return;
DescAppend(desc,
*reinterpret_cast<const uint32_t *>(
entry + Offsets::OFF_ADDON_ENTRY_NAME_PTR),
grow);
});
auto qsort = reinterpret_cast<Qsort_t>(Offsets::FUN_CRT_QSORT);
qsort(desc->data, desc->count, 4,
reinterpret_cast<void *>(Offsets::FUN_ADDON_NAME_COMPARE));
}
void Run() {
// Registry populated (login scan ran) — always true by the first
// in-world LoadScriptFunctions, but it is the state the steps below
// mutate, so gate explicitly. No gate on the index being built: the
// unload pass clears it whenever it wrote a new SV file, and the
// clear below is safe either way.
if (*reinterpret_cast<const uint8_t *>(
static_cast<uintptr_t>(Offsets::VAR_ADDON_INITIALIZED)) == 0)
return;
RefreshLooseFileIndex();
// Metadata refresh runs BEFORE the snapshot: a re-registered entry
// is alive by snapshot time, so it lands in `before` and can never
// double-count in `added` — even if the allocator reuses the old
// entry's address, `refreshed` tracks it independently of the diff.
std::vector<uintptr_t> refreshed;
const bool evicted = RefreshChangedMetadata(refreshed);
std::vector<uintptr_t> before;
ForEachEntry([&before](uintptr_t entry) { before.push_back(entry); });
// Replay login scan walk #2 verbatim: engine walker + engine
// callback + engine parser. The parser's dedup guard makes this a
// hash lookup per already-registered addon; new folders register
// as complete, normal entries (their TOC is readable now — and it
// goes through the FlavorToc/TocRewrite read hooks like any other).
//
// The dedup guard is why this replay can NEVER refresh or corrupt
// an existing entry's `##` metadata (verified in the parser's
// decompile): the guard is the function's FIRST block — hash
// lookup + name compare, early `return` on match BEFORE the TOC
// path is even built, so no file read and no entry write happen
// for a registered name. Both the Storm hash (`FUN_0064B3F0`,
// uppercases a–z and folds '/'→'\\' before hashing) and the
// compare (`SStrCmpI`) are case-insensitive, so a case-renamed
// folder still matches its existing entry rather than registering
// a duplicate.
auto scan =
reinterpret_cast<ScanDiskDirs_t>(Offsets::FUN_ADDON_SCAN_DISK_DIRS);
scan(reinterpret_cast<const char *>(Offsets::VAR_ADDON_PATH_PREFIX),
reinterpret_cast<const char *>(Offsets::VAR_ADDON_SCAN_PATTERN),
reinterpret_cast<void *>(Offsets::FUN_ADDON_DISK_DIR_CB),
/*userParam=*/nullptr, /*includeHidden=*/0);
std::vector<uintptr_t> added;
ForEachEntry([&](uintptr_t entry) {
if (std::find(before.begin(), before.end(), entry) == before.end())
added.push_back(entry);
});
// Seed the metadata map for entries this reload registered, so the
// next reload diffs a `##` edit against what was actually parsed
// (waiting for the next pass to seed would silently absorb an edit
// made between now and then).
for (uintptr_t entry : added) {
const char *name = *reinterpret_cast<const char *const *>(
entry + Offsets::OFF_ADDON_ENTRY_NAME_PTR);
uint32_t h = 0;
if (!IsRefreshExempt(entry, name) && TryHashToc(name, &h))
g_metaHash[name] = h;
}
if (added.empty() && refreshed.empty() && !evicted)
return;
// Refreshed entries need the same link fix-ups a new folder gets:
// their old reverse-LoadWith pairs died with the old entry (scrub +
// dtor), and the parser doesn't build reverse links.
std::vector<uintptr_t> linked = added;
linked.insert(linked.end(), refreshed.begin(), refreshed.end());
if (!linked.empty())
FixupReverseLoadWith(linked);
// Rebuild whenever membership OR an entry identity changed — after
// any eviction (including a pure deletion) the display array still
// holds the dead entry's freed name pointer.
RebuildDisplayArray();
}
const Game::ModuleAutoRegister _autoreg{&Run};
} // namespace
} // namespace Addons::Rescan
+262
View File
@@ -0,0 +1,262 @@
// 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/>.
// `## LoadSavedVariablesFirst: 1` — modern TOC directive, backported.
//
// Retail loads a flagged addon's SavedVariables BEFORE its Lua runs, so
// file-scope code (`local db = MyAddonDB`) sees restored config immediately.
// Vanilla 1.12 always does the opposite: the per-addon loader `FUN_0051f240`
// runs the addon's files (`FUN_ADDON_LOAD_FILES`), THEN loads SavedVariables,
// THEN fires `ADDON_LOADED`. So file-scope SV is always nil, and vanilla never
// parses the directive at all.
//
// We co-hook `FUN_ADDON_LOAD_FILES` (the per-addon file load, once per addon,
// in-world). For an addon whose TOC declares `## LoadSavedVariablesFirst`
// (nonzero), load its SavedVariables first — mirroring the engine's OWN path
// construction two steps later in `FUN_0051f240` (verified by disassembly):
// account : WTF\Account\<account>\SavedVariables\<Name>.lua
// per-char: WTF\Account\<account>\<realm>\<character>\SavedVariables\<Name>.lua,
// falling back to WTF\Account\<account>\<character>\SavedVariables\<Name>.lua
// (account = *VAR_ACCOUNT_NAME_PTR, realm = FUN_GET_REALM_NAME,
// character = FUN_GET_LOGIN_ACCOUNT_NAME) — then call the original so the
// files run with SV present. `FUN_LUA_LOAD_FILE` no-ops on a missing file, and
// `FUN_FILE_EXISTS` picks the same per-char variant the engine would.
//
// The engine STILL runs its own SavedVariables load at the normal step, right
// after the files. Left alone, that re-load would overwrite any value the
// addon wrote to its SavedVariable at file scope before ADDON_LOADED. So we
// also suppress that one redundant re-load, through Script::LoadFile's shared
// FUN_LUA_LOAD_FILE hook: each path we pre-load is remembered, and the
// engine's imminent load of that exact path is skipped once. This makes the
// behavior match true LoadSavedVariablesFirst — file-scope reads AND writes
// both survive. Our own early load calls Script::LoadFile::Original, so it is
// never self-suppressed. FUN_LUA_LOAD_FILE loads FILES only (not RunScript
// string execution), so this is a cold, addon-load-time path.
#include "Game.h"
#include "Offsets.h"
#include "addons/EngineIO.h"
#include "addons/Toc.h"
#include "script/LoadFile.h"
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
namespace AddOns::SavedVarsFirst {
namespace {
constexpr size_t NPOS = static_cast<size_t>(-1);
// Engine file I/O via the hooked FUN_FILE_READ (so a flavor TOC's flag is read —
// FlavorToc applies), the exists-check, and the Storm free. See addons/EngineIO.h.
using AddOns::EngineIO::FileExistsFn;
using AddOns::EngineIO::FileReadFn;
using AddOns::EngineIO::SMemFreeFn;
using LoadTocFilesFn = uint32_t(__fastcall *)(char *tocPath, int *a2, int *a3);
using NameFn = const char *(*)(); // no-arg readers (return in EAX)
LoadTocFilesFn g_orig = nullptr;
// Full SV paths we pre-loaded whose imminent engine re-load must be skipped
// once. Populated in LoadSavedVarsEarly, drained by SuppressReload. Only ever holds
// a handful of entries (one addon's SV files, briefly). Main-thread only.
std::vector<std::string> g_pendingSuppress;
using AddOns::Toc::EqCI;
using AddOns::Toc::Lower;
bool SamePathCI(const char *a, const char *b) {
for (; *a != '\0' && *b != '\0'; ++a, ++b)
if (Lower(*a) != Lower(*b)) return false;
return *a == *b;
}
// Extract "<Name>" from an addon base-TOC path `…\AddOns\<Name>\<Name>.toc`.
// Returns false for anything else (FrameXML.toc, nested paths, …) so the
// SavedVariables reorder only touches real addon loads.
bool AddonNameFromToc(const char *path, char *out, size_t outSize) {
const size_t len = std::strlen(path);
if (len < 4 || !(path[len - 4] == '.' && Lower(path[len - 3]) == 't' &&
Lower(path[len - 2]) == 'o' && Lower(path[len - 1]) == 'c'))
return false;
size_t lastSep = NPOS;
for (size_t i = len; i-- > 0;)
if (path[i] == '\\' || path[i] == '/') { lastSep = i; break; }
if (lastSep == NPOS) return false;
size_t prevSep = NPOS;
for (size_t i = lastSep; i-- > 0;)
if (path[i] == '\\' || path[i] == '/') { prevSep = i; break; }
if (prevSep == NPOS) return false;
size_t gpSep = NPOS;
for (size_t i = prevSep; i-- > 0;)
if (path[i] == '\\' || path[i] == '/') { gpSep = i; break; }
if (gpSep == NPOS) return false;
if (prevSep - (gpSep + 1) != 6 || !EqCI(path + gpSep + 1, 6, "AddOns"))
return false;
const size_t nameLen = lastSep - (prevSep + 1);
if (nameLen == 0 || nameLen + 1 > outSize) return false;
std::memcpy(out, path + prevSep + 1, nameLen);
out[nameLen] = '\0';
return true;
}
// True iff the leading integer of a TOC value is nonzero (WoW numeric flag).
bool NonzeroFlag(const char *v, size_t n) {
long val = 0;
bool digit = false;
for (size_t i = 0; i < n && v[i] >= '0' && v[i] <= '9'; ++i) {
val = val * 10 + (v[i] - '0');
digit = true;
}
return digit && val != 0;
}
// The SavedVariables directives that decide what LoadSavedVarsEarly does.
struct SvFlags {
bool first = false; // `## LoadSavedVariablesFirst:` is nonzero
bool account = false; // `## SavedVariables:` declares at least one variable
bool perChar = false; // `## SavedVariablesPerCharacter:` declares at least one
};
// Read the addon's TOC once (through the hooked FUN_FILE_READ, so a flavor
// TOC's directives are honored) and extract the three flags above.
SvFlags ReadSvFlags(const char *tocPath) {
SvFlags f;
auto FileRead =
reinterpret_cast<FileReadFn>(static_cast<uintptr_t>(Offsets::FUN_FILE_READ));
void *buf = nullptr;
size_t size = 0;
if (FileRead(0, tocPath, &buf, &size, 1, 1, 0) == 0 || buf == nullptr)
return f;
const char *b = static_cast<const char *>(buf);
const char *v = nullptr;
size_t n = 0;
if (AddOns::Toc::FindValue(b, size, "LoadSavedVariablesFirst", &v, &n))
f.first = NonzeroFlag(v, n);
// Gate each SV file on the DECLARATION, not mere file existence — mirroring
// the engine, which loads the account file iff `## SavedVariables` is
// declared and the per-char file iff `## SavedVariablesPerCharacter` is.
// (FindValue requires `:` right after the key, so "SavedVariables" never
// matches the "## SavedVariablesPerCharacter:" line.) Otherwise a stale SV file from a
// scope the addon no longer declares would be executed early — Lua the
// engine never runs — and queued for a suppression the engine never drains.
f.account = AddOns::Toc::FindValue(b, size, "SavedVariables", &v, &n) && n > 0;
f.perChar =
AddOns::Toc::FindValue(b, size, "SavedVariablesPerCharacter", &v, &n) && n > 0;
reinterpret_cast<SMemFreeFn>(static_cast<uintptr_t>(Offsets::FUN_STORM_SMEM_FREE))(
buf, __FILE__, __LINE__, 0);
return f;
}
bool FileExists(const char *path) {
return reinterpret_cast<FileExistsFn>(
static_cast<uintptr_t>(Offsets::FUN_FILE_EXISTS))(path, 1) != 0;
}
// Load a SavedVariables file we found, then mark its path so the engine's own
// re-load of it (right after the addon's files) is suppressed — preserving any
// file-scope write. Calls the engine loader directly so this load is never
// itself suppressed by SuppressReload.
void RunLuaFile(const char *path) {
Script::LoadFile::Original(path, nullptr, nullptr);
g_pendingSuppress.emplace_back(path);
}
// Load the addon's SavedVariables early, mirroring FUN_0051f240's own paths.
// Each scope loads only when its directive is declared (`hasAccount` /
// `hasPerChar`) AND the file exists — exactly what the engine's own SV step
// would re-load, so every suppress entry we queue is later drained.
void LoadSavedVarsEarly(const char *addonName, bool hasAccount, bool hasPerChar) {
const char *account = *reinterpret_cast<const char *const *>(
static_cast<uintptr_t>(Offsets::VAR_ACCOUNT_NAME_PTR));
if (account == nullptr || *account == '\0')
return;
char path[260];
// Account-wide (`## SavedVariables`).
if (hasAccount) {
std::snprintf(path, sizeof path, "WTF\\Account\\%s\\SavedVariables\\%s.lua",
account, addonName);
if (FileExists(path))
RunLuaFile(path);
}
// Per-character (`## SavedVariablesPerCharacter`): prefer the realm-scoped
// file, else the realm-less one — the engine's own fallback order.
if (!hasPerChar)
return;
const char *character = reinterpret_cast<NameFn>(
static_cast<uintptr_t>(Offsets::FUN_GET_LOGIN_ACCOUNT_NAME))();
if (character == nullptr || *character == '\0')
return;
const char *realm = reinterpret_cast<NameFn>(
static_cast<uintptr_t>(Offsets::FUN_GET_REALM_NAME))();
if (realm != nullptr && *realm != '\0') {
std::snprintf(path, sizeof path,
"WTF\\Account\\%s\\%s\\%s\\SavedVariables\\%s.lua", account,
realm, character, addonName);
if (FileExists(path)) {
RunLuaFile(path);
return;
}
}
std::snprintf(path, sizeof path, "WTF\\Account\\%s\\%s\\SavedVariables\\%s.lua",
account, character, addonName);
if (FileExists(path))
RunLuaFile(path);
}
uint32_t __fastcall LoadTocFiles_h(char *tocPath, int *a2, int *a3) {
char name[128];
if (tocPath != nullptr && AddonNameFromToc(tocPath, name, sizeof name)) {
const SvFlags f = ReadSvFlags(tocPath);
if (f.first)
LoadSavedVarsEarly(name, f.account, f.perChar);
}
return g_orig(tocPath, a2, a3);
}
// Skip the engine's one redundant SavedVariables re-load per pre-loaded path.
// Every other file load passes straight through. Match is by full path
// (case-insensitive); a path is suppressed exactly once, so nothing else is
// affected. Our own early load bypasses this through Original.
bool SuppressReload(const char *path) {
for (size_t i = 0; i < g_pendingSuppress.size(); ++i) {
if (SamePathCI(g_pendingSuppress[i].c_str(), path)) {
g_pendingSuppress.erase(g_pendingSuppress.begin() +
static_cast<std::ptrdiff_t>(i));
return true; // suppress — the addon's file-scope SV writes survive
}
}
return false;
}
const Game::HookAutoRegister _hook{
Offsets::FUN_ADDON_LOAD_FILES,
reinterpret_cast<void *>(&LoadTocFiles_h),
reinterpret_cast<void **>(&g_orig)};
const Script::LoadFile::AutoSuppress _suppress{&SuppressReload};
} // namespace
} // namespace AddOns::SavedVarsFirst
+92
View File
@@ -0,0 +1,92 @@
// 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
#include <cstddef>
#include <cstring>
namespace AddOns::Toc {
// Fold an ASCII letter to lower case (leaves every other byte unchanged).
inline char Lower(char c) {
return (c >= 'A' && c <= 'Z') ? static_cast<char>(c + 32) : c;
}
// Case-insensitive equality of the `n` bytes at `s` against the NUL-terminated
// `lit` (ASCII). True only when the lengths match too. Shared by the addon
// modules that scan `…\AddOns\<Name>\…` paths and TOC directive lines.
inline bool EqCI(const char *s, size_t n, const char *lit) {
for (size_t i = 0; i < n; ++i)
if (lit[i] == '\0' || Lower(s[i]) != Lower(lit[i]))
return false;
return lit[n] == '\0';
}
// Scans an in-memory TOC buffer for the `## <key>:` directive and returns the
// first one's value via out-params: [*valStart, *valStart + *valLen), trimmed
// of leading and trailing spaces/tabs and excluding the CR/LF/EOF terminator.
// `key` is the bare name ("Version", "SavedVariables"). Returns false
// (out-params untouched) when the directive is absent.
//
// Matches lines the way the engine's TOC parser `FUN_TOC_PARSER` (0x0051C9B0)
// does, so a directive the engine reads is never one we miss: a UTF-8 BOM at
// the start of the file is skipped; lines break at CR or LF; a line counts
// when it starts with "##", then any number of spaces, then `key`
// case-insensitively, IMMEDIATELY followed by ':' (the engine compares
// against literals like "SavedVariables:", which is also why
// "SavedVariables" never matches a "SavedVariablesPerCharacter:" line).
//
// Pure — reads no files; the caller owns the buffer (via FUN_FILE_READ, or an
// embedded copy). Shared by every addon module that reads a TOC directive so
// the line-scan lives in one place.
inline bool FindValue(const char *buf, size_t size, const char *key,
const char **valStart, size_t *valLen) {
const size_t klen = std::strlen(key);
if (klen == 0)
return false;
const char *end = buf + size;
const char *line = buf;
if (size >= 3 && static_cast<unsigned char>(buf[0]) == 0xEF &&
static_cast<unsigned char>(buf[1]) == 0xBB &&
static_cast<unsigned char>(buf[2]) == 0xBF)
line += 3;
while (line < end) {
const char *eol = line;
while (eol < end && *eol != '\r' && *eol != '\n')
++eol;
const char *p = line;
if (eol - p >= 2 && p[0] == '#' && p[1] == '#') {
p += 2;
while (p < eol && *p == ' ')
++p;
if (static_cast<size_t>(eol - p) > klen && EqCI(p, klen, key) &&
p[klen] == ':') {
p += klen + 1;
while (p < eol && (*p == ' ' || *p == '\t'))
++p;
const char *v = p;
p = eol;
while (p > v && (p[-1] == ' ' || p[-1] == '\t'))
--p;
*valStart = v;
*valLen = static_cast<size_t>(p - v);
return true;
}
}
line = eol + 1;
}
return false;
}
} // namespace AddOns::Toc
+304
View File
@@ -0,0 +1,304 @@
// 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 "addons/EngineIO.h"
#include "addons/TocRewrite.h"
#include "addons/Toc.h"
#include "localization/Locale.h"
#include "Offsets.h"
#include "turtle/Detect.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
namespace AddOns::TocRewrite {
namespace {
using AddOns::EngineIO::SMemAllocFn;
using AddOns::EngineIO::SMemFreeFn;
using AddOns::Toc::EqCI;
using AddOns::Toc::Lower;
bool IsSpace(char c) { return c == ' ' || c == '\t'; }
using Localization::Locale::Client;
// True iff the comma-separated `list` (spaces allowed) contains `token` (CI).
bool ListContains(const char *list, size_t listLen, const char *token) {
size_t i = 0;
while (i < listLen) {
while (i < listLen && (IsSpace(list[i]) || list[i] == ',')) ++i;
const size_t start = i;
while (i < listLen && list[i] != ',') ++i;
size_t end = i; // [start, end) is one item, maybe with trailing space
while (end > start && IsSpace(list[end - 1])) --end;
if (end > start && EqCI(list + start, end - start, token)) return true;
}
return false;
}
// A single-word `[Token]` variable expansion, or nullptr if `head` is not
// a known variable. This 1.12 + ClassicAPI client is the Classic family,
// the Vanilla game type, and whatever the client text locale is.
const char *VariableValue(const char *head, size_t headLen) {
if (EqCI(head, headLen, "Family")) return "Classic";
if (EqCI(head, headLen, "Game")) return "Vanilla";
if (EqCI(head, headLen, "TextLocale")) return Client();
return nullptr;
}
// The client interface version the loadability check compares against
// (FUN_0051d7d0 -> 0x2BC0 = 11200). Read live so we mirror the engine's own
// value rather than hardcoding it.
using ClientIfaceVer_t = uint32_t(__cdecl *)();
uint32_t ClientInterfaceVersion() {
return reinterpret_cast<ClientIfaceVer_t>(
static_cast<uintptr_t>(Offsets::FUN_ADDON_CLIENT_INTERFACE_VERSION))();
}
// If `line` is a `## Interface:` directive whose value is a comma-list, pick
// the retail value — the closest entry at or below the client version — and,
// when that is not already the first entry, append a normalized
// `<prefix>: <value>` line to `out` and return true. Vanilla's parser reads
// only the first number, so without this a later 11200 is never seen and the
// addon is marked out of date. Loadability stays an exact match on the client
// version, and the pick equals it iff it is in the list, so this only changes
// the stored value (what GetAddOnInterfaceVersion reads) for lists that were
// out of date anyway. Returns false for any other line, and for an interface
// line that needs no change (single value, nothing at or below the client
// version, or the pick already first) — the caller then copies the line
// verbatim.
bool TryRewriteInterfaceLine(const char *line, size_t len, std::string &out) {
size_t s = 0;
while (s < len && IsSpace(line[s])) ++s;
if (s + 1 >= len || line[s] != '#' || line[s + 1] != '#') return false;
size_t p = s + 2;
while (p < len && IsSpace(line[p])) ++p;
static const char kKey[] = "interface"; // matched case-insensitively
const size_t klen = 9;
if (p + klen > len) return false;
for (size_t i = 0; i < klen; ++i)
if (Lower(line[p + i]) != kKey[i]) return false;
p += klen;
while (p < len && IsSpace(line[p])) ++p;
if (p >= len || line[p] != ':') return false;
++p; // past ':'
const size_t prefixEnd = p; // "## Interface:" (author spacing preserved)
const uint32_t client = ClientInterfaceVersion();
long first = -1, best = -1;
bool hasComma = false;
size_t q = p;
while (q < len) {
while (q < len && (IsSpace(line[q]) || line[q] == ',')) {
if (line[q] == ',') hasComma = true;
++q;
}
long v = 0;
bool digit = false;
while (q < len && line[q] >= '0' && line[q] <= '9') {
v = v * 10 + (line[q] - '0');
++q;
digit = true;
}
if (digit) {
if (first < 0) first = v;
if (static_cast<uint32_t>(v) <= client && v > best) best = v;
} else if (q < len) {
++q; // skip a stray non-digit so the scan always advances
}
}
if (!hasComma || best < 0 || first == best)
return false; // single value / nothing at or below client / already first
out.append(line, prefixEnd);
out.push_back(' ');
out += std::to_string(best);
return true;
}
// True iff the game-type list names a game type this client is: always
// `vanilla`, and `turtle` (a ClassicAPI extension, like the `_Turtle.toc`
// flavor) on a Turtle client.
bool ListContainsGameType(const char *list, size_t listLen) {
return ListContains(list, listLen, "vanilla") ||
(Turtle::Detected() && ListContains(list, listLen, "turtle"));
}
// Evaluate a `[keyword args]` condition — the return is whether the line should
// load. An unrecognized keyword returns false so the caller drops the line (a
// condition we cannot confirm must not load — fail safe).
bool EvalCondition(const char *head, size_t headLen, const char *args,
size_t argsLen) {
if (EqCI(head, headLen, "AllowLoadGameType"))
return ListContainsGameType(args, argsLen);
if (EqCI(head, headLen, "ExcludeLoadGameType"))
return !ListContainsGameType(args, argsLen);
if (EqCI(head, headLen, "AllowLoadTextLocale"))
return ListContains(args, argsLen, Client());
if (EqCI(head, headLen, "AllowLoad"))
return ListContains(args, argsLen, "game"); // addon files: in-game only
return false;
}
// Rewrite one file-reference line into `out`: expand `[Variable]` tokens,
// evaluate and strip `[Condition]` directives. Returns true to KEEP the
// line (all conditions passed); on true `out` holds the cleaned,
// right-trimmed path.
bool ProcessFileLine(const char *line, size_t len, std::string &out) {
out.clear();
bool keep = true;
size_t i = 0;
while (i < len) {
const char c = line[i];
if (c != '[') {
out.push_back(c);
++i;
continue;
}
size_t close = i + 1;
while (close < len && line[close] != ']') ++close;
if (close >= len) { // unterminated '[' — copy the rest verbatim
out.append(line + i, len - i);
break;
}
const char *inner = line + i + 1;
const size_t innerLen = close - (i + 1);
size_t h = 0;
while (h < innerLen && !IsSpace(inner[h])) ++h; // [0,h) = head word
size_t a = h;
while (a < innerLen && IsSpace(inner[a])) ++a; // skip separating ws
const char *head = inner;
const size_t headLen = h;
const char *args = inner + a;
const size_t argsLen = innerLen - a;
if (argsLen == 0) {
// Single word: a variable to expand, else leave verbatim (an
// unknown token becomes a path the engine cannot open — the
// file just does not load).
const char *val = VariableValue(head, headLen);
if (val != nullptr) out.append(val);
else out.append(line + i, (close + 1) - i);
} else {
// Keyword + args: a condition. Strip it from the path (drop a
// space we already emitted before it so nothing dangles).
keep = keep && EvalCondition(head, headLen, args, argsLen);
if (!out.empty() && out.back() == ' ') out.pop_back();
}
i = close + 1;
}
while (!out.empty() && IsSpace(out.back())) out.pop_back();
return keep;
}
// Walk the whole TOC, preserving line terminators and any UTF-8 BOM.
// `#` comment and `##` metadata lines pass through verbatim; only file
// reference lines are rewritten. A gated-out line becomes a `#` comment
// so the load loop skips it (and a dumped TOC shows why it was dropped).
void RebuildToc(const char *src, size_t srcLen, std::string &out) {
out.clear();
out.reserve(srcLen + 32);
size_t i = 0;
if (srcLen >= 3 && static_cast<uint8_t>(src[0]) == 0xEF &&
static_cast<uint8_t>(src[1]) == 0xBB &&
static_cast<uint8_t>(src[2]) == 0xBF) {
out.append(src, 3);
i = 3;
}
std::string lineOut;
while (i < srcLen) {
const size_t lineStart = i;
while (i < srcLen && src[i] != '\r' && src[i] != '\n') ++i;
const char *line = src + lineStart;
const size_t len = i - lineStart;
const size_t termStart = i;
if (i < srcLen && src[i] == '\r') ++i;
if (i < srcLen && src[i] == '\n') ++i;
size_t s = 0;
while (s < len && IsSpace(line[s])) ++s;
if (s >= len) {
out.append(line, len); // blank
} else if (line[s] == '#') {
// Comment / `##` metadata — verbatim, except a multi-flavor
// `## Interface:` list that hides the client version.
if (!TryRewriteInterfaceLine(line, len, out))
out.append(line, len);
} else if (ProcessFileLine(line, len, lineOut)) {
out.append(lineOut);
} else {
out.push_back('#'); // gated out — comment it so the loader skips it
out.append(line, len);
}
out.append(src + termStart, i - termStart);
}
}
// True iff `path` is an addon `.toc` read (…\AddOns\…\*.toc). Gates the
// rewrite off every non-TOC read (a `.lua` with a `t[1]` subscript would
// otherwise be mangled) and off non-addon TOCs (FrameXML.toc, etc.).
bool IsAddonToc(const char *path) {
const size_t len = std::strlen(path);
if (len < 4) return false;
if (!(path[len - 4] == '.' && Lower(path[len - 3]) == 't' &&
Lower(path[len - 2]) == 'o' && Lower(path[len - 1]) == 'c'))
return false;
for (size_t i = 0; i + 8 <= len; ++i)
if (EqCI(path + i, 8, "\\addons\\")) return true;
return false;
}
} // namespace
void Transform(const char *path, void **outBuf, size_t *outSize) {
if (path == nullptr || outBuf == nullptr || *outBuf == nullptr) return;
if (!IsAddonToc(path)) return;
const char *content = static_cast<const char *>(*outBuf);
const size_t size = (outSize != nullptr && *outSize != 0)
? *outSize
: std::strlen(content);
if (size == 0) return;
// Fast path: no '[' (directives) and no ',' (a possible `## Interface:`
// list) means nothing to do — leave the engine buffer alone.
if (std::memchr(content, '[', size) == nullptr &&
std::memchr(content, ',', size) == nullptr)
return;
std::string rebuilt;
RebuildToc(content, size, rebuilt);
if (rebuilt.size() == size &&
std::memcmp(rebuilt.data(), content, size) == 0)
return; // brackets/commas were only in unaffected lines — nothing changed
auto SMemAlloc = reinterpret_cast<SMemAllocFn>(Offsets::FUN_STORM_SMEM_ALLOC);
auto SMemFree = reinterpret_cast<SMemFreeFn>(Offsets::FUN_STORM_SMEM_FREE);
const size_t newLen = rebuilt.size();
void *buf = SMemAlloc(newLen + 1, __FILE__, __LINE__, 0); // +1 NUL (extraBytes=1)
if (buf == nullptr) return; // OOM — keep the original
std::memcpy(buf, rebuilt.data(), newLen);
static_cast<char *>(buf)[newLen] = '\0';
SMemFree(*outBuf, __FILE__, __LINE__, 0);
*outBuf = buf;
if (outSize != nullptr) *outSize = newLen;
}
} // namespace AddOns::TocRewrite
+88
View File
@@ -0,0 +1,88 @@
// 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
#include <cstddef>
namespace AddOns::TocRewrite {
// Modern-client per-line TOC directives, backported.
//
// A single-TOC multi-flavor addon gates individual file lines with
// conditions and expands path variables:
//
// [Family]\Init.lua # -> Classic\Init.lua
// Vanilla.lua [AllowLoadGameType vanilla]
// Mainline.lua [AllowLoadGameType mainline] # dropped on this client
// Localization\[TextLocale].lua # -> Localization\enUS.lua
// deDE.lua [AllowLoadTextLocale deDE]
//
// Vanilla 1.12's TOC parsers never understood any of this. The scan
// parser (FUN_0051C9B0) reads only `##` metadata; the load pass
// (FUN_006edb90) hands each non-`#` line to the per-file loader verbatim,
// where the trailing ` [...]` breaks the extension check and the file
// silently never loads. `[Variable]` tokens likewise become part of a
// path that does not exist.
//
// This closes the gap at the FUN_FILE_READ layer (alongside FlavorToc /
// Embedded): after an addon TOC is read, rewrite its file-reference lines
// so the engine's own load loop sees clean paths. `##` metadata and `#`
// comment lines are copied verbatim, with ONE exception (`## Interface:`,
// below); metadata-line conditions, added in retail 12.0.7, are out of
// scope. What the tokens resolve to on this 1.12 client:
//
// [AllowLoadGameType ...] keep the line iff the list names a game type
// of this client
// [ExcludeLoadGameType ...] keep the line iff the list names none
// This client is the `vanilla` game type, and
// also `turtle` (a ClassicAPI extension, like
// the `_Turtle.toc` flavor) when
// Turtle::Detected(). So
// `[ExcludeLoadGameType turtle]` loads a line
// everywhere but Turtle.
// [AllowLoadTextLocale ...] keep the line iff the list contains the
// client locale (GetLocale() code, e.g. enUS)
// [AllowLoad ...] addon files only load in-game, so `game`
// keeps and `glue` drops
// [Family] -> Classic
// [Game] -> Vanilla
// [TextLocale] -> the client locale code
//
// All conditions on a line must pass for it to load (AND). An unknown
// `[keyword args]` condition fails safe (drops the line); an unknown
// single-word `[Token]` is left verbatim (the engine then fails to find
// that path, so the file does not load).
//
// Multi-flavor `## Interface:` list. Retail lets a TOC list several
// interface versions (`## Interface: 120100, 50504, 11200`). Vanilla's
// parser is a plain atoi that reads only the FIRST number, so it never
// sees a later 11200 and marks the addon out of date. The line is rewritten
// to retail's pick — the closest value at or below the client version
// (FUN_ADDON_CLIENT_INTERFACE_VERSION, 11200) — when that is not already
// first. If 11200 is listed the pick is 11200 and the addon loads; if not,
// the addon stays out of date exactly as before, but the stored value
// (`GetAddOnInterfaceVersion`) matches retail. A list with nothing at or
// below the client version is left unchanged.
//
// Called from the FUN_FILE_READ hook after the read succeeds. Does
// nothing unless `path` is an addon `.toc` read AND its content contains a
// `[` (directives) or a `,` (a possible `## Interface:` list) — the
// fast-path bail keeps every unaffected TOC zero-copy, and a rebuild that
// changes nothing is discarded by a content compare. When it does rewrite,
// it allocates a fresh Storm buffer, frees the original, and updates
// `*outBuf` / `*outSize` — the caller frees the replacement exactly as it
// would the engine's own read buffer.
void Transform(const char *path, void **outBuf, size_t *outSize);
} // namespace AddOns::TocRewrite
+915
View File
@@ -0,0 +1,915 @@
// 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/>.
// 4.3.4's CSimpleAnim and its Alpha, Translation, Scale and Rotation
// subclasses (wowdecomp15595 CSimpleAnim.cpp, CSimple*Anim.cpp and their
// _Scripts.cpp), on Animation::Object, and the group's CreateAnimation.
// Path and its control points are in Path.cpp.
//
// Later clients' additions, on the same objects:
// - the target setters (SetTarget, SetTargetName, SetTargetKey,
// SetChildKey, SetTargetParent, GetTarget);
// - Alpha's fromAlpha / toAlpha. Blizzard's own code starts a fade from
// the region's current alpha with SetFromAlpha(region:GetAlpha()), and
// its XML fades in with toAlpha="1" alone, so the alpha is absolute (the
// target's alpha becomes from + (to - from) x progress) and an unset
// fromAlpha is 0. SetChange goes back to 4.3.4's relative change;
// - Scale's SetScaleFrom / SetScaleTo. 4.3.4's scale is the case from = 1,
// and SetScale sets the end, so its old results do not change.
#include "animation/Classes.h"
#include "animation/Region.h"
#include "animation/Xml.h"
#include "Game.h"
#include "Offsets.h"
#include "baselib/Ascii.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <string>
namespace Animation {
namespace {
const char *const kAnimScripts[] = {"onload", "onplay", "onpause", "onstop", "onfinished", "onupdate"};
Class &ClassOf(AnimKind kind) {
switch (kind) {
case KIND_ALPHA: return Anim::s_alphaClass;
case KIND_TRANSLATION: return Anim::s_translationClass;
case KIND_SCALE: return Anim::s_scaleClass;
case KIND_ROTATION: return Anim::s_rotationClass;
case KIND_PATH: return Anim::s_pathClass;
default: return Anim::s_class;
}
}
} // namespace
AnimKind Anim::KindOf(const char *typeName) {
if (typeName == nullptr || *typeName == '\0')
return KIND_ANIMATION;
if (Ascii::EqualCI(typeName, "Alpha"))
return KIND_ALPHA;
if (Ascii::EqualCI(typeName, "Translation"))
return KIND_TRANSLATION;
if (Ascii::EqualCI(typeName, "Scale"))
return KIND_SCALE;
if (Ascii::EqualCI(typeName, "Rotation"))
return KIND_ROTATION;
if (Ascii::EqualCI(typeName, "Path"))
return KIND_PATH;
return KIND_ANIMATION;
}
// ---- Construction ---------------------------------------------------------------
// 4.3.4's constructor links the animation into the group's list; it joins an
// order list only once it has an order (NotifyAnimAdded, SortAnimations).
Anim::Anim(Group *group, AnimKind kind, const char *name) : Object(ClassOf(kind), group, name), kind(kind) {
if (group != nullptr)
group->animations.push_back(this);
}
// ~CSimplePathAnim: a path's control points go with it.
Anim::~Anim() {
for (ControlPoint *point : controlPoints)
delete point;
}
// ---- Playback --------------------------------------------------------------------
void Anim::ResolveTarget() {
if (!targetKey.empty())
target = Region::FindRegionByKey(this, targetKey.c_str());
else if (targetName[0] != '\0')
target = Region::FindRegionByName(targetName);
}
bool Anim::Play() {
ResolveTarget();
if (playState != 1) {
playState = 1;
RunScript(A_ONPLAY, 0);
}
return true;
}
void Anim::Pause() {
GetGroup()->Pause();
if (playState == 1) {
playState = 2;
RunScript(A_ONPAUSE, 0);
}
}
void Anim::Stop(bool requested) {
if (playState == 0)
return;
loopState = STATE_NONE;
playState = 0;
elapsed = 0.0f;
progressWithDelay = 0.0f;
progress = 0.0f;
if (HasScript(A_ONSTOP)) {
Game::Lua::PushBool(Game::Lua::State(), requested);
RunScript(A_ONSTOP, 1);
}
}
bool Anim::IsDelaying() const {
if (progressWithDelay <= 0.0f || progressWithDelay >= 1.0f)
return false;
const float total = endDelay + duration + startDelay;
if (std::fabs(total) < 0.00000023841858f)
return false;
if (loopState == STATE_REVERSE) {
if (endDelay > elapsed)
return true;
if (endDelay + duration > elapsed)
return false;
} else {
if (startDelay > elapsed)
return true;
if (duration + startDelay > elapsed)
return false;
}
return total > elapsed;
}
float Anim::UpdateProgress(float elapsedSec) {
const float prevElapsed = elapsed;
elapsed += elapsedSec;
const float total = orderPadding + startDelay + endDelay + duration;
float now;
if (total > elapsed) {
now = elapsed;
progressWithDelay = now / total;
if (progressWithDelay > 1.0f)
progressWithDelay = 1.0f;
if (std::fabs(duration) < 0.00000023841858f) {
progress = 1.0f;
} else {
frameElapsed += elapsedSec;
if ((GetGroup()->flags & GROUP_IGNORE_THROTTLE) || frameElapsed >= g_frameInterval) {
const float delay = loopState == STATE_REVERSE ? orderPadding + endDelay : startDelay;
progress = (now - delay) / duration;
if (progress < 0.0f)
progress = 0.0f;
else if (progress >= 1.0f)
progress = 1.0f;
frameElapsed = 0.0f;
}
}
} else {
now = total;
progressWithDelay = 1.0f;
progress = 1.0f;
}
float p = loopState == STATE_REVERSE ? 1.0f - progress : progress;
if (hasSmoother) {
// CSimpleAnimSCurveSmoother::GetSmoothProgress.
if (std::fabs(smoothIn) >= 0.001f && std::fabs(smoothOut) >= 0.001f)
p = 0.5f - std::cos(p * 3.1415927f) * 0.5f;
else if (std::fabs(smoothIn) >= 0.001f)
p = 1.0f - std::cos(p * 1.5707964f);
else if (std::fabs(smoothOut) >= 0.001f)
p = std::cos((p + 1.0f) * 1.5707964f) * -1.0f;
}
smoothProgress = p;
return now - prevElapsed;
}
bool Anim::OnUpdate(float elapsedSec, float &consumed) {
consumed = 0.0f;
if (progressWithDelay >= 1.0f) {
Apply(smoothProgress);
return true;
}
if (playState == 0)
return true;
if (playState == 2) {
Apply(smoothProgress);
return false;
}
consumed = UpdateProgress(elapsedSec);
if (HasScript(A_ONUPDATE)) {
Game::Lua::PushNumber(Game::Lua::State(), elapsedSec);
RunScript(A_ONUPDATE, 1);
}
Apply(smoothProgress);
if (progressWithDelay < 1.0f)
return false;
RunScript(A_ONFINISHED, 0);
return true;
}
void Anim::Apply(float p) {
void *region = GetRegionParent();
if (region == nullptr)
return;
switch (kind) {
case KIND_ALPHA:
if (alphaFromTo)
Region::SetAnimAlpha(region, target, static_cast<uint8_t>((fromAlpha + (toAlpha - fromAlpha) * p) * 255.0f));
else
Region::AddAnimAlpha(region, target, static_cast<int16_t>(change * p));
break;
case KIND_TRANSLATION:
Region::AddAnimTranslation(region, target, offsetX * p, offsetY * p);
break;
case KIND_SCALE: {
// AddAnimScale takes the share of the way to the origin, 1 - scale.
const float x = scaleFromX + (scaleToX - scaleFromX) * p;
const float y = scaleFromY + (scaleToY - scaleFromY) * p;
Region::AddAnimScale(region, target, originPoint, originX, originY, 1.0f - x, 1.0f - y);
break;
}
case KIND_ROTATION:
Region::AddAnimRotation(region, target, originPoint, originX, originY, radians * p);
break;
case KIND_PATH:
ApplyPath(p);
break;
default:
break;
}
}
// ---- Settings ----------------------------------------------------------------------
void Anim::SetStartDelay(float delay, bool notify) {
startDelay = delay < 0.0f ? 0.0f : delay;
if (notify && parent != nullptr)
GetGroup()->ComputeDuration();
}
void Anim::SetEndDelay(float delay, bool notify) {
endDelay = delay < 0.0f ? 0.0f : delay;
if (notify && parent != nullptr)
GetGroup()->ComputeDuration();
}
void Anim::SetDuration(float value, bool notify) {
duration = value;
if (notify && parent != nullptr)
GetGroup()->ComputeDuration();
}
void Anim::SetOrder(int value, bool notify, bool wrap) {
const int oldOrder = order;
if (wrap)
order = value < 0 || value > 99 ? 0 : value;
else
order = value < 0 ? 0 : (value > 99 ? 99 : value);
// 4.3.4 compares the old order with the argument, not the clamped value.
if (notify && parent != nullptr && oldOrder != value)
GetGroup()->NotifyOrderChanged(this, oldOrder);
}
void Anim::SetSmoothing(float in, float out) {
if ((in > 0.0f && in <= 1.0f) || (out > 0.0f && out <= 1.0f)) {
hasSmoother = true;
smoothIn = in < 0.0f ? 0.0f : (in < 1.0f ? in : 1.0f);
smoothOut = out < 0.0f ? 0.0f : (out < 1.0f ? out : 1.0f);
}
}
bool Anim::GetSmoothing(float &in, float &out) const {
in = hasSmoother ? smoothIn : 0.0f;
out = hasSmoother ? smoothOut : 0.0f;
return hasSmoother;
}
bool Anim::ChangeParent(Group *group) {
if (group == nullptr || parent == group)
return false;
GetGroup()->NotifyAnimRemoved(this);
parent = group;
group->NotifyAnimAdded(this);
return true;
}
void Anim::PostLoadXML() {
flags &= ~1;
if (kind == KIND_PATH) {
// CSimplePathAnim::PostLoadXML: the points' orders and positions.
BuildSpline();
UpdateControlPointPositions();
}
RunScript(A_ONLOAD, 0);
}
// ---- Lua methods ----------------------------------------------------------------------
namespace {
using StringToPoint_t = int(__fastcall *)(const char *name, int *point);
using PointToString_t = const char *(__fastcall *)(int point);
Anim *Self(void *L) { return static_cast<Anim *>(Resolve(L, 1, Anim::s_class)); }
Anim *SelfOf(void *L, Class &cls) { return static_cast<Anim *>(Resolve(L, 1, cls)); }
// Usage error when argument `idx` isn't a number; the number otherwise.
bool NumberArg(void *L, int idx, Anim *anim, const char *usage) {
if (Game::Lua::IsNumber(L, idx))
return true;
Game::Lua::Error(L, usage, anim->DisplayName());
return false;
}
int __fastcall Script_Play(void *L) {
if (Anim *a = Self(L))
a->Play();
return 0;
}
int __fastcall Script_Pause(void *L) {
if (Anim *a = Self(L))
a->Pause();
return 0;
}
int __fastcall Script_Stop(void *L) {
if (Anim *a = Self(L))
a->Stop(true);
return 0;
}
template <typename Fn> int PushBoolOf(void *L, Fn fn) {
Anim *a = Self(L);
if (a == nullptr)
return 0;
Game::Lua::PushBool(L, fn(a));
return 1;
}
template <typename Fn> int PushNumberOf(void *L, Fn fn) {
Anim *a = Self(L);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, fn(a));
return 1;
}
int __fastcall Script_IsDone(void *L) { return PushBoolOf(L, [](Anim *a) { return a->progressWithDelay >= 1.0f; }); }
int __fastcall Script_IsPlaying(void *L) { return PushBoolOf(L, [](Anim *a) { return a->playState == 1; }); }
int __fastcall Script_IsPaused(void *L) { return PushBoolOf(L, [](Anim *a) { return a->playState == 2; }); }
int __fastcall Script_IsStopped(void *L) { return PushBoolOf(L, [](Anim *a) { return a->playState == 0; }); }
int __fastcall Script_IsDelaying(void *L) { return PushBoolOf(L, [](Anim *a) { return a->IsDelaying(); }); }
int __fastcall Script_GetElapsed(void *L) { return PushNumberOf(L, [](Anim *a) { return a->elapsed; }); }
int __fastcall Script_GetStartDelay(void *L) { return PushNumberOf(L, [](Anim *a) { return a->startDelay; }); }
int __fastcall Script_GetEndDelay(void *L) { return PushNumberOf(L, [](Anim *a) { return a->endDelay; }); }
int __fastcall Script_GetDuration(void *L) { return PushNumberOf(L, [](Anim *a) { return a->duration; }); }
int __fastcall Script_GetSmoothProgress(void *L) {
return PushNumberOf(L, [](Anim *a) { return a->smoothProgress; });
}
int __fastcall Script_GetProgress(void *L) { return PushNumberOf(L, [](Anim *a) { return a->progress; }); }
int __fastcall Script_GetProgressWithDelay(void *L) {
return PushNumberOf(L, [](Anim *a) { return a->progressWithDelay; });
}
int __fastcall Script_GetOrder(void *L) {
return PushNumberOf(L, [](Anim *a) { return static_cast<double>(a->order + 1); });
}
int __fastcall Script_SetStartDelay(void *L) {
Anim *a = Self(L);
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetStartDelay(delaySec)"))
a->SetStartDelay(static_cast<float>(Game::Lua::ToNumber(L, 2)), true);
return 0;
}
int __fastcall Script_SetEndDelay(void *L) {
Anim *a = Self(L);
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetEndDelay(delaySec)"))
a->SetEndDelay(static_cast<float>(Game::Lua::ToNumber(L, 2)), true);
return 0;
}
int __fastcall Script_SetDuration(void *L) {
Anim *a = Self(L);
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetDuration(durationSec)"))
a->SetDuration(static_cast<float>(Game::Lua::ToNumber(L, 2)), true);
return 0;
}
int __fastcall Script_SetSmoothProgress(void *L) {
Anim *a = Self(L);
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetSmoothProgress(smoothProgress)"))
a->smoothProgress = static_cast<float>(Game::Lua::ToNumber(L, 2));
return 0;
}
int __fastcall Script_SetOrder(void *L) {
Anim *a = Self(L);
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetOrder(order)"))
a->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 2)) - 1, true, false);
return 0;
}
int __fastcall Script_SetSmoothing(void *L) {
Anim *a = Self(L);
if (a == nullptr)
return 0;
if (!Game::Lua::IsString(L, 2)) {
Game::Lua::Error(L, "Usage: %s:SetSmoothing(\"smoothingType\")", a->DisplayName());
return 0;
}
float in, out;
if (StringToSmoothWeights(Game::Lua::ToString(L, 2), in, out)) {
a->SetSmoothing(in, out);
return 0;
}
Game::Lua::Error(L, "%s:SetSmoothing(): Unknown smoothing type specified", a->DisplayName());
return 0;
}
int __fastcall Script_GetSmoothing(void *L) {
Anim *a = Self(L);
if (a == nullptr)
return 0;
float in, out;
a->GetSmoothing(in, out);
Game::Lua::PushString(L, SmoothWeightsToString(in, out));
return 1;
}
int __fastcall Script_SetParent(void *L) {
Anim *a = Self(L);
if (a == nullptr)
return 0;
if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_NIL) {
Game::Lua::Error(L, "%s:SetParent(): Cannot set a 'nil' parent for animations", a->DisplayName());
return 0;
}
Group *group = nullptr;
if (Game::Lua::IsString(L, 2)) {
// CScriptObject::GetScriptObjectByName(name, AnimationGroup).
Game::Lua::PushString(L, Game::Lua::ToString(L, 2));
Game::Lua::RawGet(L, Game::Lua::GLOBALS_INDEX);
void *object = Game::Lua::Type(L, -1) == Game::Lua::TYPE_TABLE ? Game::Lua::ResolveObject(L, -1) : nullptr;
Game::Lua::SetTop(L, -2);
if (object != nullptr && IsOurs(object) &&
Game::Lua::IsA(object, reinterpret_cast<uintptr_t>(&Group::s_class.typeId)))
group = static_cast<Group *>(object);
} else if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_TABLE) {
void *object = Game::Lua::ResolveObject(L, 2);
if (object == nullptr) {
Game::Lua::Error(L, "%s:SetParent(): Couldn't find 'this' in parent object", a->DisplayName());
return 0;
}
if (!IsOurs(object) || !Game::Lua::IsA(object, reinterpret_cast<uintptr_t>(&Group::s_class.typeId))) {
Game::Lua::Error(L, "%s:SetParent(): Wrong parent object type, expected AnimationGroup", a->DisplayName());
return 0;
}
group = static_cast<Group *>(object);
}
if (group == nullptr) {
Game::Lua::Error(L, "%s:SetParent(): Couldn't find animation group named '%s'", a->DisplayName(),
Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : "");
return 0;
}
const int oldOrder = a->order;
if (Game::Lua::IsNumber(L, 3)) {
a->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 3)) - 1, false, false);
} else {
int value = a->order;
if (value == -1)
value = group->GetMaxAnimOrder() + 1;
a->SetOrder(value, false, true);
}
if (!a->ChangeParent(group) && oldOrder != a->order)
group->NotifyOrderChanged(a, oldOrder);
return 0;
}
int __fastcall Script_GetRegionParent(void *L) {
Anim *a = Self(L);
if (a == nullptr)
return 0;
void *region = a->GetRegionParent();
if (region != nullptr)
Game::Lua::PushObject(L, region);
else
Game::Lua::PushNil(L);
return 1;
}
// ---- Target (later clients) ----
//
// An animation with no target animates its group's region. Each setter
// replaces the others' target and returns whether it names a region now;
// a name or key is looked up again on Play, as 4.3.4 looks up `target`.
int PushTargetFound(void *L, const Anim *a) {
Game::Lua::PushBool(L, a->target != nullptr);
return 1;
}
void *RegionArg(void *L, int idx) {
if (Game::Lua::Type(L, idx) != Game::Lua::TYPE_TABLE)
return nullptr;
void *object = Game::Lua::ResolveObject(L, idx);
if (object == nullptr || IsOurs(object) || !Game::Lua::IsA(object, Offsets::VAR_REGION_LUA_TYPE_ID))
return nullptr;
return object;
}
const char *StringArg(void *L, Anim *a, const char *usage) {
if (Game::Lua::IsString(L, 2))
return Game::Lua::ToString(L, 2);
Game::Lua::Error(L, usage, a->DisplayName());
return nullptr;
}
int __fastcall Script_SetTarget(void *L) {
Anim *a = Self(L);
if (a == nullptr)
return 0;
void *region = RegionArg(L, 2);
if (region == nullptr) {
Game::Lua::PushBool(L, false);
return 1;
}
a->targetName[0] = '\0';
a->targetKey.clear();
a->target = region;
return PushTargetFound(L, a);
}
int __fastcall Script_SetTargetName(void *L) {
Anim *a = Self(L);
const char *name = a != nullptr ? StringArg(L, a, "Usage: %s:SetTargetName(name)") : nullptr;
if (name == nullptr)
return 0;
std::snprintf(a->targetName, sizeof(a->targetName), "%s", CreateName(name, a).c_str());
a->targetKey.clear();
a->target = nullptr;
a->ResolveTarget();
return PushTargetFound(L, a);
}
int __fastcall Script_SetTargetKey(void *L) {
Anim *a = Self(L);
const char *key = a != nullptr ? StringArg(L, a, "Usage: %s:SetTargetKey(key)") : nullptr;
if (key == nullptr)
return 0;
a->targetName[0] = '\0';
a->targetKey = key;
a->target = nullptr;
a->ResolveTarget();
return PushTargetFound(L, a);
}
int __fastcall Script_SetChildKey(void *L) {
Anim *a = Self(L);
const char *key = a != nullptr ? StringArg(L, a, "Usage: %s:SetChildKey(childKey)") : nullptr;
if (key == nullptr)
return 0;
a->targetName[0] = '\0';
a->targetKey = std::string("$parent.$parent.") + key;
a->target = nullptr;
a->ResolveTarget();
return PushTargetFound(L, a);
}
int __fastcall Script_SetTargetParent(void *L) {
Anim *a = Self(L);
if (a == nullptr)
return 0;
a->targetName[0] = '\0';
a->targetKey.clear();
a->target = a->GetRegionParent();
return PushTargetFound(L, a);
}
int __fastcall Script_GetTarget(void *L) {
Anim *a = Self(L);
if (a == nullptr)
return 0;
void *region = a->target != nullptr ? a->target : a->GetRegionParent();
if (region != nullptr)
Game::Lua::PushObject(L, region);
else
Game::Lua::PushNil(L);
return 1;
}
// ---- Alpha ----
int __fastcall Script_SetChange(void *L) {
Anim *a = SelfOf(L, Anim::s_alphaClass);
if (a == nullptr || !NumberArg(L, 2, a, "Usage: %s:SetChange(change)"))
return 0;
// CSimpleAlphaAnim::SetChange.
const float change = static_cast<float>(Game::Lua::ToNumber(L, 2));
const float value = change < -1.0f ? -1.0f : (change >= 1.0f ? 1.0f : change);
a->change = static_cast<int16_t>(value * 255.0f);
a->alphaFromTo = false;
return 0;
}
int __fastcall Script_GetChange(void *L) {
Anim *a = SelfOf(L, Anim::s_alphaClass);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, a->change * (1.0f / 255.0f));
return 1;
}
// Later clients' absolute alpha. Setting either end turns it on; the other
// end keeps its value, 0 until set.
void SetAlphaEnd(void *L, float Anim::*end, const char *usage) {
Anim *a = SelfOf(L, Anim::s_alphaClass);
if (a == nullptr || !NumberArg(L, 2, a, usage))
return;
const float value = static_cast<float>(Game::Lua::ToNumber(L, 2));
a->*end = value < 0.0f ? 0.0f : (value > 1.0f ? 1.0f : value);
a->alphaFromTo = true;
}
int __fastcall Script_SetFromAlpha(void *L) {
SetAlphaEnd(L, &Anim::fromAlpha, "Usage: %s:SetFromAlpha(alpha)");
return 0;
}
int __fastcall Script_SetToAlpha(void *L) {
SetAlphaEnd(L, &Anim::toAlpha, "Usage: %s:SetToAlpha(alpha)");
return 0;
}
int __fastcall Script_GetFromAlpha(void *L) {
Anim *a = SelfOf(L, Anim::s_alphaClass);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, a->fromAlpha);
return 1;
}
int __fastcall Script_GetToAlpha(void *L) {
Anim *a = SelfOf(L, Anim::s_alphaClass);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, a->toAlpha);
return 1;
}
// ---- Translation ----
int __fastcall Script_SetOffset(void *L) {
Anim *a = SelfOf(L, Anim::s_translationClass);
if (a == nullptr)
return 0;
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
Game::Lua::Error(L, "Usage: %s:SetOffset(x, y)", a->DisplayName());
return 0;
}
const float x = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 2)));
const float y = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 3)));
// CSimpleTranslationAnim::SetOffset: a near-zero offset is zero.
if (x * x + y * y <= 0.00000023841858f) {
a->offsetX = 0.0f;
a->offsetY = 0.0f;
} else {
a->offsetX = x;
a->offsetY = y;
}
return 0;
}
int __fastcall Script_GetOffset(void *L) {
Anim *a = SelfOf(L, Anim::s_translationClass);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, Game::InternalToPixel(a->offsetX));
Game::Lua::PushNumber(L, Game::InternalToPixel(a->offsetY));
return 2;
}
// ---- Scale and Rotation origin (ReadOrigin) ----
Anim *OriginSelf(void *L) {
Anim *a = static_cast<Anim *>(Resolve(L, 1, Anim::s_class));
if (a != nullptr && a->kind != KIND_SCALE && a->kind != KIND_ROTATION) {
// The type test of 4.3.4's Scale / Rotation SetOrigin.
Game::Lua::Error(L, "Wrong object type for member function");
return nullptr;
}
return a;
}
int __fastcall Script_SetOrigin(void *L) {
Anim *a = OriginSelf(L);
if (a == nullptr)
return 0;
if (!Game::Lua::IsString(L, 2) || !Game::Lua::IsNumber(L, 3) || !Game::Lua::IsNumber(L, 4)) {
Game::Lua::Error(L, "Usage: %s:SetOrigin(point, offsetX, offsetY)", a->DisplayName());
return 0;
}
int point = Offsets::FRAMEPOINT_CENTER;
if (!reinterpret_cast<StringToPoint_t>(Offsets::FUN_STRING_TO_FRAME_POINT)(Game::Lua::ToString(L, 2), &point))
point = Offsets::FRAMEPOINT_CENTER;
a->originPoint = point;
a->originX = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 3)));
a->originY = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 4)));
return 0;
}
// 4.3.4 pushes the stored offsets as they are, in layout units.
int __fastcall Script_GetOrigin(void *L) {
Anim *a = OriginSelf(L);
if (a == nullptr)
return 0;
Game::Lua::PushString(L, reinterpret_cast<PointToString_t>(Offsets::FUN_FRAME_POINT_TO_STRING)(a->originPoint));
Game::Lua::PushNumber(L, a->originX);
Game::Lua::PushNumber(L, a->originY);
return 3;
}
// ---- Scale ----
int __fastcall Script_SetScale(void *L) {
Anim *a = SelfOf(L, Anim::s_scaleClass);
if (a == nullptr)
return 0;
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
Game::Lua::Error(L, "Usage: %s:SetScale(x, y)", a->DisplayName());
return 0;
}
// CSimpleScaleAnim::SetScale: the scale it ends on.
const float x = static_cast<float>(Game::Lua::ToNumber(L, 2));
const float y = static_cast<float>(Game::Lua::ToNumber(L, 3));
a->scaleToX = x >= 0.001f ? x : 0.001f;
a->scaleToY = y >= 0.001f ? y : 0.001f;
return 0;
}
int __fastcall Script_GetScale(void *L) {
Anim *a = SelfOf(L, Anim::s_scaleClass);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, a->scaleToX);
Game::Lua::PushNumber(L, a->scaleToY);
return 2;
}
// Later clients' SetScaleFrom / SetScaleTo: the scale the animation starts
// and ends on, as given.
void SetScaleEnd(void *L, float Anim::*x, float Anim::*y, const char *usage) {
Anim *a = SelfOf(L, Anim::s_scaleClass);
if (a == nullptr)
return;
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
Game::Lua::Error(L, usage, a->DisplayName());
return;
}
a->*x = static_cast<float>(Game::Lua::ToNumber(L, 2));
a->*y = static_cast<float>(Game::Lua::ToNumber(L, 3));
}
int __fastcall Script_SetScaleFrom(void *L) {
SetScaleEnd(L, &Anim::scaleFromX, &Anim::scaleFromY, "Usage: %s:SetScaleFrom(x, y)");
return 0;
}
int __fastcall Script_SetScaleTo(void *L) {
SetScaleEnd(L, &Anim::scaleToX, &Anim::scaleToY, "Usage: %s:SetScaleTo(x, y)");
return 0;
}
int __fastcall Script_GetScaleFrom(void *L) {
Anim *a = SelfOf(L, Anim::s_scaleClass);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, a->scaleFromX);
Game::Lua::PushNumber(L, a->scaleFromY);
return 2;
}
int __fastcall Script_GetScaleTo(void *L) {
Anim *a = SelfOf(L, Anim::s_scaleClass);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, a->scaleToX);
Game::Lua::PushNumber(L, a->scaleToY);
return 2;
}
// ---- Rotation ----
int __fastcall Script_SetDegrees(void *L) {
Anim *a = SelfOf(L, Anim::s_rotationClass);
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetDegrees(degrees)"))
a->radians = static_cast<float>(Game::Lua::ToNumber(L, 2) * 0.017453292f);
return 0;
}
int __fastcall Script_GetDegrees(void *L) {
Anim *a = SelfOf(L, Anim::s_rotationClass);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, a->radians * 57.29578f);
return 1;
}
int __fastcall Script_SetRadians(void *L) {
Anim *a = SelfOf(L, Anim::s_rotationClass);
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetRadians(radians)"))
a->radians = static_cast<float>(Game::Lua::ToNumber(L, 2));
return 0;
}
int __fastcall Script_GetRadians(void *L) {
Anim *a = SelfOf(L, Anim::s_rotationClass);
if (a == nullptr)
return 0;
Game::Lua::PushNumber(L, a->radians);
return 1;
}
const Game::Lua::FrameMethodEntry kAnimMethods[] = {
{"GetObjectType", &Script_GetObjectType},
{"IsObjectType", &Script_IsObjectType},
{"GetName", &Script_GetName},
{"GetParent", &Script_GetParent},
{"Play", &Script_Play},
{"Pause", &Script_Pause},
{"Stop", &Script_Stop},
{"IsDone", &Script_IsDone},
{"IsPlaying", &Script_IsPlaying},
{"IsPaused", &Script_IsPaused},
{"IsStopped", &Script_IsStopped},
{"IsDelaying", &Script_IsDelaying},
{"GetElapsed", &Script_GetElapsed},
{"SetStartDelay", &Script_SetStartDelay},
{"GetStartDelay", &Script_GetStartDelay},
{"SetEndDelay", &Script_SetEndDelay},
{"GetEndDelay", &Script_GetEndDelay},
{"SetDuration", &Script_SetDuration},
{"GetDuration", &Script_GetDuration},
{"GetSmoothProgress", &Script_GetSmoothProgress},
{"SetSmoothProgress", &Script_SetSmoothProgress},
{"GetProgress", &Script_GetProgress},
{"GetProgressWithDelay", &Script_GetProgressWithDelay},
{"SetOrder", &Script_SetOrder},
{"GetOrder", &Script_GetOrder},
{"SetSmoothing", &Script_SetSmoothing},
{"GetSmoothing", &Script_GetSmoothing},
{"SetParent", &Script_SetParent},
{"GetRegionParent", &Script_GetRegionParent},
{"SetTarget", &Script_SetTarget},
{"SetTargetName", &Script_SetTargetName},
{"SetTargetKey", &Script_SetTargetKey},
{"SetChildKey", &Script_SetChildKey},
{"SetTargetParent", &Script_SetTargetParent},
{"GetTarget", &Script_GetTarget},
{"HasScript", &Script_HasScript},
{"GetScript", &Script_GetScript},
{"SetScript", &Script_SetScript},
{"HookScript", &Script_HookScript},
};
const Game::Lua::FrameMethodEntry kAlphaMethods[] = {
{"SetChange", &Script_SetChange}, {"GetChange", &Script_GetChange},
{"SetFromAlpha", &Script_SetFromAlpha}, {"GetFromAlpha", &Script_GetFromAlpha},
{"SetToAlpha", &Script_SetToAlpha}, {"GetToAlpha", &Script_GetToAlpha},
};
const Game::Lua::FrameMethodEntry kTranslationMethods[] = {
{"SetOffset", &Script_SetOffset},
{"GetOffset", &Script_GetOffset},
};
const Game::Lua::FrameMethodEntry kScaleMethods[] = {
{"SetOrigin", &Script_SetOrigin}, {"GetOrigin", &Script_GetOrigin},
{"SetScale", &Script_SetScale}, {"GetScale", &Script_GetScale},
{"SetScaleFrom", &Script_SetScaleFrom}, {"GetScaleFrom", &Script_GetScaleFrom},
{"SetScaleTo", &Script_SetScaleTo}, {"GetScaleTo", &Script_GetScaleTo},
};
const Game::Lua::FrameMethodEntry kRotationMethods[] = {
{"SetOrigin", &Script_SetOrigin}, {"GetOrigin", &Script_GetOrigin}, {"SetDegrees", &Script_SetDegrees},
{"GetDegrees", &Script_GetDegrees}, {"SetRadians", &Script_SetRadians}, {"GetRadians", &Script_GetRadians},
};
template <size_t N> constexpr int Count(const Game::Lua::FrameMethodEntry (&)[N]) { return static_cast<int>(N); }
} // namespace
Class Anim::s_class{"Animation", nullptr, kAnimScripts, 6, kAnimMethods, Count(kAnimMethods), 0, 0};
Class Anim::s_alphaClass{"Alpha", &Anim::s_class, nullptr, 0, kAlphaMethods, Count(kAlphaMethods), 0, 0};
Class Anim::s_translationClass{"Translation", &Anim::s_class, nullptr, 0, kTranslationMethods,
Count(kTranslationMethods), 0, 0};
Class Anim::s_scaleClass{"Scale", &Anim::s_class, nullptr, 0, kScaleMethods, Count(kScaleMethods), 0, 0};
Class Anim::s_rotationClass{"Rotation", &Anim::s_class, nullptr, 0, kRotationMethods, Count(kRotationMethods), 0, 0};
// ---- AnimationGroup:CreateAnimation ------------------------------------------------------
int __fastcall Script_CreateAnimation(void *L) {
Group *group = static_cast<Group *>(Resolve(L, 1, Group::s_class));
if (group == nullptr)
return 0;
const char *type = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : "Animation";
const char *name = Game::Lua::IsString(L, 3) ? Game::Lua::ToString(L, 3) : nullptr;
const void *templateNode = nullptr;
if (Game::Lua::Type(L, 4) == Game::Lua::TYPE_STRING) {
const char *inherits = Game::Lua::ToString(L, 4);
templateNode = Xml::Template(inherits);
if (templateNode == nullptr) {
Game::Lua::Error(L, "%s:CreateAnimation(): Couldn't find inherited node \"%s\"", group->DisplayName(),
inherits);
return 0;
}
}
Anim *anim = new Anim(group, Anim::KindOf(type), name);
if (templateNode != nullptr) {
Xml::LoadAnim(anim, templateNode, nullptr);
anim->PostLoadXML();
}
if (anim->order == -1)
anim->SetOrder(group->GetMaxAnimOrder(), false, true);
group->NotifyAnimAdded(anim);
Push(L, anim);
return 1;
}
} // namespace Animation
+231
View File
@@ -0,0 +1,231 @@
// 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
#include "animation/Object.h"
#include <cstdint>
#include <string>
#include <vector>
// 4.3.4's CSimpleAnimGroup and CSimpleAnim (and its Alpha, Translation,
// Scale, Rotation and Path subclasses, and Path's CSimpleControlPoint), ported from the decompiled client
// (wowdecomp15595 Engine/Source/Frame/CSimpleAnimGroup.cpp, CSimpleAnim.cpp).
// Field and function names follow it; the comments say where 1.12 differs.
namespace Animation {
class Anim;
class ControlPoint;
enum LoopType { LOOP_NONE = 0, LOOP_REPEAT = 1, LOOP_BOUNCE = 2 };
enum LoopState { STATE_NONE = 0, STATE_FORWARD = 1, STATE_REVERSE = 2 };
// m_flags.
constexpr uint8_t GROUP_LOADING = 0x01;
constexpr uint8_t GROUP_PENDING_FINISH = 0x02;
constexpr uint8_t GROUP_PAUSED = 0x04;
constexpr uint8_t GROUP_STOPPING = 0x08;
constexpr uint8_t GROUP_IGNORE_THROTTLE = 0x10;
// Script indexes (Class::scriptNames order).
enum GroupScript { G_ONLOAD, G_ONPLAY, G_ONPAUSE, G_ONSTOP, G_ONFINISHED, G_ONUPDATE, G_ONLOOP };
enum AnimScript { A_ONLOAD, A_ONPLAY, A_ONPAUSE, A_ONSTOP, A_ONFINISHED, A_ONUPDATE };
class Group : public Object {
public:
static Class s_class;
// `region`: the 1.12 region (frame, texture or font string) it animates.
Group(void *region, const char *name);
~Group();
void *RegionObject() const { return parent; }
bool IsDone() const;
bool IsPlaying() const { return loopState != STATE_NONE && !(flags & GROUP_PAUSED); }
bool Play(bool reverse);
void Pause();
void Stop(bool requested);
void Finish();
bool OnUpdate(float elapsedSec);
int GetMaxAnimOrder() const;
bool HasAlphaAnim() const;
bool HasPositionAnim() const;
// Later clients' setToFinalAlpha: when the group finishes, its alpha
// animations' targets keep the alpha they end on (KeepAnimAlpha).
bool setToFinalAlpha = false;
void NotifyAnimAdded(Anim *anim);
void NotifyOrderChanged(Anim *anim, int oldOrder);
void NotifyAnimRemoved(Anim *anim);
void SortAnimations();
void ComputeDuration();
// XML: 4.3.4's PostLoadXML - every animation's, then sort, then OnLoad.
void PostLoadXML();
LoopType loopType = LOOP_NONE;
float duration = 0.0f;
float initialOffsetX = 0.0f, initialOffsetY = 0.0f; // layout units
LoopState loopState = STATE_NONE;
uint8_t flags = 0;
int currentOrder = -1;
float elapsed = 0.0f;
float progress = 0.0f;
std::vector<Anim *> animations; // m_animations, creation order
std::vector<std::vector<Anim *>> animLists; // m_animLists, by order
private:
std::vector<Anim *> *FindAnimList(int order);
std::vector<Anim *> *RegisterAnimList(int order);
bool AddAnimListNode(std::vector<Anim *> *list, Anim *anim);
bool RemoveAnimListNode(std::vector<Anim *> *list, Anim *anim);
bool AdvanceLoopState(float elapsedSec, float remaining);
bool DoGroupUpdateWork(float elapsedSec);
void ResetAnims();
};
enum AnimKind { KIND_ANIMATION, KIND_ALPHA, KIND_TRANSLATION, KIND_SCALE, KIND_ROTATION, KIND_PATH };
class Anim : public Object {
public:
static Class s_class; // "Animation"
static Class s_alphaClass; // "Alpha"
static Class s_translationClass; // "Translation"
static Class s_scaleClass; // "Scale"
static Class s_rotationClass; // "Rotation"
static Class s_pathClass; // "Path"
// The class of a CreateAnimation / XML type name; Animation for any
// other (4.3.4's CreateAnimation falls back to it).
static AnimKind KindOf(const char *typeName);
Anim(Group *group, AnimKind kind, const char *name);
~Anim();
Group *GetGroup() const { return static_cast<Group *>(parent); }
void *GetRegionParent() const { return parent != nullptr ? GetGroup()->RegionObject() : nullptr; }
bool Play();
void Pause();
void Stop(bool requested);
bool IsDelaying() const;
bool OnUpdate(float elapsedSec, float &consumed);
void Apply(float progress);
void SetStartDelay(float delay, bool notify);
void SetEndDelay(float delay, bool notify);
void SetDuration(float value, bool notify);
void SetOrder(int value, bool notify, bool wrap);
void SetSmoothing(float in, float out);
bool GetSmoothing(float &in, float &out) const;
bool ChangeParent(Group *group);
// XML: 4.3.4's PostLoadXML - OnLoad.
void PostLoadXML();
AnimKind kind;
float startDelay = 0.0f;
float endDelay = 0.0f;
float duration = 0.0f;
float frameElapsed = 0.0f;
float elapsed = 0.0f;
float progressWithDelay = 0.0f;
float progress = 0.0f;
float smoothProgress = 0.0f;
float orderPadding = 0.0f;
int order = -1;
uint8_t flags = 0;
int playState = 0; // 0 stopped, 1 playing, 2 paused
int loopState = STATE_NONE;
void *target = nullptr; // m_target, resolved from targetName or targetKey on Play
char targetName[128] = {}; // m_targetName
// Later clients' targetKey: a key path from the animation itself, where
// `$parent` steps to the group, then the group's region, then that
// region's parent. childKey "Icon" is "$parent.$parent.Icon".
std::string targetKey;
bool hasSmoother = false;
float smoothIn = 0.0f, smoothOut = 0.0f;
// Resolves targetName or targetKey into target, when either is set.
void ResolveTarget();
// Alpha: m_change, -255..255, or (alphaFromTo) the absolute fromAlpha /
// toAlpha, 0..1, that later clients replaced it with.
int16_t change = 0;
bool alphaFromTo = false;
float fromAlpha = 0.0f, toAlpha = 0.0f;
// Translation: the offset; Scale: the scale and origin; Rotation: the
// angle and origin. Offsets in layout units, as 4.3.4 keeps them.
float offsetX = 0.0f, offsetY = 0.0f;
// Scale: from and to, 1 by default. 4.3.4's m_scaleChange (1 - scale)
// is the case from = 1; later clients added the from scale.
float scaleFromX = 1.0f, scaleFromY = 1.0f;
float scaleToX = 1.0f, scaleToY = 1.0f;
float radians = 0.0f;
int originPoint = 4; // FRAMEPOINT_CENTER
float originX = 0.0f, originY = 0.0f;
// Path (CSimplePathAnim, Path.cpp): the control points it owns in link
// order (m_controlPoints), the same sorted by order (m_sortedPoints),
// and m_curve (false NONE, true SMOOTH).
std::vector<ControlPoint *> controlPoints;
std::vector<ControlPoint *> sortedPoints;
bool curve = false;
void BuildSpline();
void UpdateControlPointPositions();
int FindControlPoint(int order) const;
int GetMaxControlPointOrder() const;
int RegisterSplineControlPoint(ControlPoint *point);
void NotifyControlPointAdded(ControlPoint *point);
void NotifyControlPointRemoved(ControlPoint *point);
void NotifyControlPointOrderChanged(ControlPoint *point);
void ApplyPath(float progress);
private:
float UpdateProgress(float elapsedSec);
};
// CSimpleControlPoint: a point of a Path, an offset from where the region
// is, in layout units.
class ControlPoint : public Object {
public:
static Class s_class; // "ControlPoint"
// Links the point at the end of the path's points.
ControlPoint(Anim *path, const char *name);
~ControlPoint();
Anim *GetPath() const { return static_cast<Anim *>(parent); }
bool ChangeParent(Anim *path);
void SetOffset(float x, float y);
void SetOrder(int value, bool notify, bool wrap);
float offsetX = 0.0f, offsetY = 0.0f;
float position = 0.0f; // m_position: the path progress the point is at
int order = -1;
};
// 4.3.4's s_frameInterval: progress steps at most this often unless the
// group ignores the framerate throttle. 1/30 s until SetMaxAnimFramerate
// (Framerate.cpp) changes it.
extern float g_frameInterval;
// AnimationGroup:CreateAnimation (Anim.cpp, where the animation classes are).
int __fastcall Script_CreateAnimation(void *L);
const char *LoopTypeToString(LoopType type);
bool StringToLoopType(const char *text, LoopType &type);
const char *LoopStateToString(int state);
bool StringToSmoothWeights(const char *text, float &in, float &out);
const char *SmoothWeightsToString(float in, float out);
} // namespace Animation
+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/>.
// `SetMaxAnimFramerate(framesPerSec)` / `GetMaxAnimFramerate()` - 4.3.4's
// globals over CSimpleAnim::s_frameInterval (SimpleFrameScript_Scripts.cpp),
// the throttle that Anim::UpdateProgress steps progress by. The setter stores
// 1 / fps unchecked, as 4.3.4 does: 0 stores infinity, so progress stops
// stepping until the animation ends.
#include "Classes.h"
#include "Game.h"
namespace Animation {
float g_frameInterval = 1.0f / 30.0f;
namespace {
int __fastcall Script_SetMaxAnimFramerate(void *L) {
if (!Game::Lua::IsNumber(L, 1)) {
Game::Lua::Error(L, "Usage: SetMaxFramerate(framesPerSec)");
return 0;
}
g_frameInterval = 1.0f / static_cast<float>(Game::Lua::ToNumber(L, 1));
return 0;
}
int __fastcall Script_GetMaxAnimFramerate(void *L) {
Game::Lua::PushNumber(L, 1.0f / g_frameInterval);
return 1;
}
const Game::Doc::Field kSetArgs[] = {Game::Doc::Req("framesPerSec", "number")};
const Game::Doc::Field kGetRets[] = {Game::Doc::Req("framesPerSec", "number")};
const Game::Doc::Function kSet{"Sets how many times per second animations step their progress.", kSetArgs, {},
"AnimationGlobals"};
const Game::Doc::Function kGet{"Returns how many times per second animations step their progress.", {}, kGetRets,
"AnimationGlobals"};
void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("SetMaxAnimFramerate", &Script_SetMaxAnimFramerate, &kSet);
Game::Lua::RegisterGlobalFunction("GetMaxAnimFramerate", &Script_GetMaxAnimFramerate, &kGet);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace
} // namespace Animation
+695
View File
@@ -0,0 +1,695 @@
// 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/>.
// 4.3.4's CSimpleAnimGroup (wowdecomp15595 CSimpleAnimGroup.cpp and
// CSimpleAnimGroup_Scripts.cpp), on Animation::Object, with later clients'
// SetToFinalAlpha / IsSetToFinalAlpha: the final alpha is kept when the
// group finishes (Finish included), and Stop still restores the alpha. No
// source on disk says what a later client's Stop does with the flag.
#include "animation/Classes.h"
#include "animation/Region.h"
#include "Game.h"
#include "Offsets.h"
#include "baselib/Ascii.h"
#include <algorithm>
#include <cmath>
namespace Animation {
namespace {
const char *const kGroupScripts[] = {"onload", "onplay", "onpause", "onstop", "onfinished", "onupdate", "onloop"};
} // namespace
// ---- Construction ---------------------------------------------------------------
Group::Group(void *region, const char *name) : Object(s_class, region, name) {
if (region != nullptr)
Region::RegisterGroup(region, this);
}
Group::~Group() {
for (Anim *anim : animations)
delete anim;
}
// ---- State --------------------------------------------------------------------
bool Group::IsDone() const {
if (duration <= 0.0001f)
return true;
if (loopType == LOOP_REPEAT || loopType == LOOP_BOUNCE)
return false;
if (loopState == STATE_FORWARD || loopState == STATE_REVERSE)
return false;
return progress >= 1.0f;
}
void Group::Finish() {
if (!IsDone() && loopState != STATE_NONE)
flags |= GROUP_PENDING_FINISH;
}
int Group::GetMaxAnimOrder() const {
if (animLists.empty())
return -1;
return animLists.back().front()->order;
}
bool Group::HasAlphaAnim() const {
for (const Anim *anim : animations)
if (anim->kind == KIND_ALPHA)
return true;
return false;
}
bool Group::HasPositionAnim() const {
for (const Anim *anim : animations)
if (anim->kind != KIND_ALPHA)
return true;
return false;
}
// ---- Order lists ----------------------------------------------------------------
std::vector<Anim *> *Group::FindAnimList(int order) {
if (order == -1)
return nullptr;
int low = 0;
int high = static_cast<int>(animLists.size()) - 1;
while (low <= high) {
const int middle = static_cast<int>(static_cast<unsigned>(high + low) >> 1);
std::vector<Anim *> &list = animLists[middle];
if (!list.empty()) {
const int listOrder = list.front()->order;
if (listOrder < order)
low = middle + 1;
else if (listOrder > order)
high = middle - 1;
else
return &list;
}
}
return nullptr;
}
std::vector<Anim *> *Group::RegisterAnimList(int order) {
if (order == -1)
return nullptr;
const size_t count = animLists.size();
if (count == 0) {
animLists.emplace_back();
return &animLists.back();
}
size_t index = count;
for (size_t i = 0; i < count; ++i) {
std::vector<Anim *> &list = animLists[i];
if (list.empty())
return &list;
const int listOrder = list.front()->order;
if (order == listOrder)
return &list;
if (order < listOrder) {
index = i;
break;
}
}
animLists.insert(animLists.begin() + static_cast<ptrdiff_t>(index), std::vector<Anim *>());
return &animLists[index];
}
bool Group::AddAnimListNode(std::vector<Anim *> *list, Anim *anim) {
if (list == nullptr)
return false;
list->push_back(anim);
return true;
}
bool Group::RemoveAnimListNode(std::vector<Anim *> *list, Anim *anim) {
if (list == nullptr)
return false;
const auto it = std::find(list->begin(), list->end(), anim);
if (it == list->end())
return false;
list->erase(it);
if (list->empty())
SortAnimations();
return true;
}
void Group::ComputeDuration() {
duration = 0.0f;
for (std::vector<Anim *> &list : animLists) {
float span = 0.0f;
for (const Anim *anim : list) {
const float total = anim->duration + anim->endDelay + anim->startDelay;
if (total > span)
span = total;
}
for (Anim *anim : list)
anim->orderPadding = span - (anim->duration + anim->endDelay + anim->startDelay);
duration += span;
}
}
void Group::NotifyAnimAdded(Anim *anim) {
if (anim == nullptr)
return;
// m_animations.LinkToTail: an animation already in the list moves to its tail.
animations.erase(std::remove(animations.begin(), animations.end(), anim), animations.end());
animations.push_back(anim);
if (AddAnimListNode(RegisterAnimList(anim->order), anim))
ComputeDuration();
}
void Group::NotifyOrderChanged(Anim *anim, int oldOrder) {
if (anim == nullptr)
return;
if (RemoveAnimListNode(FindAnimList(oldOrder), anim))
if (AddAnimListNode(RegisterAnimList(anim->order), anim))
ComputeDuration();
}
void Group::NotifyAnimRemoved(Anim *anim) {
if (anim == nullptr)
return;
animations.erase(std::remove(animations.begin(), animations.end(), anim), animations.end());
std::vector<Anim *> *list = FindAnimList(anim->order);
if (RemoveAnimListNode(list, anim)) {
// RemoveAnimListNode sorts when the list emptied; the list may be gone.
ComputeDuration();
}
}
void Group::SortAnimations() {
if (loopState == STATE_NONE || (flags & GROUP_PAUSED)) {
loopState = STATE_NONE;
flags &= 0xF0;
currentOrder = -1;
elapsed = 0.0f;
progress = 0.0f;
} else {
Stop(false);
}
if (animations.empty()) {
animLists.clear();
return;
}
for (std::vector<Anim *> &list : animLists)
list.clear();
int nextOrder = 0;
for (Anim *anim : animations) {
int order = anim->order;
if (order == -1) {
order = nextOrder++;
anim->order = order < 0 ? 0 : order;
} else {
nextOrder = order + 1;
}
if (nextOrder > 99)
nextOrder = 0;
AddAnimListNode(RegisterAnimList(order), anim);
}
while (!animLists.empty() && animLists.back().empty())
animLists.pop_back();
}
void Group::ResetAnims() {
for (Anim *anim : animations) {
anim->loopState = loopState > 0 && loopState <= 2 ? loopState : 0;
anim->playState = 0;
anim->elapsed = 0.0f;
anim->progressWithDelay = 0.0f;
anim->progress = 0.0f;
}
}
// ---- Playback --------------------------------------------------------------------
void Group::Pause() {
if (loopState == STATE_NONE || (flags & GROUP_PAUSED))
return;
flags |= GROUP_PAUSED;
const std::vector<Anim *> list = animLists[currentOrder];
for (Anim *anim : list)
anim->Pause();
RunScript(G_ONPAUSE, 0);
}
void Group::Stop(bool requested) {
if (loopState == STATE_NONE || (flags & GROUP_STOPPING))
return;
flags |= GROUP_STOPPING;
const std::vector<Anim *> list = animLists[currentOrder];
for (Anim *anim : list)
anim->Stop(requested);
Region::NotifyEnd(RegionObject(), this);
flags &= 0xF0;
loopState = STATE_NONE;
currentOrder = -1;
elapsed = 0.0f;
progress = 0.0f;
if (HasScript(G_ONSTOP)) {
Game::Lua::PushBool(Game::Lua::State(), requested);
RunScript(G_ONSTOP, 1);
}
}
bool Group::AdvanceLoopState(float /*elapsedSec*/, float /*remaining*/) {
const int count = static_cast<int>(animLists.size());
const bool reverse = loopState == STATE_REVERSE;
const int step = reverse ? -1 : 1;
const int first = reverse ? count - 1 : 0;
const int end = reverse ? -1 : count;
currentOrder += step;
if (currentOrder == end) {
if (loopType == LOOP_NONE || (flags & GROUP_PENDING_FINISH))
return true;
if (loopType == LOOP_BOUNCE) {
loopState = static_cast<LoopState>(!reverse + 1);
currentOrder -= step;
} else {
currentOrder = first;
}
elapsed = 0.0f;
progress = 0.0f;
ResetAnims();
if (HasScript(G_ONLOOP)) {
Game::Lua::PushString(Game::Lua::State(), LoopStateToString(loopState));
RunScript(G_ONLOOP, 1);
}
if (loopState == STATE_NONE || (flags & GROUP_PAUSED))
return true;
}
const std::vector<Anim *> list = animLists[currentOrder];
for (Anim *anim : list)
anim->Play();
return false;
}
bool Group::DoGroupUpdateWork(float elapsedSec) {
float remaining = elapsedSec < 0.0f ? 0.0f : (elapsedSec >= 60.0f ? 60.0f : elapsedSec);
while (true) {
for (Anim *anim : animLists[currentOrder]) {
void *region = anim->GetRegionParent();
if (region != nullptr)
Region::PreOnAnimUpdate(region);
}
for (int i = 0; i < currentOrder; ++i)
for (Anim *anim : animLists[i])
anim->Apply(1.0f);
float maxConsumed = 0.0f;
bool finished = true;
const std::vector<Anim *> list = animLists[currentOrder];
for (Anim *anim : list) {
float consumed;
finished = anim->OnUpdate(remaining, consumed) && finished;
if (consumed > maxConsumed)
maxConsumed = consumed;
}
if (!(flags & GROUP_PAUSED) && loopState != STATE_NONE) {
remaining -= maxConsumed;
elapsed += maxConsumed;
progress = elapsed < duration ? elapsed / duration : 1.0f;
if (finished && AdvanceLoopState(elapsedSec, remaining))
return true;
}
if (remaining <= 0.0001f || IsDone() || loopState == STATE_NONE || (flags & GROUP_PAUSED))
return false;
}
}
bool Group::OnUpdate(float elapsedSec) {
if (IsDone() || loopState == STATE_NONE)
return true;
const bool done = DoGroupUpdateWork(elapsedSec);
if (HasScript(G_ONUPDATE)) {
Game::Lua::PushNumber(Game::Lua::State(), elapsedSec);
RunScript(G_ONUPDATE, 1);
}
if (done) {
// setToFinalAlpha: the alpha each alpha animation's target finished on
// becomes what the end restores. Stop restores the alpha as before.
if (setToFinalAlpha)
for (Anim *anim : animations)
if (anim->kind == KIND_ALPHA)
Region::KeepAnimAlpha(RegionObject(), anim->target);
Region::NotifyEnd(RegionObject(), this);
const bool requested = (flags & GROUP_PENDING_FINISH) != 0;
loopState = STATE_NONE;
flags &= 0xF0;
currentOrder = -1;
elapsed = 0.0f;
progress = 0.0f;
if (HasScript(G_ONFINISHED)) {
Game::Lua::PushBool(Game::Lua::State(), requested);
RunScript(G_ONFINISHED, 1);
}
}
return IsDone();
}
bool Group::Play(bool reverse) {
if (animations.empty())
return false;
if (loopState != STATE_NONE && !(flags & GROUP_PAUSED))
return true;
if (flags & GROUP_PAUSED) {
flags &= ~GROUP_PAUSED;
} else {
flags &= 0xF0;
loopState = STATE_NONE;
currentOrder = reverse ? 0x7FFF : -1;
elapsed = 0.0f;
progress = 0.0f;
}
RunScript(G_ONPLAY, 0);
const int count = static_cast<int>(animLists.size());
if (count > 0) {
if (currentOrder < 0 || currentOrder >= count) {
if (currentOrder < 0) {
loopState = STATE_FORWARD;
currentOrder = 0;
} else {
loopState = STATE_REVERSE;
currentOrder = count - 1;
}
ResetAnims();
}
const std::vector<Anim *> list = animLists[currentOrder];
for (Anim *anim : list)
anim->Play();
Region::NotifyBegin(RegionObject(), this);
}
OnUpdate(0.0f);
return true;
}
void Group::PostLoadXML() {
flags &= ~GROUP_LOADING;
const std::vector<Anim *> list = animations;
for (Anim *anim : list)
anim->PostLoadXML();
SortAnimations();
ComputeDuration();
RunScript(G_ONLOAD, 0);
}
// ---- Strings ----------------------------------------------------------------------
namespace {
struct Named {
int value;
const char *name;
};
const Named kLoopTypes[] = {{LOOP_NONE, "NONE"}, {LOOP_REPEAT, "REPEAT"}, {LOOP_BOUNCE, "BOUNCE"}};
const Named kLoopStates[] = {{STATE_NONE, "NONE"}, {STATE_FORWARD, "FORWARD"}, {STATE_REVERSE, "REVERSE"}};
struct Weights {
float in, out;
const char *name;
};
const Weights kSmoothWeights[] = {
{0.0f, 0.0f, "NONE"}, {1.0f, 0.0f, "IN"}, {0.0f, 1.0f, "OUT"}, {1.0f, 1.0f, "IN_OUT"}, {1.0f, 1.0f, "OUT_IN"},
};
} // namespace
const char *LoopTypeToString(LoopType type) {
for (const Named &n : kLoopTypes)
if (n.value == type)
return n.name;
return "UNKNOWN";
}
bool StringToLoopType(const char *text, LoopType &type) {
for (const Named &n : kLoopTypes)
if (text != nullptr && Ascii::EqualCI(n.name, text)) {
type = static_cast<LoopType>(n.value);
return true;
}
return false;
}
const char *LoopStateToString(int state) {
for (const Named &n : kLoopStates)
if (n.value == state)
return n.name;
return "UNKNOWN";
}
bool StringToSmoothWeights(const char *text, float &in, float &out) {
for (const Weights &w : kSmoothWeights)
if (text != nullptr && Ascii::EqualCI(w.name, text)) {
in = w.in;
out = w.out;
return true;
}
return false;
}
const char *SmoothWeightsToString(float in, float out) {
for (const Weights &w : kSmoothWeights)
if (std::fabs(in - w.in) < 0.001f && std::fabs(out - w.out) < 0.001f)
return w.name;
return "UNKNOWN";
}
// ---- Lua methods (CSimpleAnimGroup_Scripts.cpp) -------------------------------
namespace {
Group *Self(void *L) { return static_cast<Group *>(Resolve(L, 1, Group::s_class)); }
int __fastcall Script_Play(void *L) {
if (Group *g = Self(L))
g->Play(Game::Lua::ToFlag(L, 2));
return 0;
}
int __fastcall Script_Pause(void *L) {
if (Group *g = Self(L))
g->Pause();
return 0;
}
int __fastcall Script_Stop(void *L) {
if (Group *g = Self(L))
g->Stop(true);
return 0;
}
int __fastcall Script_Finish(void *L) {
if (Group *g = Self(L))
g->Finish();
return 0;
}
int __fastcall Script_GetProgress(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushNumber(L, g->elapsed / g->duration);
return 1;
}
int __fastcall Script_IsDone(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushBool(L, g->IsDone());
return 1;
}
int __fastcall Script_IsPlaying(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushBool(L, g->IsPlaying());
return 1;
}
int __fastcall Script_IsPaused(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushBool(L, (g->flags & GROUP_PAUSED) != 0);
return 1;
}
int __fastcall Script_IsPendingFinish(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushBool(L, (g->flags & GROUP_PENDING_FINISH) != 0);
return 1;
}
int __fastcall Script_GetDuration(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushNumber(L, g->duration);
return 1;
}
int __fastcall Script_SetLooping(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
if (!Game::Lua::IsString(L, 2)) {
Game::Lua::Error(L, "Usage: %s:SetLooping(\"loopType\")", g->DisplayName());
return 0;
}
LoopType type;
if (StringToLoopType(Game::Lua::ToString(L, 2), type)) {
g->loopType = type;
return 0;
}
Game::Lua::Error(L, "%s:SetLooping(): Unknown loop type specified", g->DisplayName());
return 0;
}
int __fastcall Script_GetLooping(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushString(L, LoopTypeToString(g->loopType));
return 1;
}
int __fastcall Script_GetLoopState(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushString(L, LoopStateToString(g->loopState));
return 1;
}
int __fastcall Script_GetMaxOrder(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushNumber(L, g->GetMaxAnimOrder() + 1);
return 1;
}
int __fastcall Script_SetInitialOffset(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
Game::Lua::Error(L, "Usage: %s:SetInitialOffset(x, y)", g->DisplayName());
return 0;
}
const float x = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 2)));
const float y = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 3)));
// 4.3.4's SetInitialOffset: a near-zero offset is zero.
if (x * x + y * y <= 0.00000023841858f) {
g->initialOffsetX = 0.0f;
g->initialOffsetY = 0.0f;
} else {
g->initialOffsetX = x;
g->initialOffsetY = y;
}
return 0;
}
int __fastcall Script_GetInitialOffset(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushNumber(L, Game::InternalToPixel(g->initialOffsetX));
Game::Lua::PushNumber(L, Game::InternalToPixel(g->initialOffsetY));
return 2;
}
int __fastcall Script_GetAnimations(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
const int count = static_cast<int>(g->animations.size());
if (!Game::Lua::CheckStack(L, count)) {
Game::Lua::Error(L, "%s:GetAnimations(): Stack overflow", g->DisplayName());
return 0;
}
for (Anim *anim : g->animations)
Push(L, anim);
return count;
}
int __fastcall Script_SetIgnoreFramerateThrottle(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
if (Game::Lua::ToFlag(L, 2))
g->flags |= GROUP_IGNORE_THROTTLE;
else
g->flags &= ~GROUP_IGNORE_THROTTLE;
return 0;
}
int __fastcall Script_GetIgnoreFramerateThrottle(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
if (g->flags & GROUP_IGNORE_THROTTLE)
Game::Lua::PushNumber(L, 1.0);
else
Game::Lua::PushNil(L);
return 1;
}
int __fastcall Script_SetToFinalAlpha(void *L) {
if (Group *g = Self(L))
g->setToFinalAlpha = Game::Lua::ToFlag(L, 2);
return 0;
}
int __fastcall Script_IsSetToFinalAlpha(void *L) {
Group *g = Self(L);
if (g == nullptr)
return 0;
Game::Lua::PushBool(L, g->setToFinalAlpha);
return 1;
}
const Game::Lua::FrameMethodEntry kMethods[] = {
{"GetObjectType", &Script_GetObjectType},
{"IsObjectType", &Script_IsObjectType},
{"GetName", &Script_GetName},
{"GetParent", &Script_GetParent},
{"Play", &Script_Play},
{"Pause", &Script_Pause},
{"Stop", &Script_Stop},
{"Finish", &Script_Finish},
{"GetProgress", &Script_GetProgress},
{"IsDone", &Script_IsDone},
{"IsPlaying", &Script_IsPlaying},
{"IsPaused", &Script_IsPaused},
{"IsPendingFinish", &Script_IsPendingFinish},
{"GetDuration", &Script_GetDuration},
{"SetLooping", &Script_SetLooping},
{"GetLooping", &Script_GetLooping},
{"GetLoopState", &Script_GetLoopState},
{"GetMaxOrder", &Script_GetMaxOrder},
{"SetInitialOffset", &Script_SetInitialOffset},
{"GetInitialOffset", &Script_GetInitialOffset},
{"GetAnimations", &Script_GetAnimations},
{"CreateAnimation", &Script_CreateAnimation},
{"HasScript", &Script_HasScript},
{"GetScript", &Script_GetScript},
{"SetScript", &Script_SetScript},
{"HookScript", &Script_HookScript},
{"SetIgnoreFramerateThrottle", &Script_SetIgnoreFramerateThrottle},
{"GetIgnoreFramerateThrottle", &Script_GetIgnoreFramerateThrottle},
{"SetToFinalAlpha", &Script_SetToFinalAlpha},
{"IsSetToFinalAlpha", &Script_IsSetToFinalAlpha},
};
} // namespace
Class Group::s_class{"AnimationGroup", nullptr, kGroupScripts, 7, kMethods,
static_cast<int>(sizeof(kMethods) / sizeof(kMethods[0])), 0, 0};
} // namespace Animation
+338
View File
@@ -0,0 +1,338 @@
// 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 "animation/Object.h"
#include "HookSecureFunc.h"
#include "Offsets.h"
#include "baselib/Ascii.h"
#include "frame/ScriptArgs.h"
#include <cstring>
namespace Animation {
namespace {
using Construct_t = void(__fastcall *)(void *object);
using Destruct_t = void(__fastcall *)(void *object);
using Lock_t = void(__fastcall *)(void *object, void *edx, const char *name);
using Unlock_t = void(__fastcall *)(void *object, void *edx, const char *name);
using BaseResolve_t = uint32_t *(__fastcall *)(void *object, void *edx, const char *name);
using Release_t = void(__stdcall *)(uint32_t *slot);
using GetName_t = const char *(__fastcall *)(const void *object);
// 4.3.4's CScriptObject type name, which every class's IsA(name) accepts.
constexpr const char *kObjectTypeName = "Object";
Object *Self(void *object) { return static_cast<Object *>(object); }
// ---- The vtable (the engine calls these on our objects) --------------------
void *__fastcall V_Delete(Object *object, void * /*edx*/, unsigned flags);
const char *__fastcall V_GetName(Object *object) { return object->Name(); }
// vtable+0x08: push the method `name` of the object's class or a base.
int __fastcall V_FindMethod(Object *object, void * /*edx*/, void *L, const char *name) {
for (const Class *c = object->cls; c != nullptr; c = c->base) {
if (c->methodsRef <= 0)
continue;
Game::Lua::RawGetI(L, Game::Lua::REGISTRY_INDEX, c->methodsRef);
Game::Lua::PushString(L, name);
Game::Lua::RawGet(L, -2);
if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_NIL) {
Game::Lua::Remove(L, -2);
return 1;
}
Game::Lua::SetTop(L, -3);
}
return 0;
}
// vtable+0x0C: 4.3.4's GetScriptByName - the base OnEvent first.
uint32_t *__fastcall V_ResolveScript(Object *object, void * /*edx*/, const char *name) {
uint32_t *slot =
reinterpret_cast<BaseResolve_t>(Offsets::FUN_SCRIPT_OBJECT_BASE_RESOLVE_SCRIPT)(object, nullptr, name);
return slot != nullptr ? slot : object->ScriptSlot(name);
}
int __fastcall V_IsA(Object *object, void * /*edx*/, int typeId) {
for (const Class *c = object->cls; c != nullptr; c = c->base)
if (c->typeId != 0 && c->typeId == typeId)
return 1;
return 0;
}
// vtable+0x14 differs per engine class; nothing calls it on ours.
int __fastcall V_Unused(Object * /*object*/) { return 0; }
int __fastcall V_IsAName(Object *object, void * /*edx*/, const char *typeName) {
if (typeName == nullptr)
return 0;
for (const Class *c = object->cls; c != nullptr; c = c->base)
if (Ascii::EqualCI(typeName, c->typeName))
return 1;
return Ascii::EqualCI(typeName, kObjectTypeName) ? 1 : 0;
}
const char *__fastcall V_GetObjectTypeName(Object *object) { return object->cls->typeName; }
void *g_vtable[] = {
reinterpret_cast<void *>(&V_Delete), reinterpret_cast<void *>(&V_GetName),
reinterpret_cast<void *>(&V_FindMethod), reinterpret_cast<void *>(&V_ResolveScript),
reinterpret_cast<void *>(&V_IsA), reinterpret_cast<void *>(&V_Unused),
reinterpret_cast<void *>(&V_IsAName), reinterpret_cast<void *>(&V_GetObjectTypeName),
};
// Slot 0, the engine's deleting destructor. The engine never deletes our
// objects - their owners (a region, a group) do, by their concrete type.
void *__fastcall V_Delete(Object *object, void * /*edx*/, unsigned /*flags*/) { return object; }
} // namespace
// ---- Object -------------------------------------------------------------------
Object::Object(const Class &cls, void *parent, const char *name) : cls(&cls), parent(parent) {
reinterpret_cast<Construct_t>(Offsets::FUN_SCRIPT_OBJECT_CONSTRUCT)(this);
vtable = g_vtable;
if (name != nullptr && *name != '\0')
this->name = CreateName(name, parent);
reinterpret_cast<Lock_t>(Offsets::FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER)(this, nullptr, Name());
}
bool Object::s_detached = false;
Object::~Object() {
if (s_detached)
return;
for (auto &slot : scripts)
reinterpret_cast<Release_t>(Offsets::FUN_SCRIPT_RELEASE)(slot);
while (holders > 1)
reinterpret_cast<Unlock_t>(Offsets::FUN_SCRIPT_OBJECT_UNLOCK)(this, nullptr, nullptr);
if (holders > 0)
reinterpret_cast<Unlock_t>(Offsets::FUN_SCRIPT_OBJECT_UNLOCK)(this, nullptr, Name());
reinterpret_cast<Destruct_t>(Offsets::FUN_SCRIPT_OBJECT_DESTRUCT)(this);
}
uint32_t *Object::ScriptSlot(const char *scriptName) {
if (scriptName == nullptr)
return nullptr;
for (const Class *c = cls; c != nullptr; c = c->base) {
for (int i = 0; i < c->scriptCount; ++i)
if (Ascii::EqualCI(scriptName, c->scriptNames[i]))
return scripts[i];
if (c->scriptCount > 0)
break; // only one class in a chain declares the scripts
}
return nullptr;
}
void Object::RunScript(int index, int nargs) {
void *L = Game::Lua::State();
if (L == nullptr)
return;
const int first = Game::Lua::GetTop(L) - nargs + 1;
if (HasScript(index))
Frame::ScriptArgs::RunSlotWithValues(L, scripts[index], this, first, nargs);
Game::Lua::SetTop(L, first - 1);
}
// ---- Helpers --------------------------------------------------------------------
int TypeId(Class &cls) { return Game::Lua::FrameScriptTypeId(reinterpret_cast<uintptr_t>(&cls.typeId)); }
Object *Resolve(void *L, int idx, Class &cls) {
return static_cast<Object *>(Game::Lua::ResolveTypedObject(L, idx, reinterpret_cast<uintptr_t>(&cls.typeId)));
}
void Push(void *L, Object *object) { Game::Lua::PushObject(L, object); }
bool IsOurs(const void *object) { return object != nullptr && Game::Read<void **>(object, 0) == g_vtable; }
std::string CreateName(const char *source, const void *parent) {
constexpr const char kParent[] = "$parent";
constexpr size_t kParentLen = sizeof(kParent) - 1;
if (std::strlen(source) < kParentLen || !Ascii::EqualCI(std::string(source, kParentLen).c_str(), kParent))
return source;
std::string name = "Top";
for (const void *p = parent; p != nullptr;) {
const char *pname = IsOurs(p) ? static_cast<const Object *>(p)->Name()
: Game::Read<GetName_t>(Game::Read<void *>(p, 0),
Offsets::VTBL_SCRIPTOBJECT_GET_NAME)(p);
if (pname != nullptr && *pname != '\0') {
name = pname;
break;
}
p = IsOurs(p) ? static_cast<const Object *>(p)->parent : Game::Read<void *>(p, Offsets::OFF_REGION_PARENT);
}
return name + (source + kParentLen);
}
void RegisterClass(Class &cls) {
void *L = Game::Lua::State();
TypeId(cls);
Game::Lua::NewTable(L);
for (int i = 0; i < cls.methodCount; ++i) {
Game::Lua::PushString(L, cls.methods[i].name);
Game::Lua::PushCClosure(L, cls.methods[i].func, 0);
Game::Lua::RawSet(L, -3);
}
cls.methodsRef = Game::Lua::Ref(L, Game::Lua::REGISTRY_INDEX);
}
// ---- The base methods -----------------------------------------------------------
namespace {
// The object at self, of any of our classes.
Object *AnySelf(void *L) {
if (Game::Lua::Type(L, 1) != Game::Lua::TYPE_TABLE)
return nullptr;
void *object = Game::Lua::ResolveObject(L, 1);
return IsOurs(object) ? Self(object) : nullptr;
}
} // namespace
int __fastcall Script_GetObjectType(void *L) {
Object *object = AnySelf(L);
if (object == nullptr)
return 0;
Game::Lua::PushString(L, object->cls->typeName);
return 1;
}
int __fastcall Script_IsObjectType(void *L) {
Object *object = AnySelf(L);
if (object == nullptr)
return 0;
if (!Game::Lua::IsString(L, 2)) {
Game::Lua::Error(L, "Usage: %s:IsObjectType(\"TYPE\")", object->DisplayName());
return 0;
}
if (V_IsAName(object, nullptr, Game::Lua::ToString(L, 2)))
Game::Lua::PushNumber(L, 1.0);
else
Game::Lua::PushNil(L);
return 1;
}
int __fastcall Script_GetName(void *L) {
Object *object = AnySelf(L);
if (object == nullptr)
return 0;
Game::Lua::PushString(L, object->Name());
return 1;
}
int __fastcall Script_GetParent(void *L) {
Object *object = AnySelf(L);
if (object == nullptr)
return 0;
if (object->parent != nullptr)
Game::Lua::PushObject(L, object->parent);
else
Game::Lua::PushNil(L);
return 1;
}
// 4.3.4's HasScript: 1 when the class has the script, else nil.
int __fastcall Script_HasScript(void *L) {
Object *object = AnySelf(L);
if (object == nullptr)
return 0;
if (!Game::Lua::IsString(L, 2)) {
Game::Lua::Error(L, "Usage: %s:HasScript(\"type\")", object->DisplayName());
return 0;
}
if (V_ResolveScript(object, nullptr, Game::Lua::ToString(L, 2)) != nullptr)
Game::Lua::PushNumber(L, 1.0);
else
Game::Lua::PushNil(L);
return 1;
}
// The engine's Script GetScript (0x00774780) on our object: the slot's
// context becomes current, then the handler (nil for none) is pushed.
int __fastcall Script_GetScript(void *L) {
Object *object = AnySelf(L);
if (object == nullptr)
return 0;
if (!Game::Lua::IsString(L, 2)) {
Game::Lua::Error(L, "Usage: %s:GetScript(\"type\")", object->DisplayName());
return 0;
}
const uint32_t *slot = V_ResolveScript(object, nullptr, Game::Lua::ToString(L, 2));
if (slot == nullptr) {
Game::Lua::Error(L, "%s doesn't have a \"%s\" script", object->DisplayName(), Game::Lua::ToString(L, 2));
return 0;
}
if (slot[1] != 0 && Game::Read<int>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH) != 0)
Game::Ref<uint32_t>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT) = slot[1];
Game::Lua::RawGetI(L, Game::Lua::REGISTRY_INDEX, static_cast<int>(slot[0]));
return 1;
}
// The engine's Script SetScript (0x007748D0) on our object: release the old
// handler, store a ref of the new one (0 for nil) with the current context.
int __fastcall Script_SetScript(void *L) {
Object *object = AnySelf(L);
if (object == nullptr)
return 0;
const int handlerType = Game::Lua::Type(L, 3);
if (!Game::Lua::IsString(L, 2) ||
(handlerType != Game::Lua::TYPE_FUNCTION && handlerType != Game::Lua::TYPE_NIL &&
handlerType != -1 /* none */)) {
Game::Lua::Error(L, "Usage: %s:SetScript(\"type\", function)", object->DisplayName());
return 0;
}
uint32_t *slot = V_ResolveScript(object, nullptr, Game::Lua::ToString(L, 2));
if (slot == nullptr) {
Game::Lua::Error(L, "%s doesn't have a \"%s\" script", object->DisplayName(), Game::Lua::ToString(L, 2));
return 0;
}
reinterpret_cast<Release_t>(Offsets::FUN_SCRIPT_RELEASE)(slot);
Game::Lua::SetTop(L, 3);
const int ref = Game::Lua::Ref(L, Game::Lua::REGISTRY_INDEX);
slot[0] = ref > 0 ? static_cast<uint32_t>(ref) : 0;
slot[1] = Game::Read<uint32_t>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT);
return 0;
}
// Frame HookScript's (frame/Modern.cpp) on our object: no handler yet -> the
// hook is the handler; else the hooksecurefunc wrapper over (old, hook).
int __fastcall Script_HookScript(void *L) {
Object *object = AnySelf(L);
if (object == nullptr)
return 0;
if (!Game::Lua::IsString(L, 2) || Game::Lua::Type(L, 3) != Game::Lua::TYPE_FUNCTION) {
Game::Lua::Error(L, "Usage: %s:HookScript(\"type\", function)", object->DisplayName());
return 0;
}
Game::Lua::SetTop(L, 3); // (self, type, hook)
Game::Lua::PushValue(L, 1);
Game::Lua::PushValue(L, 2);
Game::Lua::PushCClosure(L, &Script_GetScript, 0);
Game::Lua::Insert(L, -3);
Game::Lua::Call(L, 2, 1); // (self, type, hook, old)
if (Game::Lua::Type(L, 4) == Game::Lua::TYPE_FUNCTION) {
Game::Lua::Insert(L, 3); // (self, type, old, hook)
HookSecureFunc::PushWrapper(L); // (self, type, wrapper)
} else {
Game::Lua::SetTop(L, 3);
}
return Script_SetScript(L);
}
} // namespace Animation
+123
View File
@@ -0,0 +1,123 @@
// 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
#include "Game.h"
#include <cstdint>
#include <string>
// Animation groups and animations as real 1.12 script objects.
//
// 4.3.4's CSimpleAnimGroup and CSimpleAnim are CScriptObjects: the engine
// hands them to Lua as the same kind of table as a frame (`t[0]` = the
// object, metatable `__framescript_meta`), finds their methods through the
// object's vtable, resolves `self` with the object's IsA, and stores their
// scripts in {handler, context} slots it finds through the object's script
// resolver. 1.12 has the same machinery (benilla-re ui/methods, ui/script):
// - ConstructScriptObject (0x00701AE0) builds the 0x24-byte header below;
// DestructScriptObject (0x00701B40) releases it;
// - LockScriptObject / UnlockScriptObject (0x00701BD0 / 0x00701CD0) make and
// free the object's table and its name global;
// - `__framescript_meta.__index` (0x007020B0) calls vtable+0x08 (L, name)
// to push a method; ResolveTypedObject's type test calls vtable+0x10;
// - SetScriptObjectScript (0x007025C0) compiles an XML script body into
// the slot vtable+0x0C returns, and FrameScriptReleaseScript (0x00702670)
// frees a slot.
// So an animation object is an engine script object whose vtable is ours.
// It has no C++ virtual functions - its first bytes are the engine header -
// and its class (Class) carries what differs per type.
namespace Animation {
// The 1.12 script-object header, as ConstructScriptObject fills it.
struct ScriptObjectHeader {
void **vtable;
int32_t holders; // +0x04, LockScriptObject's count
int32_t luaRef; // +0x08, the table's registry ref (-2 when none)
uint32_t onEvent[2]; // +0x0C, the base OnEvent slot
uint32_t events[4]; // +0x14, the event index array
};
static_assert(sizeof(ScriptObjectHeader) == 0x24, "the engine's script-object header");
struct Class {
const char *typeName; // GetObjectType, IsObjectType
const Class *base;
// The class's own script names, lower case; a slot per name.
const char *const *scriptNames;
int scriptCount;
const Game::Lua::FrameMethodEntry *methods;
int methodCount;
int typeId; // from the engine's type counter, on first use
int methodsRef; // registry ref of the method table, per Lua state
};
constexpr int kMaxScripts = 8;
class Object : public ScriptObjectHeader {
public:
const Class *cls;
// The script object this one hangs from: a group's region, an
// animation's group (GetParent, "$parent").
void *parent;
std::string name;
uint32_t scripts[kMaxScripts][2] = {}; // {handler ref, context}
// The object's script slot for `name` (any case), or nullptr.
uint32_t *ScriptSlot(const char *name);
bool HasScript(int index) const { return scripts[index][0] != 0; }
// Runs script `index` with `nargs` values pushed on top of the stack,
// and pops them.
void RunScript(int index, int nargs);
const char *Name() const { return name.empty() ? nullptr : name.c_str(); }
// While set, a destroyed object leaves the engine alone: its table and
// handlers belonged to a Lua state that is gone (/reload leftovers).
static bool s_detached;
const char *DisplayName() const { return name.empty() ? "<unnamed>" : name.c_str(); }
protected:
// Registers the object's table, under its name when it has one ("$parent"
// resolved from `parent`).
Object(const Class &cls, void *parent, const char *name);
~Object();
};
// The class's type id (the engine's counter, assigned on first use).
int TypeId(Class &cls);
// The object at `idx` when it is of `cls` or a class derived from it, else
// raises the engine's errors (as every method does) and returns nullptr.
Object *Resolve(void *L, int idx, Class &cls);
// Pushes the object's table.
void Push(void *L, Object *object);
// Whether a script object is one of ours.
bool IsOurs(const void *object);
// 4.3.4's CScriptObject::CreateName: "$parent" at the start of `source`
// becomes the nearest named ancestor's name, "Top" when none.
std::string CreateName(const char *source, const void *parent);
// Builds every class's method table in the current Lua state.
void RegisterClass(Class &cls);
// The base methods every class has (4.3.4's CScriptObject methods), and the
// script methods groups and animations share.
int __fastcall Script_GetObjectType(void *L);
int __fastcall Script_IsObjectType(void *L);
int __fastcall Script_GetName(void *L);
int __fastcall Script_GetParent(void *L);
int __fastcall Script_HasScript(void *L);
int __fastcall Script_GetScript(void *L);
int __fastcall Script_SetScript(void *L);
int __fastcall Script_HookScript(void *L);
} // namespace Animation
+501
View File
@@ -0,0 +1,501 @@
// 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/>.
// 4.3.4's CSimplePathAnim and CSimpleControlPoint (wowdecomp15595
// CSimplePathAnim.cpp, CSimpleControlPoint.cpp and their _Scripts.cpp).
//
// A Path moves the region through its control points: each point is an
// offset from where the region is, the points are spread evenly over the
// animation's progress (point i of n at (i + 1) / n), and the path starts
// at offset 0. Between points the offset is a straight line, or with the
// SMOOTH curve a Catmull-Rom spline. The offset goes through the same
// AddAnimTranslation as a Translation.
#include "animation/Classes.h"
#include "animation/Region.h"
#include "animation/Xml.h"
#include "Game.h"
#include "baselib/Ascii.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
namespace Animation {
// ---- CSimpleControlPoint ------------------------------------------------------------
ControlPoint::ControlPoint(Anim *path, const char *name) : Object(s_class, path, name) {
if (path != nullptr)
path->controlPoints.push_back(this);
}
ControlPoint::~ControlPoint() = default;
void ControlPoint::SetOffset(float x, float y) {
if (x * x + y * y <= 0.00000023841858f) {
offsetX = 0.0f;
offsetY = 0.0f;
} else {
offsetX = x;
offsetY = y;
}
}
void ControlPoint::SetOrder(int value, bool notify, bool wrap) {
const int oldOrder = order;
if (wrap)
order = value < 0 || value > 99 ? 0 : value;
else
order = value < 0 ? 0 : (value > 99 ? 99 : value);
if (parent != nullptr && notify && oldOrder != order)
GetPath()->NotifyControlPointOrderChanged(this);
}
bool ControlPoint::ChangeParent(Anim *path) {
if (path == nullptr || GetPath() == path)
return false;
// LinkToTail unlinks the point from the old path's list first.
Anim *old = GetPath();
if (old != nullptr)
old->controlPoints.erase(std::remove(old->controlPoints.begin(), old->controlPoints.end(), this),
old->controlPoints.end());
path->controlPoints.push_back(this);
if (old != nullptr)
old->NotifyControlPointRemoved(this);
parent = path;
path->NotifyControlPointAdded(this);
return true;
}
// ---- CSimplePathAnim -------------------------------------------------------------------
int Anim::GetMaxControlPointOrder() const { return sortedPoints.empty() ? -1 : sortedPoints.back()->order; }
int Anim::FindControlPoint(int value) const {
if (value == -1)
return -1;
int low = 0;
int high = static_cast<int>(sortedPoints.size()) - 1;
while (low <= high) {
const int middle = static_cast<int>(static_cast<unsigned>(high + low) >> 1);
const ControlPoint *point = sortedPoints[middle];
if (point == nullptr)
break; // 4.3.4 spins here; the array has no holes after BuildSpline
if (point->order < value)
low = middle + 1;
else if (point->order > value)
high = middle - 1;
else
return middle;
}
return -1;
}
void Anim::UpdateControlPointPositions() {
const size_t count = sortedPoints.size();
if (count == 0)
return;
const float step = 1.0f / static_cast<float>(count);
for (size_t i = 0; i < count; ++i) {
float position = static_cast<float>(i + 1) * step;
position = position < 0.0f ? 0.0f : (position >= 1.0f ? 1.0f : position);
sortedPoints[i]->position = position;
}
}
int Anim::RegisterSplineControlPoint(ControlPoint *point) {
const int count = static_cast<int>(sortedPoints.size());
if (count == 0) {
sortedPoints.push_back(point);
return 0;
}
int index = count;
for (int i = 0; i < count; ++i) {
ControlPoint *existing = sortedPoints[i];
if (existing == nullptr) {
sortedPoints[i] = point;
return i;
}
if (point->order == existing->order)
return i;
if (point->order < existing->order) {
index = i;
break;
}
}
sortedPoints.insert(sortedPoints.begin() + index, point);
return index;
}
void Anim::BuildSpline() {
Stop(false);
if (controlPoints.empty()) {
sortedPoints.clear();
return;
}
std::fill(sortedPoints.begin(), sortedPoints.end(), nullptr);
// Points take their order in link order; a point without one, or with
// one below the next free order, takes the next free order.
int nextOrder = 0;
for (ControlPoint *point : controlPoints) {
int value = point->order;
if (value == -1 || value < nextOrder) {
value = nextOrder++;
point->order = value < 0 ? 0 : value;
} else {
nextOrder = value + 1;
}
if (nextOrder > 99)
nextOrder = 0;
RegisterSplineControlPoint(point);
}
while (!sortedPoints.empty() && sortedPoints.back() == nullptr)
sortedPoints.pop_back();
}
void Anim::NotifyControlPointAdded(ControlPoint *point) {
if (point == nullptr)
return;
const int index = FindControlPoint(point->order);
if (index < 0) {
if (RegisterSplineControlPoint(point) >= 0)
UpdateControlPointPositions();
return;
}
// The order is taken: the point goes before the one that has it and
// takes the order; BuildSpline moves the rest up.
ControlPoint *existing = sortedPoints[index];
controlPoints.erase(std::remove(controlPoints.begin(), controlPoints.end(), point), controlPoints.end());
controlPoints.insert(std::find(controlPoints.begin(), controlPoints.end(), existing), point);
BuildSpline();
UpdateControlPointPositions();
}
void Anim::NotifyControlPointRemoved(ControlPoint *point) {
if (point != nullptr && FindControlPoint(point->order) >= 0) {
BuildSpline();
UpdateControlPointPositions();
}
}
void Anim::NotifyControlPointOrderChanged(ControlPoint *point) {
if (point == nullptr)
return;
const int index = FindControlPoint(point->order);
if (index >= 0 && sortedPoints[index] != point) {
ControlPoint *existing = sortedPoints[index];
controlPoints.erase(std::remove(controlPoints.begin(), controlPoints.end(), point), controlPoints.end());
controlPoints.insert(std::find(controlPoints.begin(), controlPoints.end(), existing), point);
}
BuildSpline();
UpdateControlPointPositions();
}
void Anim::ApplyPath(float progress) {
const int count = static_cast<int>(sortedPoints.size());
if (count == 0)
return;
void *region = GetRegionParent();
if (region == nullptr)
return;
const float t = std::fabs(progress);
// The segment: 4.3.4 converts count * t with the 2^16 + x float trick,
// which rounds to 1/128 before it truncates. Kept, so a progress just
// under a point's lands on the same segment.
const float scaled = static_cast<float>(count) * t;
const float biased = std::fabs(scaled) + 65536.0f;
int32_t bits;
std::memcpy(&bits, &biased, sizeof(bits));
uint32_t scaledBits;
std::memcpy(&scaledBits, &scaled, sizeof(scaledBits));
const int32_t sign = static_cast<int32_t>(scaledBits >> 31);
const int index = static_cast<int16_t>((((bits >> 7) & 0x7FFF) ^ sign) - sign);
float x = 0.0f, y = 0.0f;
const auto offsetOf = [this](int i, float &ox, float &oy) {
ox = sortedPoints[i]->offsetX;
oy = sortedPoints[i]->offsetY;
};
if (static_cast<unsigned>(index) >= static_cast<unsigned>(count)) {
offsetOf(count - 1, x, y);
} else if (curve && count > 1) {
// Catmull-Rom through p1 -> p2; the start is offset 0.
float p0x = 0.0f, p0y = 0.0f, p1x = 0.0f, p1y = 0.0f, p2x, p2y, p3x, p3y, t0, t1;
if (index != 0) {
offsetOf(index - 1, p1x, p1y);
t0 = sortedPoints[index - 1]->position;
offsetOf(index, p2x, p2y);
t1 = sortedPoints[index]->position;
if (index != 1)
offsetOf(index - 2, p0x, p0y);
if (index == count - 1) {
p3x = p2x * 2.0f - p1x;
p3y = p2y * 2.0f - p1y;
} else {
offsetOf(index + 1, p3x, p3y);
}
} else {
t0 = 0.0f;
offsetOf(0, p2x, p2y);
t1 = sortedPoints[0]->position;
p0x = -p2x;
p0y = -p2y;
offsetOf(1, p3x, p3y);
}
const float f = (t - t0) / (t1 - t0);
const float f2 = f * f;
const float f3 = f2 * f;
const float ax = -p0x + p1x * 3.0f - p2x * 3.0f + p3x;
const float ay = -p0y + p1y * 3.0f - p2y * 3.0f + p3y;
const float bx = p0x * 2.0f - p1x * 5.0f + p2x * 4.0f - p3x;
const float by = p0y * 2.0f - p1y * 5.0f + p2y * 4.0f - p3y;
const float cx = -p0x + p2x;
const float cy = -p0y + p2y;
x = (cx * f + p1x * 2.0f + bx * f2 + ax * f3) * 0.5f;
y = (cy * f + p1y * 2.0f + by * f2 + ay * f3) * 0.5f;
} else {
float ax = 0.0f, ay = 0.0f, bx, by, t0;
if (index != 0) {
offsetOf(index - 1, ax, ay);
t0 = sortedPoints[index - 1]->position;
} else {
t0 = 0.0f;
}
offsetOf(index, bx, by);
const float t1 = sortedPoints[index]->position;
const float f = (t - t0) / (t1 - t0);
x = ax + (bx - ax) * f;
y = f * (by - ay) + ay;
}
if (progress >= 0.0f)
Region::AddAnimTranslation(region, target, x, y);
else
Region::AddAnimTranslation(region, target, -x, -y);
}
// ---- Lua methods ---------------------------------------------------------------------
namespace {
Anim *PathSelf(void *L) { return static_cast<Anim *>(Resolve(L, 1, Anim::s_pathClass)); }
ControlPoint *PointSelf(void *L) { return static_cast<ControlPoint *>(Resolve(L, 1, ControlPoint::s_class)); }
// LoadXML.cpp's s_curveTypes.
bool StringToCurve(const char *text, bool &curve) {
if (Ascii::EqualCI(text, "NONE")) {
curve = false;
return true;
}
if (Ascii::EqualCI(text, "SMOOTH")) {
curve = true;
return true;
}
return false;
}
int __fastcall Script_SetCurve(void *L) {
Anim *path = PathSelf(L);
if (path == nullptr)
return 0;
if (!Game::Lua::IsString(L, 2)) {
Game::Lua::Error(L, "Usage: %s:SetCurve(\"curveType\")", path->DisplayName());
return 0;
}
if (!StringToCurve(Game::Lua::ToString(L, 2), path->curve))
Game::Lua::Error(L, "%s:SetCurve(): Unknown curve type specified", path->DisplayName());
return 0;
}
int __fastcall Script_GetCurve(void *L) {
Anim *path = PathSelf(L);
if (path == nullptr)
return 0;
Game::Lua::PushString(L, path->curve ? "SMOOTH" : "NONE");
return 1;
}
int __fastcall Script_GetMaxOrder(void *L) {
Anim *path = PathSelf(L);
if (path == nullptr)
return 0;
Game::Lua::PushNumber(L, path->GetMaxControlPointOrder() + 1);
return 1;
}
int __fastcall Script_GetControlPoints(void *L) {
Anim *path = PathSelf(L);
if (path == nullptr)
return 0;
const int count = static_cast<int>(path->sortedPoints.size());
if (count == 0)
return 0;
if (!Game::Lua::CheckStack(L, count)) {
Game::Lua::Error(L, "%s:GetControlPoints(): Stack overflow", path->DisplayName());
return 0;
}
for (ControlPoint *point : path->sortedPoints)
Push(L, point);
return count;
}
int __fastcall Script_CreateControlPoint(void *L) {
Anim *path = PathSelf(L);
if (path == nullptr)
return 0;
const char *name = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : nullptr;
const void *templateNode = nullptr;
if (Game::Lua::Type(L, 3) == Game::Lua::TYPE_STRING) {
const char *inherits = Game::Lua::ToString(L, 3);
templateNode = Xml::Template(inherits);
if (templateNode == nullptr) {
Game::Lua::Error(L, "%s:CreateControlPoint(): Couldn't find inherited node \"%s\"", path->DisplayName(),
inherits);
return 0;
}
}
ControlPoint *point = new ControlPoint(path, name);
if (templateNode != nullptr)
Xml::LoadControlPoint(point, templateNode, nullptr);
if (Game::Lua::IsNumber(L, 4))
point->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 4)) - 1, false, false);
// The decompiled CreateControlPoint passes the highest order itself,
// which takes the last point's place and reverses points made one after
// another; one past it, as SetParent does, puts the point last.
if (point->order == -1)
point->SetOrder(path->GetMaxControlPointOrder() + 1, false, true);
path->NotifyControlPointAdded(point);
Push(L, point);
return 1;
}
int __fastcall Script_PointSetParent(void *L) {
ControlPoint *point = PointSelf(L);
if (point == nullptr)
return 0;
if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_NIL) {
Game::Lua::Error(L, "%s:SetParent(): Cannot set a 'nil' parent for control points", point->DisplayName());
return 0;
}
const uintptr_t pathType = reinterpret_cast<uintptr_t>(&Anim::s_pathClass.typeId);
Anim *path = nullptr;
if (Game::Lua::IsString(L, 2)) {
// CScriptObject::GetScriptObjectByName(name, Path).
Game::Lua::PushString(L, Game::Lua::ToString(L, 2));
Game::Lua::RawGet(L, Game::Lua::GLOBALS_INDEX);
void *object = Game::Lua::Type(L, -1) == Game::Lua::TYPE_TABLE ? Game::Lua::ResolveObject(L, -1) : nullptr;
Game::Lua::SetTop(L, -2);
if (object != nullptr && IsOurs(object) && Game::Lua::IsA(object, pathType))
path = static_cast<Anim *>(object);
} else if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_TABLE) {
void *object = Game::Lua::ResolveObject(L, 2);
if (object == nullptr) {
Game::Lua::Error(L, "%s:SetParent(): Couldn't find 'this' in parent object", point->DisplayName());
return 0;
}
if (!IsOurs(object) || !Game::Lua::IsA(object, pathType)) {
Game::Lua::Error(L, "%s:SetParent(): Wrong parent object type, expected Path", point->DisplayName());
return 0;
}
path = static_cast<Anim *>(object);
}
if (path == nullptr) {
Game::Lua::Error(L, "%s:SetParent(): Couldn't find Path named '%s'", point->DisplayName(),
Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : "");
return 0;
}
const int oldOrder = point->order;
if (Game::Lua::IsNumber(L, 3)) {
point->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 3)) - 1, false, false);
} else {
int value = point->order;
if (value == -1)
value = path->GetMaxControlPointOrder() + 1;
point->SetOrder(value, false, true);
}
if (!point->ChangeParent(path) && oldOrder != point->order)
path->NotifyControlPointOrderChanged(point);
return 0;
}
int __fastcall Script_PointSetOffset(void *L) {
ControlPoint *point = PointSelf(L);
if (point == nullptr)
return 0;
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
Game::Lua::Error(L, "Usage: %s:SetOffset(x, y)", point->DisplayName());
return 0;
}
point->SetOffset(Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 2))),
Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 3))));
return 0;
}
int __fastcall Script_PointGetOffset(void *L) {
ControlPoint *point = PointSelf(L);
if (point == nullptr)
return 0;
Game::Lua::PushNumber(L, Game::InternalToPixel(point->offsetX));
Game::Lua::PushNumber(L, Game::InternalToPixel(point->offsetY));
return 2;
}
int __fastcall Script_PointSetOrder(void *L) {
ControlPoint *point = PointSelf(L);
if (point == nullptr)
return 0;
if (!Game::Lua::IsNumber(L, 2)) {
Game::Lua::Error(L, "Usage: %s:SetOrder(order)", point->DisplayName());
return 0;
}
point->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 2)) - 1, true, false);
return 0;
}
int __fastcall Script_PointGetOrder(void *L) {
ControlPoint *point = PointSelf(L);
if (point == nullptr)
return 0;
Game::Lua::PushNumber(L, point->order + 1);
return 1;
}
const Game::Lua::FrameMethodEntry kPathMethods[] = {
{"SetCurve", &Script_SetCurve},
{"GetCurve", &Script_GetCurve},
{"GetControlPoints", &Script_GetControlPoints},
{"CreateControlPoint", &Script_CreateControlPoint},
{"GetMaxOrder", &Script_GetMaxOrder},
};
// CScriptObject's methods, then CSimpleControlPoint's.
const Game::Lua::FrameMethodEntry kPointMethods[] = {
{"GetObjectType", &Script_GetObjectType}, {"IsObjectType", &Script_IsObjectType},
{"GetName", &Script_GetName}, {"GetParent", &Script_GetParent},
{"SetParent", &Script_PointSetParent}, {"SetOffset", &Script_PointSetOffset},
{"GetOffset", &Script_PointGetOffset}, {"SetOrder", &Script_PointSetOrder},
{"GetOrder", &Script_PointGetOrder},
};
template <size_t N> constexpr int Count(const Game::Lua::FrameMethodEntry (&)[N]) { return static_cast<int>(N); }
} // namespace
Class Anim::s_pathClass{"Path", &Anim::s_class, nullptr, 0, kPathMethods, Count(kPathMethods), 0, 0};
Class ControlPoint::s_class{"ControlPoint", nullptr, nullptr, 0, kPointMethods, Count(kPointMethods), 0, 0};
} // namespace Animation
+893
View File
@@ -0,0 +1,893 @@
// 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/>.
// The region side of the animation system, and the region methods
// CreateAnimationGroup / GetAnimationGroups / StopAnimating.
//
// 4.3.4 (wowdecomp15595 CScriptRegion.cpp, CSimpleFrame.cpp, CSimpleRegion.cpp,
// CSimpleRender.cpp, CLayoutFrame.cpp):
// - a region owns its groups (m_animGroups) and lists the playing ones
// (m_playingAnimGroups);
// - CSimpleFrame::OnLayerUpdate runs OnUpdate, then every group of the
// frame, then every group of each of its regions;
// - when a group starts, the region stores the state its animations change
// (AnimActivated: a frame its own alpha, a texture or font string its
// vertex alpha), unless an earlier group already did; a frame does this
// for every frame and region below it too;
// - every update first puts that state back (PreOnAnimUpdate), then the
// animations add to it (AddAnimAlpha: a frame's own alpha becomes
// change + its drawn alpha; a region's vertex alpha change + its own);
// - when the last group with that kind of animation on the region or any
// ancestor ends, the stored state goes back (AnimDeactivated).
// So, as in 4.3.4, GetAlpha returns the animated alpha while it plays.
//
// Position animations (Translation, Scale, Rotation) move only what
// is DRAWN, never a frame's rect: a frame hands them to every texture and font
// string below it. A texture moves the four corners its draw record points at
// (+0xD4, TL BL TR BR, the order of 4.3.4's m_positions); a font string moves
// its text block's string position, and is turned and scaled about its origin
// when its glyphs are baked (4.3.4 bakes them again whenever the string's
// rotation or scale changes; so does this, through the engine's node
// invalidate). The glyphs are scaled, not drawn at a larger font size: one
// size per update would fill the glyph cache. Their stored base is what the engine
// itself lays out (4.3.4's StoreAnimPosition): a texture's corners from its
// rect through the engine's corner store, a font string's inset x layout
// scale + its rect's min corner. When the layout moves a region mid-animation,
// the co-hooks on the two OnFrameSizeChanged callbacks move the base and keep
// the animation's offset, as 4.3.4's own OnFrameSizeChanged legs do.
//
// 1.12's regions have no room for these, so they are kept here, keyed by the
// region. A frame's own alpha is Frame::Alpha's (3.x's m_alpha), set through
// the frame's vtable setter as SetAlpha sets it; a region's vertex alpha is the
// engine's region color (FUN_REGION_GET_COLOR / FUN_FONTSTRING_SET_COLOR).
// The groups update from a co-hook of CSimpleFrame::OnFrameUpdate, which the
// engine calls for every shown frame after OnUpdate, so a hidden frame's
// groups wait, as in 4.3.4. Groups die with their frame (Frame::Destruction).
#include "animation/Region.h"
#include "animation/Classes.h"
#include "animation/Xml.h"
#include "Game.h"
#include "Offsets.h"
#include "frame/Alpha.h"
#include "frame/Destruction.h"
#include "texture/Transform.h"
#include "xml/Anchors.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <unordered_map>
#include <vector>
namespace Animation::Region {
namespace {
struct State {
std::vector<Group *> groups; // m_animGroups (owned)
std::vector<Group *> playing; // m_playingAnimGroups
};
// CAnimationData.
struct AnimData {
bool hasAlpha = false;
uint8_t alpha = 0xFF;
bool hasPosition = false;
// m_position[4]: a texture's four corners {x, y, z}; a font string uses
// the first as its string position.
float position[12] = {};
// A font string's animated rotation and scale (4.3.4's m_rotation /
// m_scale over the animation base), and what its glyphs were last baked
// with.
float rotation = 0.0f;
float scale = 1.0f;
float bakedRotation = 0.0f;
float bakedScale = 1.0f;
};
std::unordered_map<void *, State> g_states;
std::unordered_map<void *, AnimData> g_data;
// Font strings whose rotation or scale an update reset: checked against what
// they were baked with once the update has run.
std::vector<void *> g_touchedStrings;
// Regions (not frames) with groups: their frame's update has to look at its
// regions.
int g_regionsWithGroups = 0;
using FrameUpdate_t = void(__fastcall *)(void *frame, void *edx, float elapsed);
using SetFrameAlpha_t = void(__fastcall *)(void *frame, void *edx, uint32_t alpha);
using GetColor_t = void(__fastcall *)(void *region, void *edx, uint32_t *bgra);
using SetColor_t = void(__fastcall *)(void *region, void *edx, const uint32_t *bgra);
using StoreCorners_t = void(__fastcall *)(void *region, void *edx, float *rect);
using Crop_t = void(__fastcall *)(void *region, void *edx, float *rect);
using SetStringPos_t = void(__fastcall *)(void *block, const float *position);
using NdcToDdc_t = void(__fastcall *)(float *outX, float *outY, float x, float y);
using SizeChanged_t = void(__fastcall *)(void *layout, void *edx, const float *oldRect);
using InvalidateNode_t = void(__fastcall *)(void *node);
FrameUpdate_t g_origFrameUpdate = nullptr;
SizeChanged_t g_origTextureSizeChanged = nullptr;
SizeChanged_t g_origFontStringSizeChanged = nullptr;
bool IsFrame(void *region) { return Game::Lua::IsA(region, Offsets::VAR_FRAME_LUA_TYPE_ID); }
bool IsTexture(void *region) { return Game::Lua::IsA(region, Offsets::VAR_TEXTURE_LUA_TYPE_ID); }
bool IsFontString(void *region) { return Game::Lua::IsA(region, Offsets::VAR_FONTSTRING_LUA_TYPE_ID); }
void *ParentOf(void *region) { return Game::Read<void *>(region, Offsets::OFF_REGION_PARENT); }
State *Find(void *region) {
const auto it = g_states.find(region);
return it != g_states.end() ? &it->second : nullptr;
}
AnimData *DataOf(void *region) {
const auto it = g_data.find(region);
return it != g_data.end() ? &it->second : nullptr;
}
template <typename Fn> void ForEachChild(void *frame, Fn fn) {
Game::ForEachFrameListObject(frame, Offsets::OFF_FRAME_CHILD_LIST, fn);
Game::ForEachFrameListObject(frame, Offsets::OFF_FRAME_REGION_LIST, fn);
}
// ---- The state alpha animations change -----------------------------------------
uint8_t OwnAlpha(void *frame) { return Frame::Alpha::OwnAlpha(frame); }
void SetOwnAlpha(void *frame, uint8_t alpha) {
void **vtable = *static_cast<void ***>(frame);
reinterpret_cast<SetFrameAlpha_t>(vtable[Offsets::VTBL_FRAME_SET_FRAME_ALPHA / sizeof(void *)])(frame, nullptr,
alpha);
}
uint8_t DrawnParentAlpha(void *frame) {
void *parent = ParentOf(frame);
return parent != nullptr ? Game::Read<uint8_t>(parent, Offsets::OFF_FRAME_ALPHA) : 0xFF;
}
uint32_t VertexColor(void *region) {
uint32_t bgra = 0xFFFFFFFF;
reinterpret_cast<GetColor_t>(Offsets::FUN_REGION_GET_COLOR)(region, nullptr, &bgra);
return bgra;
}
// An unchanged alpha writes nothing. The setter already does nothing when the
// one entry it would store is the region's colour, but the getter reads a
// gradient back as white, and the setter shrinks a gradient's four entries to
// that one (benilla-re ui/texture, "Setting a vertex colour"). So restoring
// the stored alpha (PreOnAnimUpdate, AnimDeactivated) on a gradient under an
// ancestor's alpha group flattened it to white. 3.3.5's and 4.3.4's
// SetVertexColor drop the gradient there too; here only a region that an
// animation itself fades loses it. The ancestor's fade still reaches the
// gradient: a frame's alpha change refolds every region's entries (0x77FAC0).
void SetVertexAlpha(void *region, uint8_t alpha) {
const uint32_t color = VertexColor(region);
if ((color >> 24) == alpha)
return;
const uint32_t bgra = (color & 0x00FFFFFF) | (static_cast<uint32_t>(alpha) << 24);
reinterpret_cast<SetColor_t>(Offsets::FUN_FONTSTRING_SET_COLOR)(region, nullptr, &bgra);
}
// ---- The state position animations change --------------------------------------
float *Corners(void *texture) { return Game::Ptr<float>(texture, Offsets::OFF_SIMPLETEXTURE_CORNERS); }
// CSimpleTexture::SetPosition(m_rect, m_positions): the corners from the rect,
// written the way the texture's layout callback (FUN_TEXTURE_ON_FRAME_SIZE_CHANGED)
// writes them - cropped when SetTexCoordModifiesRect is on - so the corner
// store's co-hooks (Texture::Transform) shape them as they do on a layout.
void StoreTextureCorners(void *texture) {
float rect[4];
std::memcpy(rect, Game::Ptr<float>(texture, Offsets::OFF_REGION_RECT), sizeof(rect));
if (Game::Read<int>(texture, Offsets::OFF_REGION_TEXCOORD_MODIFIES_RECT) != 0)
reinterpret_cast<Crop_t>(Offsets::FUN_REGION_TEXCOORD_CROP)(texture, nullptr, rect);
reinterpret_cast<StoreCorners_t>(Offsets::FUN_REGION_STORE_CORNERS)(texture, nullptr, rect);
}
void *StringBlock(void *fontString) { return Game::Read<void *>(fontString, Offsets::OFF_FONTSTRING_TEXT_BLOCK); }
// Where the engine lays the string out: inset x layout scale + the rect's min
// corner (the position FUN_FONTSTRING_ON_FRAME_SIZE_CHANGED and SetTextOffset
// pass), as 4.3.4's StoreAnimPosition computes it.
void StringBase(void *fontString, float out[3]) {
const float *rect = Game::Ptr<const float>(fontString, Offsets::OFF_REGION_RECT);
const float scale = Game::Read<float>(fontString, Offsets::OFF_LAYOUT_SCALE);
out[0] = Game::Read<float>(fontString, Offsets::OFF_FONTSTRING_INSET_X) * scale + rect[1];
out[1] = Game::Read<float>(fontString, Offsets::OFF_FONTSTRING_INSET_Y) * scale + rect[0];
out[2] = 0.0f;
}
// TextBlockGetStringPos: the string node's position, back in DDC.
bool GetStringPos(void *block, float out[3]) {
const void *node = Game::Read<void *>(block, Offsets::OFF_TEXTBLOCK_NODE);
if (node == nullptr)
return false;
const float *position = Game::Ptr<const float>(node, Offsets::OFF_TEXT_NODE_POSITION);
reinterpret_cast<NdcToDdc_t>(Offsets::FUN_COORD_NDC_TO_DDC)(&out[0], &out[1], position[0], position[1]);
out[2] = position[2];
return true;
}
void SetStringPos(void *block, const float position[3]) {
reinterpret_cast<SetStringPos_t>(Offsets::FUN_TEXTBLOCK_SET_STRING_POS)(block, position);
}
// CSimpleTexture / CSimpleFontString::StoreAnimPosition.
void StoreAnimPosition(void *region, AnimData &data) {
if (IsTexture(region)) {
StoreTextureCorners(region);
std::memcpy(data.position, Corners(region), sizeof(data.position));
data.hasPosition = true;
} else if (IsFontString(region)) {
StringBase(region, data.position);
data.hasPosition = true;
}
}
void *StringNode(void *fontString) {
void *block = StringBlock(fontString);
return block != nullptr ? Game::Read<void *>(block, Offsets::OFF_TEXTBLOCK_NODE) : nullptr;
}
// GxuFontStringInvalidate after GxuFontSetRotation / GxuFontSetScale: the
// glyphs are baked again on the next paint, where FontStringBaked turns and
// scales them. Only when the values differ from the baked ones.
void RebakeIfChanged(void *fontString, const AnimData &data) {
if (data.rotation == data.bakedRotation && data.scale == data.bakedScale)
return;
if (void *node = StringNode(fontString))
reinterpret_cast<InvalidateNode_t>(Offsets::FUN_TEXT_NODE_INVALIDATE)(node);
}
// AnimData_ResetPositionData: the region goes back to where the layout puts it.
void ResetPosition(void *region, AnimData &data) {
data.hasPosition = false;
if (IsTexture(region)) {
StoreTextureCorners(region);
} else if (IsFontString(region)) {
// 4.3.4 leaves the string where the last update put it until the next
// layout; it goes back now, as the corners of a texture do.
if (void *block = StringBlock(region)) {
float base[3];
StringBase(region, base);
SetStringPos(block, base);
}
data.rotation = 0.0f;
data.scale = 1.0f;
RebakeIfChanged(region, data);
}
}
// CSimpleFrame / CSimpleRegion::AnimActivated.
void AnimActivated(void *region, bool alpha, bool position) {
const bool frame = IsFrame(region);
AnimData &data = g_data[region]; // AnimData_Init
if (alpha) {
data.hasAlpha = true;
data.alpha = frame ? OwnAlpha(region) : static_cast<uint8_t>(VertexColor(region) >> 24);
}
// A frame stores no position of its own, but it is marked, so the end of
// its last position group resets everything below it (NotifyEnd reads
// the mark), as the end of an alpha group does.
if (position) {
if (frame)
data.hasPosition = true;
else
StoreAnimPosition(region, data);
}
if (frame)
ForEachChild(region, [alpha, position](void *child) { AnimActivated(child, alpha, position); });
}
// CSimpleFrame / CSimpleRegion::AnimDeactivated.
void AnimDeactivated(void *region, bool alpha, bool position) {
const bool frame = IsFrame(region);
AnimData *data = DataOf(region);
if (alpha) {
const uint8_t stored = data != nullptr ? data->alpha : 0xFF; // AnimData_GetAlpha
if (frame) {
if (stored != OwnAlpha(region))
SetOwnAlpha(region, stored);
} else {
SetVertexAlpha(region, stored);
}
if (data != nullptr) {
data->hasAlpha = false;
data->alpha = 0xFF;
}
}
if (position && data != nullptr) {
if (frame)
data->hasPosition = false;
else
ResetPosition(region, *data);
}
if (frame)
ForEachChild(region, [alpha, position](void *child) { AnimDeactivated(child, alpha, position); });
}
// CScriptRegion::HasActiveAlphaAnim / HasActivePositionAnim: a playing group
// with that kind of animation on the region or an ancestor.
template <typename Has> bool HasActiveAnim(void *region, Has has) {
for (void *r = region; r != nullptr; r = ParentOf(r)) {
const State *state = Find(r);
if (state == nullptr)
continue;
for (const Group *group : state->playing)
if (has(group))
return true;
}
return false;
}
// ---- The update ----------------------------------------------------------------------
void UpdateGroups(void *region, float elapsed) {
State *state = Find(region);
if (state == nullptr)
return;
const std::vector<Group *> groups = state->groups;
for (Group *group : groups)
group->OnUpdate(elapsed);
}
void __fastcall FrameUpdate_h(void *frame, void *edx, float elapsed) {
g_origFrameUpdate(frame, edx, elapsed);
if (g_states.empty())
return;
UpdateGroups(frame, elapsed);
if (g_regionsWithGroups > 0)
Game::ForEachFrameListObject(frame, Offsets::OFF_FRAME_REGION_LIST,
[elapsed](void *region) { UpdateGroups(region, elapsed); });
// The font strings this update turned or scaled, or put back.
for (void *fontString : g_touchedStrings)
if (const AnimData *data = DataOf(fontString))
RebakeIfChanged(fontString, *data);
g_touchedStrings.clear();
}
const Game::HookAutoRegister _frameUpdateHook{Offsets::FUN_FRAME_ON_UPDATE, reinterpret_cast<void *>(&FrameUpdate_h),
reinterpret_cast<void **>(&g_origFrameUpdate)};
// ---- A layout during a position animation -----------------------------------------
//
// The layout writes the region's unanimated position. As in 4.3.4's
// OnFrameSizeChanged legs, the stored base becomes that new position and the
// drawn position keeps the animation's offset from it.
AnimData *PositionData(void *region) {
if (g_data.empty())
return nullptr;
AnimData *data = DataOf(region);
return data != nullptr && data->hasPosition ? data : nullptr;
}
void __fastcall TextureSizeChanged_h(void *layout, void *edx, const float *oldRect) {
void *texture = static_cast<char *>(layout) - Offsets::OFF_REGION_ANCHOR;
AnimData *data = PositionData(texture);
if (data == nullptr) {
g_origTextureSizeChanged(layout, edx, oldRect);
return;
}
float animated[12];
std::memcpy(animated, Corners(texture), sizeof(animated));
g_origTextureSizeChanged(layout, edx, oldRect);
float *corners = Corners(texture);
for (int i = 0; i < 12; ++i) {
const float base = corners[i];
corners[i] = animated[i] + (base - data->position[i]);
data->position[i] = base;
}
}
void __fastcall FontStringSizeChanged_h(void *layout, void *edx, const float *oldRect) {
void *fontString = static_cast<char *>(layout) - Offsets::OFF_REGION_ANCHOR;
AnimData *data = PositionData(fontString);
if (data == nullptr) {
g_origFontStringSizeChanged(layout, edx, oldRect);
return;
}
float animated[3];
void *before = StringBlock(fontString);
const bool hadString = before != nullptr && GetStringPos(before, animated);
g_origFontStringSizeChanged(layout, edx, oldRect);
float base[3];
StringBase(fontString, base);
void *block = StringBlock(fontString);
if (hadString && block != nullptr) {
float position[3];
for (int i = 0; i < 3; ++i)
position[i] = animated[i] + (base[i] - data->position[i]);
SetStringPos(block, position);
}
std::memcpy(data->position, base, sizeof(base));
}
const Game::HookAutoRegister _textureSizeHook{Offsets::FUN_TEXTURE_ON_FRAME_SIZE_CHANGED,
reinterpret_cast<void *>(&TextureSizeChanged_h),
reinterpret_cast<void **>(&g_origTextureSizeChanged)};
const Game::HookAutoRegister _fontStringSizeHook{Offsets::FUN_FONTSTRING_ON_FRAME_SIZE_CHANGED,
reinterpret_cast<void *>(&FontStringSizeChanged_h),
reinterpret_cast<void **>(&g_origFontStringSizeChanged)};
// ---- Lifetime ------------------------------------------------------------------------
void DestroyGroupsOf(void *region) {
const auto it = g_states.find(region);
if (it != g_states.end()) {
if (!it->second.groups.empty() && !IsFrame(region))
--g_regionsWithGroups;
const std::vector<Group *> groups = std::move(it->second.groups);
g_states.erase(it);
for (Group *group : groups)
delete group;
}
g_data.erase(region);
}
// The frame and its regions die here; its child frames run their own
// destructors.
void OnFrameDestroyed(void *frame) {
if (g_states.empty() && g_data.empty())
return;
Game::ForEachFrameListObject(frame, Offsets::OFF_FRAME_REGION_LIST, [](void *region) { DestroyGroupsOf(region); });
DestroyGroupsOf(frame);
}
const Frame::Destruction::AutoSubscribe _destructionSub{&OnFrameDestroyed};
// Groups on frames that outlived a /reload: their tables and handlers were
// in the old Lua state, so they are dropped without touching it.
void DropLeftovers() {
Object::s_detached = true;
for (auto &entry : g_states)
for (Group *group : entry.second.groups)
delete group;
Object::s_detached = false;
g_states.clear();
g_data.clear();
g_regionsWithGroups = 0;
}
// ---- Region methods (CScriptRegion_Scripts.cpp) -------------------------------------------
void StopAnimating(void *region) {
if (State *state = Find(region)) {
const std::vector<Group *> playing = state->playing;
for (Group *group : playing)
group->Stop(true);
}
// CSimpleFrame::StopAnimating: and everything below it.
if (IsFrame(region))
ForEachChild(region, [](void *child) { StopAnimating(child); });
}
int __fastcall Script_CreateAnimationGroup(void *L) {
void *region = Game::Lua::ResolveRegion(L);
if (region == nullptr)
return 0;
const char *name = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : nullptr;
const void *templateNode = nullptr;
if (Game::Lua::Type(L, 3) == Game::Lua::TYPE_STRING) {
const char *inherits = Game::Lua::ToString(L, 3);
templateNode = Xml::Template(inherits);
if (templateNode == nullptr) {
Game::Lua::Error(L, "%s:CreateAnimationGroup(): Couldn't find inherited node \"%s\"",
Game::Lua::ObjectDisplayName(region), inherits);
return 0;
}
}
Group *group = new Group(region, name);
if (templateNode != nullptr) {
Xml::LoadGroup(group, templateNode, nullptr);
group->PostLoadXML();
}
Push(L, group);
return 1;
}
int __fastcall Script_GetAnimationGroups(void *L) {
void *region = Game::Lua::ResolveRegion(L);
if (region == nullptr)
return 0;
const State *state = Find(region);
if (state == nullptr)
return 0;
const int count = static_cast<int>(state->groups.size());
if (!Game::Lua::CheckStack(L, count)) {
Game::Lua::Error(L, "%s:GetAnimationGroups(): Stack overflow", Game::Lua::ObjectDisplayName(region));
return 0;
}
for (Group *group : state->groups)
Push(L, group);
return count;
}
int __fastcall Script_StopAnimating(void *L) {
void *region = Game::Lua::ResolveRegion(L);
if (region != nullptr)
StopAnimating(region);
return 0;
}
const Game::Lua::FrameMethodEntry kRegionMethods[] = {
{"CreateAnimationGroup", &Script_CreateAnimationGroup},
{"GetAnimationGroups", &Script_GetAnimationGroups},
{"StopAnimating", &Script_StopAnimating},
};
const Game::Doc::Field kCreateArgs[] = {
Game::Doc::Opt("name", "string", nullptr, "The group's name; \"$parent\" is the region's."),
Game::Doc::Opt("templateName", "string", nullptr, "A virtual <AnimationGroup> to inherit."),
};
const Game::Doc::Field kCreateRets[] = {
Game::Doc::Req("animationGroup", "AnimationGroup"),
};
const Game::Doc::Field kGroupsRets[] = {
Game::Doc::Vararg("AnimationGroup", "Every animation group of the region, in creation order."),
};
const Game::Doc::Function kCreateAnimationGroup{"Creates an animation group on the region.", kCreateArgs,
kCreateRets};
const Game::Doc::Function kGetAnimationGroups{"Returns the region's animation groups.", {}, kGroupsRets};
const Game::Doc::Function kStopAnimating{
"Stops every playing animation group of the region and, for a frame, of everything inside it.", {}, {}};
const Game::Doc::Method kRegionDocs[] = {
{"CreateAnimationGroup", &kCreateAnimationGroup},
{"GetAnimationGroups", &kGetAnimationGroups},
{"StopAnimating", &kStopAnimating},
};
void RegisterLuaFunctions() {
DropLeftovers();
RegisterClass(Group::s_class);
RegisterClass(Anim::s_class);
RegisterClass(Anim::s_alphaClass);
RegisterClass(Anim::s_translationClass);
RegisterClass(Anim::s_scaleClass);
RegisterClass(Anim::s_rotationClass);
RegisterClass(Anim::s_pathClass);
RegisterClass(ControlPoint::s_class);
Game::Lua::RegisterFrameMethods(
reinterpret_cast<void *>(Offsets::VAR_REGION_METHOD_REGISTRY), kRegionMethods, kRegionDocs);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace
// ---- The CScriptRegion animation members ---------------------------------------------
void RegisterGroup(void *region, Group *group) {
State &state = g_states[region];
if (state.groups.empty() && !IsFrame(region))
++g_regionsWithGroups;
state.groups.push_back(group);
}
void NotifyBegin(void *region, Group *group) {
if (group == nullptr)
return;
State &state = g_states[region];
const AnimData *data = DataOf(region);
const bool alpha = !(data != nullptr && data->hasAlpha) && group->HasAlphaAnim();
const bool position = !(data != nullptr && data->hasPosition) && group->HasPositionAnim();
AnimActivated(region, alpha, position);
state.playing.push_back(group);
}
void NotifyEnd(void *region, Group *group) {
State *state = Find(region);
if (group == nullptr || state == nullptr)
return;
state->playing.erase(std::remove(state->playing.begin(), state->playing.end(), group), state->playing.end());
const AnimData *data = DataOf(region);
const bool alpha = data != nullptr && data->hasAlpha &&
!HasActiveAnim(region, [](const Group *g) { return g->HasAlphaAnim(); });
const bool position = data != nullptr && data->hasPosition &&
!HasActiveAnim(region, [](const Group *g) { return g->HasPositionAnim(); });
AnimDeactivated(region, alpha, position);
}
void PreOnAnimUpdate(void *region) {
const bool frame = IsFrame(region);
const AnimData *data = DataOf(region);
if (data != nullptr && data->hasAlpha) {
if (frame) {
if (data->alpha != OwnAlpha(region))
SetOwnAlpha(region, data->alpha);
} else {
SetVertexAlpha(region, data->alpha);
}
}
if (data != nullptr && data->hasPosition) {
if (IsTexture(region)) {
std::memcpy(Corners(region), data->position, sizeof(data->position));
} else if (IsFontString(region)) {
if (void *block = StringBlock(region))
SetStringPos(block, data->position);
// CSimpleFontString::PreOnAnimUpdate: back to the base rotation
// and scale.
AnimData *own = DataOf(region);
own->rotation = 0.0f;
own->scale = 1.0f;
g_touchedStrings.push_back(region);
}
}
if (frame)
ForEachChild(region, [](void *child) { PreOnAnimUpdate(child); });
}
void AddAnimTranslation(void *region, void *target, float x, float y) {
if (IsFrame(region)) {
// CSimpleFrame::AddAnimTranslation: the frame itself does not move;
// everything below it does, or only the target below it.
if (target == region)
target = nullptr;
ForEachChild(region, [target, x, y](void *child) { AddAnimTranslation(child, target, x, y); });
return;
}
if (target != nullptr && target != region)
return;
// Only a region whose base is stored: PreOnAnimUpdate puts it back before
// the next add, so nothing builds up.
const AnimData *data = DataOf(region);
if (data == nullptr || !data->hasPosition)
return;
if (IsTexture(region)) {
// ApplyTranslationAnim(m_positions, translation).
float *corners = Corners(region);
for (int i = 0; i < 4; ++i) {
corners[i * 3 + 0] += x;
corners[i * 3 + 1] += y;
}
} else if (void *block = StringBlock(region)) {
float position[3];
if (!GetStringPos(block, position))
return;
position[0] += x;
position[1] += y;
SetStringPos(block, position);
}
}
void AddAnimAlpha(void *region, void *target, int16_t alpha) {
if (IsFrame(region)) {
// CSimpleFrame::AddAnimAlpha: a target below the frame takes it.
if (target != nullptr && target != region) {
ForEachChild(region, [target, alpha](void *child) { AddAnimAlpha(child, target, alpha); });
return;
}
const uint8_t own = OwnAlpha(region);
const int value = alpha + static_cast<uint8_t>(own * DrawnParentAlpha(region) / 255);
const uint8_t newAlpha = static_cast<uint8_t>(value > 255 ? 255 : (value < 0 ? 0 : value));
if (newAlpha != own)
SetOwnAlpha(region, newAlpha);
return;
}
// CSimpleRegion::AddAnimAlpha.
if (target != nullptr && target != region)
return;
const int value = alpha + static_cast<int>(VertexColor(region) >> 24);
SetVertexAlpha(region, static_cast<uint8_t>(value > 255 ? 255 : (value < 0 ? 0 : value)));
}
void SetAnimAlpha(void *region, void *target, uint8_t alpha) {
if (IsFrame(region)) {
if (target != nullptr && target != region) {
ForEachChild(region, [target, alpha](void *child) { SetAnimAlpha(child, target, alpha); });
return;
}
if (alpha != OwnAlpha(region))
SetOwnAlpha(region, alpha);
return;
}
if (target != nullptr && target != region)
return;
SetVertexAlpha(region, alpha);
}
void KeepAnimAlpha(void *region, void *target) {
void *shown = target != nullptr ? target : region;
AnimData *data = DataOf(shown);
if (data != nullptr && data->hasAlpha)
data->alpha = IsFrame(shown) ? OwnAlpha(shown) : static_cast<uint8_t>(VertexColor(shown) >> 24);
}
namespace {
// The corners (TL, BL, TR, BR) as 2D points.
float CornerX(const float *corners, int i) { return corners[i * 3 + 0]; }
float CornerY(const float *corners, int i) { return corners[i * 3 + 1]; }
// GetOriginOffset (4.3.4 CSimpleRegion.cpp): the origin point on the drawn
// quad, then the offset along the quad's bottom edge direction, so the
// offset turns with a quad that is already turned.
void GetOriginOffset(int origin, const float *c, float offsetX, float offsetY, float &x, float &y) {
const auto mid = [c](int a, int b, float &mx, float &my) {
mx = (CornerX(c, b) - CornerX(c, a)) * 0.5f + CornerX(c, a);
my = (CornerY(c, b) - CornerY(c, a)) * 0.5f + CornerY(c, a);
};
switch (origin) {
case Offsets::FRAMEPOINT_TOPLEFT: x = CornerX(c, 0); y = CornerY(c, 0); break;
case Offsets::FRAMEPOINT_TOP: mid(0, 2, x, y); break;
case Offsets::FRAMEPOINT_TOPRIGHT: x = CornerX(c, 2); y = CornerY(c, 2); break;
case Offsets::FRAMEPOINT_LEFT: mid(0, 1, x, y); break;
case Offsets::FRAMEPOINT_CENTER: mid(0, 3, x, y); break;
case Offsets::FRAMEPOINT_RIGHT: mid(2, 3, x, y); break;
case Offsets::FRAMEPOINT_BOTTOMLEFT: x = CornerX(c, 1); y = CornerY(c, 1); break;
case Offsets::FRAMEPOINT_BOTTOM: mid(1, 3, x, y); break;
case Offsets::FRAMEPOINT_BOTTOMRIGHT: x = CornerX(c, 3); y = CornerY(c, 3); break;
default: x = 0.0f; y = 0.0f; break;
}
if (offsetX * offsetX + offsetY * offsetY > 0.00000011920929f) {
float dx = CornerX(c, 3) - CornerX(c, 1);
float dy = CornerY(c, 3) - CornerY(c, 1);
const float length = dy * dy + dx * dx;
if (length > 0.00000023841858f) {
const float scale = 1.0f / std::sqrt(length);
dx *= scale;
dy *= scale;
}
x = offsetX * dx - offsetY * dy + x;
y = offsetY * dx + offsetX * dy + y;
}
}
// The font string that takes a position animation, or nullptr.
AnimData *AnimatedString(void *region, void *target) {
if (target != nullptr && target != region)
return nullptr;
AnimData *data = DataOf(region);
if (data == nullptr || !data->hasPosition || !IsFontString(region))
return nullptr;
return data;
}
// The texture that takes a position animation (the target filter of the
// region overrides), or nullptr.
float *AnimatedCorners(void *region, void *target) {
if (target != nullptr && target != region)
return nullptr;
const AnimData *data = DataOf(region);
if (data == nullptr || !data->hasPosition || !IsTexture(region))
return nullptr;
return Corners(region);
}
} // namespace
void AddAnimScale(void *region, void *target, int origin, float offsetX, float offsetY, float x, float y) {
if (IsFrame(region)) {
// CSimpleFrame::AddAnimScale.
if (target == region)
target = nullptr;
ForEachChild(region, [=](void *child) { AddAnimScale(child, target, origin, offsetX, offsetY, x, y); });
return;
}
// CSimpleFontString::AddAnimScale: the text grows from its origin by the
// x scale; the last scale animation of the update wins.
if (AnimData *data = AnimatedString(region, target)) {
data->scale = 1.0f - x;
return;
}
// CSimpleTexture::AddAnimScale -> ApplyScaleAnim.
float *c = AnimatedCorners(region, target);
if (c == nullptr)
return;
float cx, cy;
GetOriginOffset(origin, c, offsetX, offsetY, cx, cy);
for (int i = 0; i < 4; ++i) {
c[i * 3 + 0] = (cx - c[i * 3 + 0]) * x + c[i * 3 + 0];
c[i * 3 + 1] = (cy - c[i * 3 + 1]) * y + c[i * 3 + 1];
}
}
void AddAnimRotation(void *region, void *target, int origin, float offsetX, float offsetY, float radians) {
if (IsFrame(region)) {
// CSimpleFrame::AddAnimRotation.
if (target == region)
target = nullptr;
ForEachChild(region, [=](void *child) { AddAnimRotation(child, target, origin, offsetX, offsetY, radians); });
return;
}
// CSimpleFontString::AddAnimRotation: the text turns about its origin;
// the last rotation animation of the update wins.
if (AnimData *data = AnimatedString(region, target)) {
data->rotation = radians;
return;
}
// CSimpleTexture::AddAnimRotation -> ApplyRotationAnim.
float *c = AnimatedCorners(region, target);
if (c == nullptr)
return;
float cx, cy;
GetOriginOffset(origin, c, offsetX, offsetY, cx, cy);
const float cs = std::cos(radians);
const float sn = std::sin(radians);
for (int i = 0; i < 4; ++i) {
const float x = c[i * 3 + 0] - cx;
const float y = c[i * 3 + 1] - cy;
c[i * 3 + 0] = x * cs - y * sn + cx;
c[i * 3 + 1] = x * sn + y * cs + cy;
}
}
void FontStringBaked(void *node, void *fontString) {
if (g_data.empty())
return;
AnimData *data = DataOf(fontString);
if (data == nullptr)
return;
if (data->rotation != 0.0f || data->scale != 1.0f)
Texture::Transform::ScaleRotateFontStringNode(node, data->scale, data->rotation);
data->bakedRotation = data->rotation;
data->bakedScale = data->scale;
}
float *TextureBaseCorners(void *texture) {
if (g_data.empty())
return nullptr;
AnimData *data = DataOf(texture);
return data != nullptr && data->hasPosition && IsTexture(texture) ? data->position : nullptr;
}
bool StringAnimated(void *fontString) {
if (g_data.empty())
return false;
const AnimData *data = DataOf(fontString);
return data != nullptr && (data->rotation != 0.0f || data->scale != 1.0f || data->bakedRotation != 0.0f ||
data->bakedScale != 1.0f);
}
void *FindRegionByName(const char *name) {
void *L = Game::Lua::State();
if (L == nullptr || name == nullptr)
return nullptr;
Game::Lua::PushString(L, name);
Game::Lua::RawGet(L, Game::Lua::GLOBALS_INDEX);
void *object = Game::Lua::Type(L, -1) == Game::Lua::TYPE_TABLE ? Game::Lua::ResolveObject(L, -1) : nullptr;
Game::Lua::SetTop(L, -2);
if (object == nullptr || IsOurs(object) || !Game::Lua::IsA(object, Offsets::VAR_REGION_LUA_TYPE_ID))
return nullptr;
return object;
}
// The leading `$parent` steps that stay among our objects (an animation to
// its group, a group to its region) are taken here; the rest of the path,
// from that region, is the one Xml::Anchors resolves for relativeKey.
void *FindRegionByKey(Object *from, const char *path) {
if (from == nullptr || path == nullptr)
return nullptr;
void *current = from;
const char *p = path;
while (current != nullptr && IsOurs(current)) {
const char *dot = std::strchr(p, '.');
const std::string part = dot != nullptr ? std::string(p, dot) : std::string(p);
if (Game::StrCmpI(part.c_str(), "$parent") != 0)
return nullptr; // a key on a group or animation names no region
current = static_cast<Object *>(current)->parent;
p = dot != nullptr ? dot + 1 : p + part.size();
}
if (current == nullptr)
return nullptr;
if (*p != '\0')
current = ::Xml::Anchors::ResolveKeyPath(current, p, false);
if (current == nullptr || IsOurs(current) || !Game::Lua::IsA(current, Offsets::VAR_REGION_LUA_TYPE_ID))
return nullptr;
return current;
}
} // namespace Animation::Region
+73
View File
@@ -0,0 +1,73 @@
// 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
#include <cstdint>
// The region side of the animation system: 4.3.4's CScriptRegion animation
// members (m_animGroups, m_playingAnimGroups, the CLayoutFrame animation
// data) and their virtuals on CSimpleFrame and CSimpleRegion, for 1.12's
// frames, textures and font strings, which have no room for them.
namespace Animation {
class Group;
class Object;
}
namespace Animation::Region {
// CScriptRegion::RegisterAnimGroup - the region owns the group from now on.
void RegisterGroup(void *region, Group *group);
// CScriptRegion::NotifyAnimBegin / NotifyAnimEnd.
void NotifyBegin(void *region, Group *group);
void NotifyEnd(void *region, Group *group);
// CScriptRegion::PreOnAnimUpdate: put the animated state back to its base
// before the animations apply themselves for this update.
void PreOnAnimUpdate(void *region);
// CScriptRegion::AddAnimAlpha(target, alpha) on the group's region.
void AddAnimAlpha(void *region, void *target, int16_t alpha);
// Later clients' absolute alpha (Alpha fromAlpha / toAlpha): the same target
// rule as AddAnimAlpha, but the alpha becomes `alpha` instead of growing.
void SetAnimAlpha(void *region, void *target, uint8_t alpha);
// AnimationGroup setToFinalAlpha: the alpha that `target` (the group's
// `region` when null) shows now becomes the one the group's end restores.
void KeepAnimAlpha(void *region, void *target);
// CScriptRegion::AddAnimTranslation(target, translation), in layout units:
// moves the drawn textures and font strings, never a rect.
void AddAnimTranslation(void *region, void *target, float x, float y);
// CScriptRegion::AddAnimScale(target, origin, offset, scale): `x`/`y` are the
// share of the way to the origin (1 - scale at full progress).
void AddAnimScale(void *region, void *target, int origin, float offsetX, float offsetY, float x, float y);
// CScriptRegion::AddAnimRotation(target, origin, offset, radians),
// counter-clockwise.
void AddAnimRotation(void *region, void *target, int origin, float offsetX, float offsetY, float radians);
// A font string's glyphs were just baked (the draw builder): turn and scale
// them by its animation, and remember what they were baked with.
void FontStringBaked(void *node, void *fontString);
// The stored corners (TL BL TR BR {x, y, z}) of a texture a position group
// is playing on, or nullptr. Each update draws the animation on top of them,
// so a change to the texture's own shape (Texture::Transform) goes here, not
// to the drawn corners.
float *TextureBaseCorners(void *texture);
// Whether the font string's glyphs carry an animation's rotation or scale:
// then a change to its own rotation has to bake them again.
bool StringAnimated(void *fontString);
// CScriptObject::GetScriptObjectByName for a region (Animation:Play's
// target lookup): the region named `name`, or nullptr.
void *FindRegionByName(const char *name);
// The region a later-client targetKey path names, read from `from`: each
// dot-separated part is `$parent` (the object's parent) or a key on the
// current object's table. Nullptr unless the path ends on a region.
void *FindRegionByKey(Object *from, const char *path);
} // namespace Animation::Region

Some files were not shown because too many files have changed in this diff Show More