mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-17 00:16:02 +00:00
* docs(container): describe the C_Container functions
Descriptors for the 17 undocumented C_Container functions and the
ItemQuestInfo structure. SwapItems, MoveItem, AutoStoreItem,
GetContainerItemCharges, GetContainerItemRepairCost and
IsContainerItemOpenable are not in retail's API and are marked as
ClassicAPI extensions.
* docs(aura): describe the C_UnitAuras functions
Descriptors for the 16 undocumented C_UnitAuras functions, plus the
AuraData structure that GetAuraDataByAuraInstanceID already named but
nothing defined. The four positional getters share the Classic Era
UnitAura return list.
* docs(equipmentset): describe the C_EquipmentSet functions
Descriptors for the 18 undocumented C_EquipmentSet functions,
GameTooltip:SetEquipmentSet, and the EQUIPMENT_SETS_CHANGED,
EQUIPMENT_SWAP_PENDING and EQUIPMENT_SWAP_FINISHED events. They
describe what the functions return here, which differs from retail in
places: an icon path, not a file ID; numMissing, not numLost;
GetIgnoredSlots lists slot numbers.
* docs(faction): describe the reputation functions
Descriptors for GetFactionIDByIndex, GetFactionInfoByID,
GetFactionParentID, the 17 undocumented C_Reputation functions, the
FactionData structure, and the FACTION_STANDING_CHANGED event.
C_Reputation.IsFactionInactive and SetFactionInactive mirror stock
globals, but no Blizzard client has them under C_Reputation, so they
are marked as ClassicAPI extensions.
* docs(player): describe the player functions and events
Descriptors for C_PlayerInfo.CanUseItem, GetName, GetClass, GetRace,
GetSex and IsConnected; GetPlayerFacing, GetPlayerInfoByGUID,
UnitNameFromGUID and IsLoggedIn; the four C_PlayerCache functions; and
the PLAYER_EQUIPMENT_CHANGED, UPDATE_INVENTORY_DURABILITY,
HEARTHSTONE_BOUND and six PLAYER_STARTED/STOPPED_MOVING, LOOKING and
TURNING events. They describe what the functions return here: sex is 2
or 3, not the UnitSex enum, and GetPlayerInfoByGUID has no level.
C_PlayerCache is ours, so its functions are marked as extensions.
GetCritChance and GetRangedCritChance move from system "PaperDollInfo"
to "PlayerGlobals": PaperDollInfo is the C_PaperDollInfo namespace's
system, and a global must not share it.
* docs(map): describe the C_Map functions
Descriptors for the 30 undocumented C_Map and C_MapExplorationInfo
functions, the UiMapDetails, UiMapLayerInfo, UiMapPoint,
AreaTriggerInfo, MapOverlayInfo and MapOverlayTile structures, and the
USER_WAYPOINT_UPDATED event. mapType is a plain number because no
Enum.UIMapType is registered, and flags is always 0. GetAreaTriggerInfo,
GetAreaTriggers, GetAreas, GetMapAreaIDs, GetMapOverlays and
GetUnexploredMapTextures are marked as ClassicAPI extensions.
* docs(loot): describe the C_Loot and C_LootHistory functions
Descriptors for the six C_Loot functions and the four C_LootHistory
functions, the LootableUnit, ScannedCorpse and ScannedLootItem
structures, and the LOOT_SCAN_COMPLETED and three LOOT_HISTORY_* events.
Every C_Loot function here and C_LootHistory.Clear are marked as
ClassicAPI extensions; Blizzard's C_Loot has none of them.
* docs(sound): describe the sound functions
Descriptors for the six undocumented C_Sound functions, the PlaySound,
PlaySoundFile, StopSound, MuteSoundFile and UnmuteSoundFile globals, the
PlaySoundParams and RecentSoundFile structures, the ItemSoundType and
Vocalerrorsounds enums, and the SOUNDKIT_FINISHED event.
C_Sound.PlaySound's second argument is documented as the channel name it
takes here, not retail's UISoundSubType. GetRecentSoundFiles is marked as
a ClassicAPI extension.
* docs(console): describe the console functions
Descriptors for ConsoleExec, ConsoleEcho, ConsoleIsActive,
ConsoleGetColorFromType, ConsoleGetFontHeight, SetConsoleKey,
CalculateStringEditDistance, ConsoleGetAllCommands and
ConsolePrintAllMatchingCommands, the ConsoleCommandInfo structure, and
the ConsoleCommandType and ConsoleCategory enums. The game and glue
registrations of each function share one descriptor. ConsoleExec and
ConsoleEcho return nothing here, and SetConsoleKey takes a key code.
* docs(voicechat): describe the text-to-speech functions
Descriptors for the four C_VoiceChat text-to-speech functions, the ten
C_TTSSettings functions, the VoiceTtsVoiceType structure, and the five
VOICE_CHAT_TTS_* events. The event payloads follow the shapes the
client sends here. GetSpeechVoiceID, SetVoiceOptionByName and
RefreshVoices are marked as ClassicAPI extensions.
* docs(api): correct entries that drifted from the code
Fixes entries that the descriptor pass found to differ from what the
functions do: C_PlayerInfo.GetSex never returns 1, the name and race
getters need a visible unit for unit locations too, RememberPlayer
raises on missing arguments, mutes outlive a reload, scan results fill
in during a scan, LootHistory names can be nil and ROLL_CHANGED can
carry playerIndex 0, GetMapRectOnMap's fallback and Kalimdor ID, dungeon
maps have no parent, and GetBestMapForUnit gives zones, not subzones.
HEARTHSTONE_BOUND and the player input-state events now describe only
their behavior; the packet handlers, engine addresses and hook notes
are gone.
* docs(loot): say when LOOT_HISTORY_FULL_UPDATE fires
The comment above the loot-history event names said FULL_UPDATE was
never fired from C++, but FireFullUpdate sends it when a roll opens a
new item, when the 128-item ring evicts the oldest entry, and from
C_LootHistory.Clear.
* docs(api): describe behavior, not implementation
API.md is the contract for addon authors, so it no longer names engine
addresses, struct offsets, internal type and field names, packet
opcodes, hook mechanics, source files or our C++ modules, and drops
provenance notes and remarks about which client version lacks what.
Where that text carried a real behavior, the behavior stays in plain
words: "when the server answers" in place of an opcode, "ignores the
merchant and repair cursor modes" in place of the function it skips.
Also: C_Spell.GetSpellPowerCost no longer calls GetSpellInfo's cost the
base cost (both are the effective cost), the C_Spell cast-info note no
longer calls the functions player-only, the name-cache intro says the
game empties its cache on each world entry, and examples use a generic
realm name.
* docs(item): describe the item functions
Descriptors for the 95 undocumented item registrations: the C_Item
readers, lock, use and equip calls, the GetItemInfo family, the
Get*ItemID companions, the GameTooltip item methods, the ItemData,
ItemSetInfo and ItemEnchantInfo structures, the InventoryType,
ItemClass and ItemQuality enums, and the ITEM_DATA_LOAD_RESULT and
GET_ITEM_INFO_RECEIVED events. They describe what the functions return
here where it differs from retail: GetItemSetInfo returns a table,
GetWeaponEnchantInfo returns twelve values, and RequestLoadItemData
returns whether the request went out. GetItemIDForItemInfo's return is
now optional, since input that names no item returns nothing.
* docs(unit): describe the unit functions
Descriptors for the 49 undocumented unit functions, the PowerType enum,
and the PLAYER_FOCUS_CHANGED and UPDATE_SHAPESHIFT_FORM events. They
describe what the functions do here: UnitHealthMissing has no
usePredicted argument, IsFalling and IsSwimming take no unit,
UnitPowerType returns no color, and UnitPosition keeps its Y-first
return order.
* docs(baselib): describe the Lua library additions
Descriptors for the Lua 5.1 functions added to the game's Lua: select,
unpack with a range, xpcall with arguments, collectgarbage options,
debugstack, the math hyperbolics, fmod and modf, string.match, gmatch,
reverse, byte, split, join and trim with their global aliases, and
strreplace, plus Mixin and CreateFromMixins. strreplace is the one
ClassicAPI extension; retail binds the other aliases itself.
* docs(api): correct entries the item and unit descriptors contradicted
UnitIsMinion, UnitIsPet and UnitIsOtherPlayersPet raise on a string that
is not a unit token; only a token that names no unit, or a non-string,
returns false. GetItemCooldown does not take item names. A full request
queue makes RequestLoadItemData return false. GetInventoryItemID needs a
player, so pets and totems return nil. GetItemNameByID keeps a link's
random suffix. GetInventoryItemRepairCost raises on a non-number slot.
The Get*ItemID intro no longer calls the companions stock functions.
Also settles two entries that contradicted themselves: the summoning
ritual's channel events do fire, and GetSecondsUntilDailyReset counts to
UTC midnight. C_PlayerInfo.UnitPosition gets a line under UnitPosition.
* fix(docs): map the remaining widget method registries to systems
Methods registered on the Button, Slider, StatusBar, MessageFrame,
SimpleHTML, ScrollingMessageFrame, PlayerModel and DressUpModel
registries had descriptors, but the browser listed them as an unmapped
registry. The five Blizzard has use its names (SimpleButtonAPI and so
on); the other three are named the same way.
* docs(ui): describe the frame, texture and input functions
Descriptors for the texture, region, frame, button, editbox and tooltip
methods ClassicAPI adds, the C_Texture atlas, C_XMLUtil, C_ColorUtil,
C_UIColor and C_NamePlate functions, the binding, modifier-key, cursor
and screen globals, the AtlasInfo, XML template and DBColorExport
structures, Enum.UICursorType, and the nameplate, cursor and
MODIFIER_STATE_CHANGED events. IsMouseButtonDown, GetMouseButtonName and
GetCursorDelta move to the InputGlobals system.
* docs(spell): describe the spell, action and creature functions
Descriptors for the remaining spell, spellbook, tracking, action bar,
talent, totem, loss-of-control, macro, combat, tradeskill, targeting,
GUID, class, C_CreatureInfo and C_GameObjectInfo registrations, their
structures, and the LEARNED_SPELL_IN_SKILL_LINE, PLAYER_TOTEM_UPDATE,
LOSS_OF_CONTROL_*, CREATURE_DATA_LOAD_RESULT and
GAMEOBJECT_DATA_LOAD_RESULT events. The IsItemAction,
HasBonusActionBar and IsStackableAction globals move from the
C_ActionBar system to ActionBarGlobals.
* docs(world): describe the gossip, quest, social and vendor functions
Descriptors for C_GossipInfo, the friends and /who functions, C_QuestLog
and the quest globals, C_TaxiMap, C_MerchantFrame, C_AuctionHouse.PostItem,
the mail, group, instance, coin-text, chat, character-order and
expansion globals, their structures, the FlightPath enums, and the
QUEST_DATA_LOAD_RESULT and AUCTION_MULTISELL_* events. Globals that
named a namespaced system (QuestLog, PartyInfo, CurrencyInfo) move to
the matching *Globals system, and GetCoinText gets separate global and
C_CurrencyInfo descriptors.
* docs(lua): describe the cvar, encoding, time, addon and Lua functions
Descriptors for the cvar, C_EncodingUtil, C_DateAndTime, C_Timer,
C_AddOns, coroutine, table, security-account, event, script, clipboard
and hooksecurefunc registrations, the CalendarTime and SavedAccountInfo
structures, and the Base64Variant, CompressionMethod and
AddOnSecurityStatus enums.
* docs(api): correct entries the last descriptor pass contradicted
SelectOption takes an optional password for boxCoded options.
IsWhoQueryPending clears when the answer arrives, not after a timer, and
SendWhoQueryByName raises on a nil or non-string name. SetTalentByID
raises on a nil or non-number talentID. The gossip getters also read the
quest greeting window. GetPoint returns three values for an anchor with
no relative frame. RegisterAtlas's rectangle is optional.
GetSecondsUntilDailyReset returns nothing before login.
CopyToClipboard is a Blizzard function, not an extension, and always
returns the length. ConvertHSLToRGB, DoesTemplateExist,
GetNamePlateForGUID, GetNamePlateGUIDs and SetModernScriptArgs are
labelled as ClassicAPI extensions, and C_AuctionHouse.PostItem is
described as retail's function plus a numStacks argument.
IsAddOnLoadable's descriptor notes the nil reason for an unknown name.
* docs: start every function and event summary with a verb
Function summaries now read "Returns …", "Returns whether …" and so on,
not a bare "Whether …", "The …" or "How many …", and event summaries
read "Fires when …" instead of describing the past ("A cast ended").
A few two-sentence summaries become one sentence, and the two range
check toggles say what they do rather than "Used with …".
* refactor(lua): require a descriptor on every registration
The registrars and Event::Custom::AutoReserve no longer default their
doc argument, so a function, method table, enum, alias or custom event
registered without a descriptor does not compile. The _classicapi_
debug functions, which the documentation export skips, pass nullptr
explicitly.
* docs: stop calling namespaced Blizzard globals extensions
A function is a ClassicAPI extension only when no Blizzard client ships
it under any name. C_XMLUtil.DoesTemplateExist (the global
DoesTemplateExist), C_PlayerInfo.UnitPosition, C_Reputation.
IsFactionInactive and SetFactionInactive, and C_Macro.CreateMacro and
EditMacro are Blizzard globals under a namespace Blizzard never gave
them, so their descriptors and API.md no longer label them extensions.
* refactor(baselib): register newproxy through the registrars
newproxy set its global by hand so its C closure could carry the weak
table of valid metatables as an upvalue, which left it the one global
with no descriptor. The weak table now lives in the registry (made on
first use in each Lua state), so newproxy is a plain C function that
RegisterGlobalFunction and RegisterGlueFunction bind with a descriptor.
Behavior is unchanged.
* docs(api): drop the C++ module name from the aura timing heading
* docs(api): fix descriptor errors found in review
- UnitSpellTargetName is a Blizzard function (Unit system): drop the
extension flag and file it under UnitGlobals.
- Flag the ClassicAPI-only spell functions as extensions: GetSpellRadius
(global and C_Spell), GetSpellReagents, GetSpellDispelType,
IsNextMeleeSpell, ResetsMeleeSwing, GetSpellMechanicByID,
GetSpellEffectMechanics, GetSpellEffectInfo, GetSpellRequiredTargetLevel,
GetSpellLevelInfo and C_SpellBook.GetPlayerSpellsByAura. No Blizzard
client ships any of them.
- Name the Region registry SimpleScriptRegionAPI, as retail does, and
make the no-counterpart comment cover all three rows it applies to.
- Start the VOICE_CHAT_TTS_SPEAK_TEXT_UPDATE summary with a verb.
- Type GetCurrentChatEvent's guid return as WOWGUID, matching
GetCurrentChatGUID.
- Say that the itemInfo argument also accepts an item string.
* docs(api): document the methods the source count missed
_classicapi_UndocumentedAPI() still listed 23 names. Each sat in a method
array that already had a partial doc array, so the source count read it
as documented.
- GameTooltip: SetUnitAura, SetUnit, GetUnit, GetUnitGUID, HasUnit.
GetUnitGUID and HasUnit are extensions; no Blizzard client ships them.
- FontString: GetStringHeight, GetUnboundedStringWidth, GetWrappedWidth,
GetNumLines, GetLineHeight, IsTruncated, SetMaxLines, GetMaxLines,
GetFieldSize.
- ModelScene actor: GetObjectType, IsObjectType, GetName, GetParent,
HasScript, GetScript, SetScript, HookScript, as our object methods
return them (1/nil, no HookScript result).
- GetAverageItemLevel moves to PaperDollInfoGlobals: PaperDollInfo is the
C_PaperDollInfo namespace.
The in-game check now reports 0.
825 lines
40 KiB
C++
825 lines
40 KiB
C++
// 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 <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);
|
|
}
|
|
|
|
// An engine constant at a fixed VA, read each time it is used, so the value is
|
|
// the one the engine's own code reads: a runtime patch shows, and so does a
|
|
// global the engine's static initializers fill after this DLL loads. Converts
|
|
// to T, so it stands in a float expression as a float would.
|
|
//
|
|
// const Game::Live<float> kSkin{Offsets::VAR_MOVER_SKIN};
|
|
template <typename T>
|
|
struct Live {
|
|
uintptr_t address;
|
|
operator T() const { return Read<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]
|
|
// * [FLOAT_SCRIPT_COORD_SCALE])`; every script coordinate push (GetLeft,
|
|
// GetStringWidth, GetFont's height, GetCursorPosition, OnCursorChanged) is the
|
|
// inverse, `DivideByScreenScaleX(GetScaledScreenAspect() * 1024 * value)`,
|
|
// which InternalToPixel calls in that order. 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 *)();
|
|
|
|
// Master glue Lua-state init function. `__stdcall` (no args, no return).
|
|
// Hooked to inject our own glue-side globals after the engine finishes
|
|
// 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. Lua's own spelling is wrong here: "bool", never
|
|
// "boolean".
|
|
// - `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);
|
|
|
|
// Lua 5.0 pseudo-index used to read/write entries on the globals table.
|
|
constexpr int GLOBALS_INDEX = -10001;
|
|
// Lua 5.0 pseudo-index for the registry table — a Lua-state-local
|
|
// table protected from script code, used by C modules to anchor
|
|
// values across calls (e.g. timer callbacks pinned against GC).
|
|
constexpr int REGISTRY_INDEX = -10000;
|
|
// LUA_UPVALUEINDEX(i) — pseudo-index for accessing the i-th upvalue
|
|
// of a C closure. Lua 5.0 layout: `LUA_GLOBALSINDEX - i`.
|
|
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_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;
|
|
constexpr int TYPE_NUMBER = 3;
|
|
constexpr int TYPE_STRING = 4;
|
|
constexpr int TYPE_TABLE = 5;
|
|
constexpr int TYPE_FUNCTION = 6;
|
|
constexpr int TYPE_USERDATA = 7;
|
|
constexpr int TYPE_THREAD = 8;
|
|
|
|
using lua_isnumber_t = bool(__fastcall *)(void *L, int index);
|
|
using lua_isstring_t = bool(__fastcall *)(void *L, int index);
|
|
using lua_tonumber_t = double(__fastcall *)(void *L, int index);
|
|
using lua_toboolean_t = int(__fastcall *)(void *L, int index);
|
|
using lua_tostring_t = const char *(__fastcall *)(void *L, int index);
|
|
using lua_strlen_t = unsigned int(__fastcall *)(void *L, int index);
|
|
using lua_pushnumber_t = void(__fastcall *)(void *L, double n);
|
|
using lua_pushnil_t = void(__fastcall *)(void *L);
|
|
using lua_pushboolean_t = void(__fastcall *)(void *L, int b);
|
|
using lua_pushstring_t = void(__fastcall *)(void *L, const char *s);
|
|
using lua_pushlstring_t = void(__fastcall *)(void *L, const char *s, unsigned int len);
|
|
using lua_pushvalue_t = void(__fastcall *)(void *L, int idx);
|
|
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
|
|
// is fine because cdecl tolerates extra-arg-less calls. New callers
|
|
// forwarding user-supplied error strings should use `Error(L, "%s",
|
|
// userMsg)` to avoid format-string interpretation of `%` in the
|
|
// message body.
|
|
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.
|
|
// We declare the return type honestly here; callers that don't want
|
|
// to rely on the calling convention preserving eax can read the
|
|
// thread back from L's top via `ToPointer(L, -1)`.
|
|
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;
|
|
extern const lua_tonumber_t ToNumber;
|
|
extern const lua_toboolean_t ToBoolean;
|
|
extern const lua_tostring_t ToString;
|
|
extern const lua_strlen_t StrLen;
|
|
extern const lua_pushnumber_t PushNumber;
|
|
extern const lua_pushnil_t PushNil;
|
|
extern const lua_pushboolean_t PushBoolean;
|
|
// Convenience overload — takes a real `bool` so callers don't have to
|
|
// `static_cast<int>(...)` or `condition ? 1 : 0` at every site. The
|
|
// 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;
|
|
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.
|
|
void *State();
|
|
|
|
// Resolves a Lua-side frame/object table at stack index `idx` to its
|
|
// underlying `CFrameScriptObject *`. Mirrors the standard prologue
|
|
// of the engine's own `Set*` frame methods — pushes the object via
|
|
// `FrameScript_PushObject`, reads it back as a pointer via
|
|
// `FrameScript_GetObject`, then balances the stack. Returns nullptr
|
|
// if the slot isn't a CObject (table, light-userdata, or userdata
|
|
// types are accepted by the engine resolver). Callers pass `1` for
|
|
// 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). It has no default, so a registration without one does not
|
|
// compile; only the `_classicapi_` debug functions, which the export skips,
|
|
// pass `nullptr`.
|
|
|
|
// 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, const Doc::Function *doc);
|
|
|
|
// Glue-state equivalent of `RegisterGlobalFunction`. Identical wire
|
|
// (calls `FrameScript_RegisterFunction`); the engine routes the
|
|
// registration to whichever Lua state `VAR_LUA_STATE` currently
|
|
// references. Only safe to call from inside a `GlueModuleAutoRegister`
|
|
// callback — at that point the engine has just finished registering
|
|
// 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, const Doc::Function *doc);
|
|
|
|
// Frame-method registration entry: { name, func } pairs walked by the engine's
|
|
// per-frame-type method-table iterator. Layout matches what the engine expects
|
|
// natively — name first, then function pointer.
|
|
struct FrameMethodEntry {
|
|
const char *name;
|
|
CFunction func;
|
|
};
|
|
|
|
// 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. `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, const Doc::Function *doc);
|
|
|
|
// 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);
|
|
|
|
// 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;
|
|
};
|
|
|
|
// 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.
|
|
// `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);
|
|
|
|
// 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).
|
|
// Pushes the key + value, calls `SetTable(L, -3)`, which pops both and
|
|
// leaves the table on the stack — so it's safe to chain. NULL string
|
|
// values are coerced to `""` so callers don't have to gate each push.
|
|
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
|
|
// no `__newindex` in vanilla 1.12 — explicit intent and skips a dead
|
|
// metatable check. Used for flat constant globals like
|
|
// `CLASSIC_API_VERSION` and the `LE_ITEM_QUALITY_*` family.
|
|
void SetGlobalNumber(void *L, const char *name, double value);
|
|
|
|
// Pushes `_G[globalName]` onto the stack if it resolves to a string
|
|
// (Blizzard's FrameXML globals like `ITEMS_EQUIPPED`, addon-defined
|
|
// localization tables, etc.); otherwise pushes `fallback`. Either way
|
|
// leaves exactly one string at the top of the stack. The canonical
|
|
// pattern is "look up a localized format string with an English
|
|
// fallback for stripped servers / pre-init states":
|
|
//
|
|
// Game::Lua::PushLocalizedString(L, "ITEMS_EQUIPPED", "%d equipped");
|
|
// Game::Lua::PushNumber(L, count);
|
|
// // … then string.format / sprintf-style consume
|
|
void PushLocalizedString(void *L, const char *globalName, const char *fallback);
|
|
|
|
// Pushes `string.format(_G[globalName] or fallback, n)` — the result
|
|
// of formatting a single integer into a localized string. Leaves the
|
|
// formatted string on top of the stack. Common shape: most
|
|
// FrameXML count-style strings (`ITEMS_EQUIPPED = "%d equipped"`,
|
|
// `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
|
|
// client is launched with `-console`. Vanilla maintains a
|
|
// `TSExplicitList<CONSOLECOMMAND>`; these wrap the engine's registrar
|
|
// and output paths. See the "Console commands & Interface file export"
|
|
// section in CLAUDE.md for the underlying offsets and ABI.
|
|
namespace Console {
|
|
|
|
// 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 — 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,
|
|
CATEGORY_CONSOLE = 2,
|
|
CATEGORY_COMBAT = 3,
|
|
CATEGORY_GAME = 4,
|
|
CATEGORY_DEFAULT = 5,
|
|
CATEGORY_NET = 6,
|
|
CATEGORY_SOUND = 7,
|
|
CATEGORY_GM = 8,
|
|
};
|
|
|
|
// Registers a console command. `name` and `description` are stored BY
|
|
// POINTER (the engine doesn't copy them), so pass string literals or
|
|
// otherwise process-lifetime storage. Dedup-safe: re-registering the
|
|
// same name is a harmless no-op, so it's fine to call from a hook that
|
|
// fires more than once. Safe any time after engine boot — the command
|
|
// table self-initializes on first use. `description` may be nullptr.
|
|
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, 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
|
|
|
|
// Self-registration for API modules. Each module .cpp declares a file-scope
|
|
// `static const Game::ModuleAutoRegister _r{&RegisterLuaFunctions};`, which
|
|
// chains itself onto a global list at DLL-load time. `RunModuleRegistrations`
|
|
// is called once from the LoadScriptFunctions post-hook to fire them all,
|
|
// so DllMain.cpp doesn't need to know the modules exist.
|
|
//
|
|
// Order is unspecified (LIFO of static-init order across TUs). Modules must
|
|
// not depend on each other's registration side effects.
|
|
struct ModuleAutoRegister {
|
|
using Fn = void (*)();
|
|
explicit ModuleAutoRegister(Fn fn);
|
|
Fn fn;
|
|
ModuleAutoRegister *next;
|
|
};
|
|
|
|
void RunModuleRegistrations();
|
|
|
|
// Glue-state mirror of `ModuleAutoRegister`. Modules wanting login-
|
|
// screen exposure declare a file-scope
|
|
// `static const Game::GlueModuleAutoRegister _g{&RegisterGlueFunctions};`
|
|
// alongside (or instead of) the in-game `ModuleAutoRegister`. Glue
|
|
// callbacks run from the `FUN_LOAD_GLUE_SCRIPT_FUNCTIONS` post-hook,
|
|
// once per glue boot (game launch + every world→glue return). Use
|
|
// `Game::Lua::RegisterGlueFunction` from inside the callback.
|
|
struct GlueModuleAutoRegister {
|
|
using Fn = void (*)();
|
|
explicit GlueModuleAutoRegister(Fn fn);
|
|
Fn fn;
|
|
GlueModuleAutoRegister *next;
|
|
};
|
|
|
|
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 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 four core engine-init hooks in
|
|
// DllMain (FrameScript_Initialize / LoadScriptFunctions /
|
|
// 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;
|
|
void *hook;
|
|
void **original;
|
|
HookAutoRegister *next;
|
|
};
|
|
|
|
// 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
|