Compare commits

..
10 Commits
Author SHA1 Message Date
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
23 changed files with 1122 additions and 383 deletions
+3 -1
View File
@@ -51,7 +51,7 @@ In the Frame rows, a name that starts with `:` is a method of the widget that th
| Namespace | Calls |
|-----------|-------|
| [Action](docs/API.md#action) | `GetActionInfo`, `IsItemAction`, `HasBonusActionBar` |
| [Action](docs/API.md#action) | `GetActionInfo`, `IsItemAction`, `HasBonusActionBar`, `C_ActionBar.EnableActionRangeCheck` |
| [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 |
@@ -280,6 +280,8 @@ when launching with `-console`), not as Lua functions. See the
| 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)) |
+100 -2
View File
@@ -14,6 +14,7 @@ build instructions.
- [`IsItemAction(slot)`](#isitemactionslot)
- [`HasBonusActionBar()`](#hasbonusactionbar)
- [`C_ActionBar.ShouldShowKeyring()`](#c_actionbarshouldshowkeyring)
- [`C_ActionBar.EnableActionRangeCheck(slot, enable)`](#c_actionbarenableactionrangecheckslot-enable)
- [AddOns](#addons)
- [`C_AddOns.GetAddOnName(indexOrName)`](#c_addonsgetaddonnameindexorname)
@@ -235,6 +236,8 @@ build instructions.
- [Player input-state events (`PLAYER_STARTED_MOVING` / `LOOKING` / `TURNING` + `STOPPED_*`)](#player-input-state-events)
- [`GLOBAL_MOUSE_DOWN` / `GLOBAL_MOUSE_UP` events](#global_mouse_down--global_mouse_up-events)
- [`AUCTION_MULTISELL_START` / `AUCTION_MULTISELL_UPDATE` / `AUCTION_MULTISELL_FAILURE` events](#c_auctionhousepostitemitemlocation-duration-quantity-numstacks-bid-buyout)
- [`ACTION_RANGE_CHECK_UPDATE` event](#action_range_check_update-event)
- [`ACTION_USABLE_CHANGED` event](#action_usable_changed-event)
- [`COMBAT_LOG_EVENT_UNFILTERED` / `COMBAT_LOG_EVENT` events](#combat_log_event_unfiltered--combat_log_event-events)
- [`CURSOR_CHANGED` event](#cursor_changed-event)
- [`EQUIPMENT_SETS_CHANGED` event](#equipment_sets_changed-event)
@@ -1310,6 +1313,34 @@ if C_ActionBar.ShouldShowKeyring() then
end
```
### `C_ActionBar.EnableActionRangeCheck(slot, enable)`
Starts or stops the range check of a 1-based action-bar slot for
[`ACTION_RANGE_CHECK_UPDATE`](#action_range_check_update-event). A slot
that is not in the range 1 to 120 is ignored.
The client counts the calls for each slot. Each call with `enable` set to
`true` adds one. Each call with `enable` set to `false` removes one. The
client checks the slot while its count is more than zero. Thus, if two
buttons show the same slot, each button can enable and disable the slot
for itself.
After each call with `enable` set to `true`, the next check of the slot
fires the event, also if the state did not change. This gives a new
button the current state of its slot. You do not have to call
`IsActionInRange` when you show a button.
A `/reload` sets the count of all slots to zero.
```lua
local f = CreateFrame("Frame")
f:RegisterEvent("ACTION_RANGE_CHECK_UPDATE")
f:SetScript("OnEvent", function()
print("Slot", arg1, arg3 and (arg2 and "in range" or "out of range") or "no range check")
end)
C_ActionBar.EnableActionRangeCheck(1, true)
```
## AddOns
`C_AddOns.*` getters that splat the
@@ -5533,6 +5564,68 @@ Behavior notes:
- Clicks during a loading screen or a screen fade do not fire the
events. Clicks that the open console takes also do not fire them.
### `ACTION_RANGE_CHECK_UPDATE` event
Fires when an action-bar slot that has
[`EnableActionRangeCheck`](#c_actionbarenableactionrangecheckslot-enable)
on goes into or out of range of its target.
```
ACTION_RANGE_CHECK_UPDATE: slot, isInRange, checksRange
```
- **`slot`** (number) — the 1-based action-bar slot.
- **`isInRange`** (boolean) — `true` when the target is in range. Do not
use this value when `checksRange` is `false`.
- **`checksRange`** (boolean) — `false` when the client did not do a range
check. For example, the slot is empty, its action has no range, or there
is no target.
The values are the values that `IsActionInRange(slot)` gives: `1` is
`isInRange = true`, `0` is `isInRange = false`, and `nil` is
`checksRange = false`. A macro that is aimed at a unit (for example
`[@focus]`) uses that unit as its target.
The client checks the enabled slots on each frame, but only while a frame
is registered for the event. The event fires only when the state of a
slot changes, and after each enable call. When the action in a slot
changes, the client checks the new action. The event fires if its state
is different.
### `ACTION_USABLE_CHANGED` event
Fires when the usable state of one or more action-bar slots changes. The
payload gives only the slots that changed. Thus, a handler does not have
to read `IsUsableAction` for each button.
```
ACTION_USABLE_CHANGED: changes
```
- **`changes`** (table) — a list with one table for each slot that
changed:
| Field | Type | Meaning |
|---|---|---|
| `slot` | number | The 1-based action-bar slot. |
| `usable` | boolean | The new first return value of `IsUsableAction(slot)`, as a boolean. |
| `noMana` | boolean | The new second return value of `IsUsableAction(slot)`, as a boolean. |
The event fires immediately after `ACTIONBAR_UPDATE_USABLE`, which does
not change. When the action in a slot changes, the client fires
`ACTIONBAR_SLOT_CHANGED` for that slot, not this event. Thus, read
`IsUsableAction` for a slot on `ACTIONBAR_SLOT_CHANGED`.
```lua
local f = CreateFrame("Frame")
f:RegisterEvent("ACTION_USABLE_CHANGED")
f:SetScript("OnEvent", function()
for _, change in ipairs(arg1) do
print("Slot", change.slot, change.usable, change.noMana)
end
end)
```
### `COMBAT_LOG_EVENT_UNFILTERED` / `COMBAT_LOG_EVENT` events
`COMBAT_LOG_EVENT_UNFILTERED` fires once for each combat log event: a hit, a
@@ -9150,6 +9243,10 @@ Sets how the bar fills as its value increases. `fillStyle` is a value of
- A string is not case-sensitive. Any other value is an error.
- The `Center` style ignores `statusBar:SetReverseFill()`.
- The bar texture covers only the filled part of the bar. A region that is
anchored to `statusBar:GetStatusBarTexture()` moves with the edge of the
fill. When the bar is empty, the texture has a size of 0 along the fill,
at the start edge.
```lua
bar:SetFillStyle(Enum.StatusBarFillStyle.Center)
@@ -9198,8 +9295,9 @@ end
- `SetValue` does not remove the timer. `SetMinMaxValues` removes it.
- A hidden bar does not move. When it shows again, its fill is correct on
its first frame.
- The bar keeps its texture crop and its fill style, from `SetFillStyle`,
`SetReverseFill` and `SetRotatesTexture`.
- The bar keeps its fill style, from `SetFillStyle`, `SetReverseFill` and
`SetRotatesTexture`. The bar texture moves with the fill, as it does
for `SetValue`.
- `interpolation` is a value of `Enum.StatusBarInterpolation`. The default
is `Immediate`. With `ExponentialEaseOut`, the fill eases from the fill
that the bar showed before, and then follows the timer with the same ease
+3
View File
@@ -15,6 +15,7 @@
#include "MinHook.h"
#include "Offsets.h"
#include "api/Documentation.h"
#include "compat/WowTurbo.h"
namespace Game {
@@ -586,6 +587,8 @@ 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;
+46 -10
View File
@@ -891,6 +891,15 @@ enum Offsets {
// which adds the built string (+0xF8) when the rect is valid and not
// wholly off screen.
FUN_FONTSTRING_EMIT = 0x00772E50,
// CSimpleFontString::OnColorChanged — `void __thiscall(fs, int changed)`,
// `ret 4`, the font string's region slot 8 (VTBL_REGION_RECOLOR): calls the
// region colour fold 0x0077FAC0, then, with a built string, hands
// colors[0] (or white when the count is not 1) to TextBlockUpdateColor
// 0x0044D650 and redoes the shadow. SetVertexColor (0x0077F750) calls it
// after storing a colour, and the frame alpha setter (0x0076A690) on each
// region, so every change of OFF_FONTSTRING_COLOR_ARRAY ends here.
// Verified by disassembly.
FUN_FONTSTRING_ON_COLOR_CHANGED = 0x00772180,
// A layer batch's entry count: the quad append and the text append each
// add one (0x00772FD0, 0x00773080).
OFF_LAYER_BATCH_COUNT = 0x4,
@@ -1013,12 +1022,10 @@ enum Offsets {
// {rgba@+4, shown@+8, timeVisibleLeft@+0xC, fadeLeft@+0x10} in the
// stride-0x10 line array at smf+0x3A4) animates each visible line
// fontstring's alpha byte through this same SetColor every frame, then
// hides the fs at fade end. Text::InlineTexturePool mirrors this byte onto
// the line's icon regions each tick so inline icons fade with their line
// (regions parent to the CHAT FRAME, so the frame's own alpha byte —
// frame+0xC8, per Script_GetAlpha 0x00774DC0 — already modulates them via
// the engine's parent×region product; only the fs's own component needs
// mirroring).
// hides the fs at fade end. The byte also carries the frame's alpha
// (folded by 0x0077FAC0). Text::InlineTexturePool copies it onto the
// line's icon textures from FUN_FONTSTRING_ON_COLOR_CHANGED; the textures
// have no frame, so it is the only alpha they get.
OFF_FONTSTRING_COLOR_COUNT = 0xB4,
OFF_FONTSTRING_COLOR_ARRAY = 0xB8,
OFF_TEXTBLOCK_NODE = 0x8, // the gxu text node inside the handle
@@ -2106,6 +2113,25 @@ enum Offsets {
// own text is empty), as 4.3.4 calls UnitCombatLogSpellFail. Returns for a
// null player or spell (disassembly, 0x0062C37C-0x0062C38E).
FUN_COMBAT_LOG_SPELL_FAIL = 0x0062C360,
// LoggingCombat's flag (s_loggingFlags[1]; [0] at 0x00B4FDB4 is chat):
// nonzero while the combat log is written to a file. Cleared by the chat
// teardown (0x00498700). Disassembled, 0x0049FE70 / 0x0049B1D3.
VAR_COMBAT_LOGGING = 0x00B4FDB8,
// Storm SLogCreate — `bool __stdcall(const char *path, uint32_t flags,
// uint32_t *log)`. Flag 4 appends; the file is opened (and its folders
// made) on the first write. LoggingCombat opens Logs\WoWCombatLog.txt with
// it (0x0049FEA2). Storm closes every open log at exit (0x0065A4B0).
// benilla-re storm/log.
FUN_SLOG_CREATE = 0x0065A0C0,
// Storm SLogWrite — `void __cdecl(uint32_t log, const char *format, ...)`:
// one line, prefixed with "M/D HH:MM:SS.mmm " and ended with "\r\n". The
// combat log's own line writer (0x0049B1E8) calls it with "%s".
// benilla-re storm/log.
FUN_SLOG_WRITE = 0x0065ACE0,
// Storm SLogClose — `void __stdcall(uint32_t log)`: writes the buffered
// lines to the file, flushes and closes it. The chat teardown closes the
// chat and combat logs with it (0x0049871B). benilla-re storm/log.
FUN_SLOG_CLOSE = 0x00659EC0,
// A unit's death — `void __fastcall(CGUnit *unit)`: writes the death
// line (0x0062C160), shows the pending XP gain, plays the death animation
// and sound. Its one caller is CGUnit_C::OnDied (0x006058AE), from the
@@ -7017,6 +7043,19 @@ enum Offsets {
// ACTIONBAR_UPDATE_USABLE (0xD7, via FUN_FIRE_EVENT_NO_ARGS) when one did.
// Disassembled; it is 4.3.4's `CGActionBar::UpdateUsable` line for line.
FUN_ACTION_UPDATE_USABLE = 0x004E5C00,
// The uint[120] caches FUN_ACTION_UPDATE_USABLE compares and stores:
// FUN_ACTION_SLOT_USABLE's return at `0x004E5C1A` / `0x004E5C2F`, its
// `*outNoMana` at `0x004E5C26` / `0x004E5C36`. `IsUsableAction` reads them.
VAR_ACTION_USABLE = 0x00BC6B60,
VAR_ACTION_NO_MANA = 0x00BC67A0,
// FUN_ACTION_UPDATE_USABLE's per-slot `call FUN_ACTION_SLOT_USABLE` (ecx
// slot0, edx &noMana), compared against the caches above before they are
// stored. E8 call, disassembled.
CALL_UPDATE_USABLE_SLOT_USABLE = 0x004E5C15,
// FUN_ACTION_UPDATE_USABLE's `mov ecx, 0xD7; call FUN_FIRE_EVENT_NO_ARGS`
// (ACTIONBAR_UPDATE_USABLE), reached only when a slot changed. E8 call,
// disassembled.
CALL_UPDATE_USABLE_FIRE = 0x004E5C53,
// Drop the cursor onto a slot — `__fastcall(uint slot0)`. Sole entry
// for `PlaceAction`, and the tail of both FUN_ACTION_PICKUP and
// nampower's detoured `CGActionBar_UseAction` (`0x004E5EE0`) when the
@@ -12269,10 +12308,7 @@ enum Offsets {
VTBL_LAYOUT_ON_FRAME_SIZE_CHANGED = 0x00,
VTBL_LAYOUT_DELETING_DESTRUCTOR = 0x04,
VTBL_LAYOUT_GET_LAYOUT_PARENT = 0x0C,
// +0x10 SetLayoutScale (this, float scale, int force) -> int, ret 8: what
// AddRegionToLayer (0x0076A860) calls with the frame's OFF_LAYOUT_SCALE
// and 0 when it links a region into a draw layer.
VTBL_LAYOUT_SET_LAYOUT_SCALE = 0x10,
// +0x10 SetLayoutScale: VTBL_LAYOUT_SET_SCALE.
// +0x1C / +0x20 the explicit width / height, `float __thiscall(this)`:
// CLayoutFrame's read +0x50 / +0x54 (0x00768420 / 0x00768410); textures
// and font strings override them. Script GetWidth / GetHeight call them
+4
View File
@@ -28,6 +28,8 @@
// 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"
@@ -107,4 +109,6 @@ 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
+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
+9 -24
View File
@@ -89,8 +89,8 @@ void PatchLoadWindow() {
reinterpret_cast<const void *>(&LoadWindowCloseThunk));
}
int __fastcall Script_UpdateAddOnMemoryUsage(void * /*L*/) {
Gc::Tag::UpdateUsage();
int __fastcall Script_UpdateAddOnMemoryUsage(void *L) {
Gc::Tag::UpdateUsage(L);
return 0;
}
@@ -107,30 +107,15 @@ int __fastcall Script_GetAddOnMemoryUsage(void *L) {
}
// `_classicapi_LuaHeapAudit()` → objectBytes, nblocks, taggedObjects.
// Walks every collectable object the engine can reach — the main list,
// the userdata list and the string table, the three lists `luaC_sweep`
// sweeps — summing `Gc::Tag::SizeOf`. `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.
uint64_t SumList(const uint8_t *object) {
uint64_t total = 0;
while (object != nullptr) {
total += Gc::Tag::SizeOf(object);
object = Game::Read<const uint8_t *>(object, Offsets::OFF_LUA_GCHEADER_NEXT);
}
return total;
}
// 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);
uint64_t bytes = SumList(Game::Read<const uint8_t *>(g, Offsets::OFF_LUA_G_ROOTGC)) +
SumList(Game::Read<const uint8_t *>(g, Offsets::OFF_LUA_G_ROOTUDATA));
const auto buckets =
Game::Read<const uint8_t *const *>(g, Offsets::OFF_LUA_G_STRT_HASH);
const int size = Game::Read<int>(g, Offsets::OFF_LUA_G_STRT_SIZE);
for (int i = 0; i < size; ++i)
bytes += SumList(buckets[i]);
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()));
+20 -10
View File
@@ -35,6 +35,7 @@
#include "combatlog/Entry.h"
#include "Game.h"
#include "combatlog/File.h"
#include "combatlog/History.h"
#include "Offsets.h"
#include "event/Custom.h"
@@ -405,9 +406,7 @@ int Push(void *L, const Entry &e) {
PushString(L, name);
else
PushNil(L);
PushNumber(L, spell != nullptr
? SchoolMask(Game::Read<uint32_t>(spell, Offsets::OFF_SPELL_RECORD_SCHOOL))
: e.spellSchool);
PushNumber(L, spell != nullptr ? SpellSchoolMask(spell) : e.spellSchool);
count += 3;
}
if (e.info & INFO_COUNT) {
@@ -419,14 +418,12 @@ int Push(void *L, const Entry &e) {
++count;
}
if (e.info & INFO_MISS) {
const int miss = e.v[0];
PushString(L, (miss >= 0 && miss < MISS_COUNT) ? kMissNames[miss] : kMissNames[0]);
PushString(L, MissName(e.v[0]));
PushFlag(L, e.offHand);
count += 2;
}
if (e.info & INFO_ENVIRONMENTAL) {
const int type = e.v[0];
PushString(L, (type >= 0 && type < 6) ? kEnvironmentalNames[type] : kEnvironmentalNames[0]);
PushString(L, EnvironmentalName(e.v[0]));
++count;
}
if (e.info & INFO_DAMAGE) {
@@ -488,9 +485,7 @@ int Push(void *L, const Entry &e) {
PushString(L, name);
else
PushNil(L);
PushNumber(L, extra != nullptr ? SchoolMask(Game::Read<uint32_t>(
extra, Offsets::OFF_SPELL_RECORD_SCHOOL))
: 0);
PushNumber(L, SpellSchoolMask(extra));
count += 3;
}
if (e.info & INFO_ITEM) {
@@ -581,6 +576,14 @@ const char *Name(int event) {
return (event >= 0 && event < EVENT_COUNT) ? kEventNames[event] : "";
}
const char *MissName(int missType) {
return (missType >= 0 && missType < MISS_COUNT) ? kMissNames[missType] : kMissNames[0];
}
const char *EnvironmentalName(int type) {
return (type >= 0 && type < 6) ? kEnvironmentalNames[type] : kEnvironmentalNames[0];
}
int PushEvent(void *L, const Entry &entry) { return Push(L, entry); }
const uint8_t *SpellRecord(int spellId) { return Spell::Lookup::RecordForID(spellId); }
@@ -608,6 +611,12 @@ bool Ranged(const uint8_t *spell) {
uint32_t SchoolMask(uint32_t school) { return school < kSchoolCount ? 1u << school : 0; }
uint32_t SpellSchoolMask(const uint8_t *spell) {
return spell != nullptr
? SchoolMask(Game::Read<uint32_t>(spell, Offsets::OFF_SPELL_RECORD_SCHOOL))
: 0;
}
bool HasAuraEffect(const uint8_t *spell, int auraName) {
if (spell == nullptr)
return false;
@@ -700,6 +709,7 @@ void Queue(Entry &e) {
g_startTimeMs = e.timeMs;
}
History::Record(e);
File::Write(e);
Send(e);
}
+9
View File
@@ -72,6 +72,12 @@ enum Subevent : int {
const char *Name(int event);
// The INFO_MISS value as 4.3.4's g_spellMissStrings names it.
const char *MissName(int missType);
// The INFO_ENVIRONMENTAL value as 4.3.4's s_environmentalDamageTypes names it.
const char *EnvironmentalName(int type);
// 4.3.4's m_infoFlags: which suffix blocks the event carries, pushed in
// this order after the spell prefix.
enum Info : uint32_t {
@@ -158,6 +164,9 @@ bool Ranged(const uint8_t *spell);
// A school index (Spell.dbc School, the packets' school) as a school mask.
uint32_t SchoolMask(uint32_t school);
// The spell's school as a mask (4.3.4's SpellRec m_schoolMask), 0 for nullptr.
uint32_t SpellSchoolMask(const uint8_t *spell);
// Whether one of the spell's three effects applies the aura `auraName`
// (EffectApplyAuraName).
bool HasAuraEffect(const uint8_t *spell, int auraName);
+212
View File
@@ -0,0 +1,212 @@
// 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 combat log file — 4.3.4's CombatLogEntry::PackEvent line, written as
// SendCombatLogEvents writes it while LoggingCombat is on.
//
// The engine pieces:
// - the switch is LoggingCombat's own flag, so /combatlog and
// LoggingCombat() turn both files on and off, and logging out (the chat
// teardown in CGGameUI::ShutdownGame, 0x00498700, clears the flag) stops
// both;
// - 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.
// 1.12's own Logs\WoWCombatLog.txt keeps its chat-text lines, which 1.12
// log readers parse;
// - the file is a Storm log, opened as LoggingCombat opens its own (append)
// and written with SLogWrite (which stamps "M/D HH:MM:SS.mmm " on each
// line, as in 4.3.4's file). When the flag turns off it is closed, which
// writes its buffered lines. Storm closes what is still open at exit;
// - the line is PackEvent's: no hideCaster, flags as hex, the spell school
// as a hex mask (the extra spell's in decimal), damage values as numbers,
// flags as 1 or nil, no isOffHand and no alternate power type.
//
// The flag is read once a frame (FrameTick, which also runs on the glue
// screen, so a logout's cleared flag is seen there) and before each line.
// LoggingCombat itself is not hooked: other DLLs add their own logs to it.
#include "combatlog/File.h"
#include "Game.h"
#include "Offsets.h"
#include "guid/Guid.h"
#include "tick/FrameTick.h"
#include <cstdio>
#include <ctime>
#include <string>
namespace CombatLog::File {
namespace {
constexpr uint32_t kAppend = 4; // SLogCreate: open at the end of the file
uint32_t g_log = 0;
bool Logging() { return Game::Read<int>(Offsets::VAR_COMBAT_LOGGING) != 0; }
// A new log named for the local time now. True when it is open.
bool Open() {
const std::time_t now = std::time(nullptr);
std::tm local{};
if (localtime_s(&local, &now) != 0)
return false;
char path[64];
std::strftime(path, sizeof path, "Logs\\WoWCombatLog-%m%d%y_%H%M%S.txt", &local);
using Create_t = int(__stdcall *)(const char *path, uint32_t flags, uint32_t *log);
const auto create = reinterpret_cast<Create_t>(static_cast<uintptr_t>(Offsets::FUN_SLOG_CREATE));
if (create(path, kAppend, &g_log) == 0)
g_log = 0;
return g_log != 0;
}
void Close() {
using Close_t = void(__stdcall *)(uint32_t log);
reinterpret_cast<Close_t>(static_cast<uintptr_t>(Offsets::FUN_SLOG_CLOSE))(g_log);
g_log = 0;
}
// Follows the flag: a new file when it turns on, the file closed when it
// turns off.
void OnFrame() {
const bool logging = Logging();
if (logging && g_log == 0)
Open();
else if (!logging && g_log != 0)
Close();
}
const Tick::FrameTick::AutoSubscribe _frame{&OnFrame};
// PackString
void Plain(std::string &line, const char *text) {
line += ',';
line += text;
}
// PackQuotedString, or PackString "nil" when there is no text.
void Quoted(std::string &line, const char *text) {
if (text == nullptr) {
Plain(line, "nil");
return;
}
line += ",\"";
for (const char *c = text; *c != '\0'; ++c) {
if (*c == '"' || *c == '\\')
line += '\\';
line += *c;
}
line += '"';
}
// PackHex
void Hex(std::string &line, uint32_t value) {
char text[16];
std::snprintf(text, sizeof text, ",0x%x", value);
line += text;
}
void Number(std::string &line, int value) {
char text[16];
std::snprintf(text, sizeof text, ",%d", value);
line += text;
}
// PackBool
void Flag(std::string &line, bool value) { line += value ? ",1" : ",nil"; }
void Unit(std::string &line, uint64_t guid, bool named, const std::string &name, uint32_t flags,
uint32_t raidFlags) {
char text[Guid::STRING_SIZE];
line += ',';
line += Guid::FormatAsString(guid, text, sizeof text);
Quoted(line, named ? name.c_str() : nullptr);
Hex(line, flags);
Hex(line, raidFlags);
}
// CombatLogEntry::PackEvent, the blocks 1.12 fills.
std::string Pack(const Entry &e) {
std::string line = Name(e.event);
Unit(line, e.source, e.sourceNamed, e.sourceName, e.sourceFlags, e.sourceRaidFlags);
Unit(line, e.dest, e.destNamed, e.destName, e.destFlags, e.destRaidFlags);
if (e.spellPrefix) {
const uint8_t *spell = SpellRecord(e.spellId);
Number(line, e.spellId);
Quoted(line, SpellName(spell));
Hex(line, spell != nullptr ? SpellSchoolMask(spell) : e.spellSchool);
}
if (e.info & INFO_COUNT)
Number(line, e.v[0]);
if (e.info & INFO_TEXT)
Quoted(line, e.text.c_str());
if (e.info & INFO_MISS)
Plain(line, MissName(e.v[0]));
if (e.info & INFO_ENVIRONMENTAL)
Plain(line, EnvironmentalName(e.v[0]));
if (e.info & INFO_DAMAGE) {
for (const int slot : {1, 2, 3, 5, 6, 4})
Number(line, e.v[slot]);
Flag(line, e.critical);
Flag(line, e.glancing);
Flag(line, e.crushing);
}
if (e.info & INFO_MISS_ABSORBED)
Number(line, e.v[4]);
if (e.info & INFO_MISS_RESISTED)
Number(line, e.v[5]);
if (e.info & INFO_MISS_BLOCKED)
Number(line, e.v[6]);
if (e.info & INFO_HEAL) {
for (int i = 0; i < 3; ++i)
Number(line, e.v[i]);
Flag(line, e.critical);
}
if (e.info & INFO_ENERGIZE) {
for (int i = 0; i < 2; ++i)
Number(line, e.v[i]);
}
if (e.info & INFO_DRAIN) {
for (int i = 0; i < 3; ++i)
Number(line, e.v[i]);
}
if (e.info & INFO_EXTRA_SPELL) {
const uint8_t *extra = SpellRecord(e.v[0]);
Number(line, e.v[0]);
Quoted(line, SpellName(extra));
Number(line, static_cast<int>(SpellSchoolMask(extra)));
}
if (e.info & INFO_ITEM) {
Number(line, e.v[0]);
Quoted(line, e.itemNamed ? e.itemName.c_str() : nullptr);
}
if (e.info & INFO_AURA_TYPE)
Plain(line, e.harmful ? "DEBUFF" : "BUFF");
if (e.info & INFO_AURA_AMOUNT)
Number(line, e.v[2]);
return line;
}
} // namespace
void Write(const Entry &entry) {
// A line in the frame logging turned on comes before the frame's check.
if (!Logging() || (g_log == 0 && !Open()))
return;
using Write_t = void(__cdecl *)(uint32_t log, const char *format, ...);
reinterpret_cast<Write_t>(static_cast<uintptr_t>(Offsets::FUN_SLOG_WRITE))(
g_log, "%s", Pack(entry).c_str());
}
} // namespace CombatLog::File
+29
View File
@@ -0,0 +1,29 @@
// 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 combat log file — 4.3.4's WoWCombatLog.txt line, written while
// LoggingCombat is on to a file per logging session named as retail names it
// (Logs\WoWCombatLog-MMDDYY_HHMMSS.txt). 1.12's own WoWCombatLog.txt keeps
// its chat-text lines.
#include "combatlog/Entry.h"
namespace CombatLog::File {
// SendCombatLogEvents' write: CombatLogEntry::PackEvent's line, through
// CGChat::AddCombatMessage's SLogWrite, while combat logging is on.
void Write(const Entry &entry);
} // namespace CombatLog::File
+83
View File
@@ -0,0 +1,83 @@
// 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 "compat/WowTurbo.h"
#include "Common.h"
#include <cstring>
#include <windows.h>
namespace Compat::WowTurbo {
namespace {
// The prologue patch wow_turbo's MinHook writes on x86: `jmp rel32` over the
// first five bytes. 1.12's entries open with `push ebp; mov ebp,esp`, never
// the `mov edi,edi` that would make MinHook hot-patch instead.
constexpr uint8_t kJmp = 0xE9;
constexpr size_t kJmpLen = 5;
// The `kJmpLen` bytes at `va` as WoW.exe holds them on disk, located through
// the loaded image's own section table.
bool ReadStock(uintptr_t va, uint8_t (&out)[kJmpLen]) {
const auto base = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
const auto *dos = reinterpret_cast<const IMAGE_DOS_HEADER *>(base);
const auto *nt = reinterpret_cast<const IMAGE_NT_HEADERS *>(base + dos->e_lfanew);
const IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION(nt);
const uintptr_t rva = va - base;
for (WORD i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++section) {
if (rva < section->VirtualAddress ||
rva + kJmpLen > section->VirtualAddress + section->SizeOfRawData)
continue;
wchar_t path[MAX_PATH];
const DWORD len = GetModuleFileNameW(nullptr, path, MAX_PATH);
if (len == 0 || len == MAX_PATH)
return false;
const HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE)
return false;
OVERLAPPED at{};
at.Offset = static_cast<DWORD>(rva - section->VirtualAddress + section->PointerToRawData);
DWORD read = 0;
const bool ok = ReadFile(file, out, kJmpLen, &read, &at) != 0 && read == kJmpLen;
CloseHandle(file);
return ok;
}
return false;
}
} // namespace
void Reclaim(uintptr_t function) {
const HMODULE turbo = GetModuleHandleW(L"wow_turbo.dll");
if (turbo == nullptr)
return;
const auto *entry = reinterpret_cast<const uint8_t *>(function);
if (entry[0] != kJmp)
return;
int32_t rel = 0;
std::memcpy(&rel, entry + 1, sizeof rel);
HMODULE owner = nullptr;
if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(function + kJmpLen + rel), &owner) ||
owner != turbo)
return;
uint8_t stock[kJmpLen];
if (ReadStock(function, stock) && stock[0] != kJmp)
Common::PatchBytes(reinterpret_cast<void *>(function), stock, kJmpLen);
}
} // namespace Compat::WowTurbo
+44
View File
@@ -0,0 +1,44 @@
// 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>
// wow_turbo (github.com/athei/wow-mods) detours ~380 engine functions to Rust
// reimplementations and yields any function another mod has already hooked:
// its installer refuses a prologue that fails its signature. It installs from
// DllMain, but ClassicAPI installs from `Load`, which VanillaFixes calls after
// every DllMain, so wow_turbo never sees our hooks and always installs first.
// MinHook then copies wow_turbo's jump into our trampoline, and our hook calls
// the Rust body instead of the engine's. That loses everything that lives in
// the stock body: Frame::ScriptArgs' pcall redirects in both script runners,
// and InlineTexture / IndentedWordWrap in the text builder, whose Rust copy
// calls its own emitter.
//
// `Reclaim` gives the stock prologue back before we hook, the state wow_turbo
// itself produces when it loads after a mod that hooked first. wow_turbo keeps
// its original in place, logs "prologue overwritten ... by ClassicAPI.dll"
// and does not re-patch these entries.
//
// The DllMain core hooks need no reclaim: the only one wow_turbo also
// replaces is the integrity scan, which both make the same no-op.
namespace Compat::WowTurbo {
// Restores the engine's own first instruction at `function` when it is a
// `jmp` into wow_turbo.dll. No-op when wow_turbo is not loaded or the
// prologue is anything else.
void Reclaim(uintptr_t function);
} // namespace Compat::WowTurbo
@@ -1,3 +1,5 @@
local strsplit = string.split;
LinkTypes = {
AADCOpenConfig = "aadcopenconfig",
Action = "action",
@@ -75,7 +77,7 @@ function LinkUtil.FormatLink(linkType, linkDisplayText, ...)
end
function LinkUtil.SplitLinkData(linkData)
local linkType, linkOptions = string.split(":", linkData, 2);
local linkType, linkOptions = strsplit(":", linkData, 2);
linkOptions = linkOptions or ""; -- Could be nil if there's no ":" in linkData.
return linkType, linkOptions;
end
@@ -85,7 +87,7 @@ function LinkUtil.SplitLink(link) -- returns linkText and displayText
end
function LinkUtil.SplitLinkOptions(linkOptions)
return string.split(":", linkOptions);
return strsplit(":", linkOptions);
end
-- Extract the first link from the text given, ignoring leading and trailing characters.
+11 -6
View File
@@ -25,8 +25,9 @@ namespace Gc::Tag {
namespace {
// Live tagged objects → tag. Untagged objects are never stored, and every
// free erases, so a reused address can't inherit a dead object's tag.
// Tagged objects → tag. Untagged objects are never stored. Every create
// writes or erases its address's entry, so a reused address can't inherit a
// dead object's tag even when its free bypassed `FUN_LUA_C_FREEOBJ`.
ankerl::unordered_dense::map<const void *, const char *> g_tags;
// `GCUsage` list: tag → bytes at the last UpdateUsage. Like 3.3.5's list, a
@@ -38,8 +39,10 @@ std::vector<const char *> g_pins;
void OnCreate(const void *object) {
const char *ctx = Game::Read<const char *>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT);
if (ctx == nullptr)
if (ctx == nullptr) {
g_tags.erase(object);
return;
}
const char *pin = g_pins.empty() ? nullptr : g_pins.back();
g_tags[object] = pin != nullptr ? pin : ctx;
}
@@ -103,11 +106,13 @@ void PopPin() {
g_pins.pop_back();
}
void UpdateUsage() {
void UpdateUsage(const void *L) {
for (auto &entry : g_usage)
entry.second = 0;
for (const auto &[object, tag] : g_tags)
g_usage[tag] += SizeOf(object);
ForEachObject(L, [](const void *object) {
if (const char *tag = Of(object))
g_usage[tag] += SizeOf(object);
});
}
uint64_t Usage(const char *tag) {
+28 -2
View File
@@ -13,6 +13,9 @@
#pragma once
#include "Game.h"
#include "Offsets.h"
#include <cstddef>
#include <cstdint>
@@ -26,9 +29,14 @@
// addon loader sets to the addon's name pointer and script slots, constants
// and value copies carry — but its GC header has no room for a tag (a
// table's spare header bytes hold flags/lsizenode, a closure's isC/nupvalues),
// so the tag lives here, keyed by object, added on create and dropped on free
// so the tag lives here, keyed by object, set on create and dropped on free
// through `Gc::Hooks`. Tags are compared by pointer and never dereferenced.
//
// The map is only ever asked about live objects: `UpdateUsage` walks the
// engine's lists as `luaC_sizeall` does, never the map's own keys. A sweep
// that frees without `FUN_LUA_C_FREEOBJ` (wow_turbo's frees inline) leaves
// dead entries behind, and they are never read.
//
// `lua_gctag` is this module's pin stack: `PinScope` sets it for exactly the
// windows 3.3.5 sets it (an addon's load, a template's application).
@@ -55,8 +63,26 @@ struct PinScope {
PinScope &operator=(const PinScope &) = delete;
};
// Calls `fn(object)` on every collectable object the engine can reach: the
// main list, the userdata list and the string table, the three lists
// `luaC_sweep` sweeps.
template <typename Fn> void ForEachObject(const void *L, Fn fn) {
const auto walk = [&fn](const uint8_t *object) {
for (; object != nullptr;
object = Game::Read<const uint8_t *>(object, Offsets::OFF_LUA_GCHEADER_NEXT))
fn(object);
};
const uint8_t *g = Game::Read<const uint8_t *>(L, Offsets::OFF_LUA_STATE_G);
walk(Game::Read<const uint8_t *>(g, Offsets::OFF_LUA_G_ROOTGC));
walk(Game::Read<const uint8_t *>(g, Offsets::OFF_LUA_G_ROOTUDATA));
const auto buckets = Game::Read<const uint8_t *const *>(g, Offsets::OFF_LUA_G_STRT_HASH);
const int size = Game::Read<int>(g, Offsets::OFF_LUA_G_STRT_SIZE);
for (int i = 0; i < size; ++i)
walk(buckets[i]);
}
// `luaC_sizeall`: recount every tag's bytes from the live objects.
void UpdateUsage();
void UpdateUsage(const void *L);
// `luaC_getsize`: a tag's bytes as of the last `UpdateUsage`; 0 if unseen.
uint64_t Usage(const char *tag);
+2 -3
View File
@@ -58,9 +58,8 @@
// 1.12 has the split this needs: OnFrameUpdate draws the fill from the bar's
// GetFillFraction virtual (4.3.4's GetAnimValue), not from the stored value.
// A co-hook on it answers the shown fraction for a bar with a timer or an
// ease. Every fill layout takes its fraction there - 1.12's texture crop and
// StatusBar::Fill's reversed, centered, turned and tiled layouts alike - so
// both keep the bar's crop and fill style. Advance runs from that same update
// ease. StatusBar::Fill's layout takes its fraction there, so a timer or an
// ease keeps the bar's fill style. Advance runs from that same update
// pass, for shown bars only, with the pass's elapsed, which is the step the
// probe found; the fraction it settled is the one drawn.
//
+36 -80
View File
@@ -11,27 +11,30 @@
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
// `bar:SetReverseFill` / `GetReverseFill`, `SetRotatesTexture` /
// `GetRotatesTexture` and `SetFillStyle` / `GetFillStyle`.
// The bar fill, as 4.3.4 and retail lay it out, and `bar:SetReverseFill` /
// `GetReverseFill`, `SetRotatesTexture` / `GetRotatesTexture` and
// `SetFillStyle` / `GetFillStyle`.
//
// 1.12 draws the fill by cropping: the bar texture is installed with
// OFF_REGION_TEXCOORD_MODIFIES_RECT, and OnFrameUpdate sets its coordinates to
// the filled part, which shrinks its rectangle from the bottom-left corner.
// That crop can only grow a fill from the left or the bottom.
// the filled part, which shrinks the drawn quad but not the texture's rect. A
// region anchored to GetStatusBarTexture() then stays on the full bar.
//
// 4.3.4's CSimpleStatusBar::OnLayerUpdate (CSimpleStatusBar.cpp:248) does not
// crop: it sets the coordinates and moves the texture's four points in from
// the bar's edges by the empty part, from the right / top or, reversed, from
// the left / bottom (`m_reverseFill`), and with `m_rotatesTexture` maps the
// image turned a quarter. A bar with any of these modes on takes that layout
// here: the co-hook on OnFrameUpdate runs the base frame update and lays the
// texture out as 4.3.4 does, with the crop flag cleared on the texture. A bar
// with them all off runs 1.12's own update untouched. Turning the last mode
// off pins the texture to the bar again and gives it back its crop flag, as
// InstallBarTexture and SetBarTexture leave it.
// image turned a quarter. Retail does the same, so a region anchored to the
// texture's edge rides the fill. The co-hook replaces 1.12's OnFrameUpdate
// for every bar: it runs the base frame update and lays the texture out as
// 4.3.4 does, with the crop flag that InstallBarTexture sets cleared. The
// points are set with doResize, as 4.3.4 sets them, which queues the texture
// for the layout pass before the draw; its dependents resolve in that pass.
// An empty fill keeps a zero-width rect on the start edge (1.12's
// CalculateRect has no size test), where 4.3.4 also hides the texture; that
// hide is left out, so the texture stays shown as 1.12 leaves it.
//
// A tiled bar texture (Texture::Tile) takes the same layout, since the crop
// would size it by its repeat count, and keeps its coordinates, as 4.3.4's
// A tiled bar texture (Texture::Tile) keeps its coordinates, as 4.3.4's
// OnLayerUpdate sets none for a texture with a tile flag on.
//
// The retail fill styles (Enum.StatusBarFillStyle) fit the same layout:
@@ -85,29 +88,21 @@ struct State {
bool reverseFill = false;
bool rotatesTexture = false;
int fillStyle = kStandard;
// The texture's crop flag and points are ours until Restore.
bool owned = false;
bool laidOut = false;
float width = 0.0f;
float height = 0.0f;
bool Active() const { return reverseFill || rotatesTexture || fillStyle != kStandard; }
};
// Bars with a mode on, or laid out by us and not yet restored. Dropped when the
// bar is destroyed.
// Every bar laid out or given a mode. Dropped when the bar is destroyed.
std::unordered_map<const void *, State> g_state;
using Update_t = void(__fastcall *)(void *bar, void *edx, float elapsed);
using SetPoint_t = void(__thiscall *)(void *anchor, int point, void *relative, int relativePoint, float x,
float y, int doResize);
using SetAllPoints_t = void(__thiscall *)(void *anchor, void *relative, int doResize);
using SetTexCoordRect_t = void(__thiscall *)(void *texture, const float *rect);
using SetTexCoordCorners_t = void(__thiscall *)(void *texture, const float *corners);
using GetFillFraction_t = float(__fastcall *)(void *bar, void *edx);
Update_t g_origUpdate = nullptr;
uint32_t &Flags(void *bar) { return Game::Ref<uint32_t>(bar, Offsets::OFF_VALUE_FLAGS); }
void *BarTexture(void *bar) { return Game::Read<void *>(bar, Offsets::OFF_STATUSBAR_BAR_TEXTURE); }
@@ -135,6 +130,9 @@ float FillFraction(void *bar, int fillStyle) {
*static_cast<void **>(bar), Offsets::OFF_VMT_STATUSBAR_GET_FILL_FRACTION))(bar, nullptr);
}
// InstallBarTexture puts each new bar texture on 1.12's crop.
void Uncrop(void *texture) { Game::Ref<int>(texture, Offsets::OFF_REGION_TEXCOORD_MODIFIES_RECT) = 0; }
void SetPoint(void *texture, int point, void *bar, float x, float y) {
reinterpret_cast<SetPoint_t>(Offsets::FUN_REGION_SET_POINT)(
Game::Ptr<uint8_t>(texture, Offsets::OFF_REGION_ANCHOR), point,
@@ -171,9 +169,6 @@ void LayOut(void *bar, State &state, bool tiled) {
s1 = 1.0f;
}
Game::Ref<int>(texture, Offsets::OFF_REGION_TEXCOORD_MODIFIES_RECT) = 0; // a new texture is installed with it
state.owned = true;
float left = 0.0f, right = 0.0f, top = 0.0f, bottom = 0.0f;
if (IsVertical(bar)) {
if (!tiled && state.rotatesTexture) {
@@ -208,46 +203,20 @@ void LayOut(void *bar, State &state, bool tiled) {
state.height = height;
}
// Hands the texture back to 1.12's crop: pinned to the bar, crop flag on, and
// the fill marked for 1.12's next update.
void Restore(void *bar) {
if (void *texture = BarTexture(bar)) {
reinterpret_cast<SetAllPoints_t>(Offsets::FUN_LAYOUT_SET_ALL_POINTS)(
Game::Ptr<uint8_t>(texture, Offsets::OFF_REGION_ANCHOR),
Game::Ptr<uint8_t>(bar, Offsets::OFF_REGION_ANCHOR), 1);
Game::Ref<int>(texture, Offsets::OFF_REGION_TEXCOORD_MODIFIES_RECT) = 1;
}
Flags(bar) |= Offsets::VALUE_FLAG_CHANGED;
}
// Replaces CSimpleStatusBar::OnFrameUpdate: 1.12's crop never runs.
void __fastcall Update_h(void *bar, void *edx, float elapsed) {
StatusBar::Display::Advance(bar, elapsed);
void *texture = BarTexture(bar);
const bool tiled = texture != nullptr && Texture::Wrap::Tiles(texture);
auto it = g_state.find(bar);
if (it == g_state.end()) {
if (!tiled) {
g_origUpdate(bar, edx, elapsed);
return;
}
// 1.12's crop would size a tiled texture by its repeat count.
it = g_state.emplace(bar, State{}).first;
Game::Ref<int>(texture, Offsets::OFF_REGION_TEXCOORD_MODIFIES_RECT) = 0;
it->second.owned = true;
Flags(bar) |= Offsets::VALUE_FLAG_CHANGED;
} else if (!it->second.Active() && !tiled) {
Restore(bar);
g_state.erase(it);
g_origUpdate(bar, edx, elapsed);
return;
}
State &state = it->second;
reinterpret_cast<Update_t>(Offsets::FUN_FRAME_ON_UPDATE)(bar, edx, elapsed);
void *texture = BarTexture(bar);
if (texture == nullptr)
return;
Uncrop(texture);
constexpr uint32_t kReady = Offsets::VALUE_FLAG_RANGE_SET | Offsets::VALUE_FLAG_VALUE_SET;
const uint32_t flags = Flags(bar);
if ((flags & kReady) != kReady || BarTexture(bar) == nullptr)
if ((flags & kReady) != kReady)
return;
State &state = g_state[bar];
bool changed = (flags & Offsets::VALUE_FLAG_CHANGED) != 0;
if (!changed && state.laidOut) { // a resize moves the offsets' lengths
float width, height;
@@ -256,35 +225,21 @@ void __fastcall Update_h(void *bar, void *edx, float elapsed) {
}
if (!changed)
return;
LayOut(bar, state, tiled);
LayOut(bar, state, Texture::Wrap::Tiles(texture));
Flags(bar) &= ~Offsets::VALUE_FLAG_CHANGED;
}
const Game::HookAutoRegister _updateHook{Offsets::FUN_STATUSBAR_ON_FRAME_UPDATE,
reinterpret_cast<void *>(&Update_h),
reinterpret_cast<void **>(&g_origUpdate)};
reinterpret_cast<void *>(&Update_h), nullptr};
void OnFrameDestroyed(void *frame) { g_state.erase(frame); }
const Frame::Destruction::AutoSubscribe _destructionSub{&OnFrameDestroyed};
// Applies a mode change. A bar with a mode on takes its texture off the crop
// at once - a turned image's coordinates would crop it to nothing - and is laid
// out on its next update; one with none goes back to 1.12's fill.
// Applies a mode change; the bar is laid out again on its next update.
template <typename Change> void Modify(void *bar, Change change) {
State &state = g_state[bar];
change(state);
change(g_state[bar]);
Flags(bar) |= Offsets::VALUE_FLAG_CHANGED;
if (state.Active()) {
if (void *texture = BarTexture(bar)) {
Game::Ref<int>(texture, Offsets::OFF_REGION_TEXCOORD_MODIFIES_RECT) = 0;
state.owned = true;
}
return;
}
if (state.owned || state.laidOut)
Restore(bar);
g_state.erase(bar);
}
const State *Find(void *bar) {
@@ -294,8 +249,6 @@ const State *Find(void *bar) {
void *ResolveBar(void *L) { return Game::Lua::ResolveTypedObject(L, 1, Offsets::VAR_STATUSBAR_LUA_TYPE_ID); }
int __fastcall Script_SetReverseFill(void *L) {
void *bar = ResolveBar(L);
if (bar == nullptr)
@@ -317,10 +270,13 @@ int __fastcall Script_GetReverseFill(void *L) {
void SetRotates(void *bar, bool rotates) {
Modify(bar, [rotates](State &s) { s.rotatesTexture = rotates; });
// 4.3.4 sets the full coordinates at once, so a bar with no value yet
// shows its image turned, or not, before the first layout. Full
// coordinates crop nothing, so a texture back on the crop takes them too.
if (void *texture = BarTexture(bar))
// shows its image turned, or not, before the first layout. A texture not
// yet laid out is still on the crop, which would crop the turned image
// to nothing.
if (void *texture = BarTexture(bar)) {
Uncrop(texture);
SetFullTexCoord(texture, rotates);
}
}
int __fastcall Script_SetRotatesTexture(void *L) {
+81 -48
View File
@@ -44,13 +44,14 @@
// (FUN_007724A0) maps each fresh text node to its OWNING FONTSTRING (1.12
// chat lines are real CSimpleFontStrings — the ScrollingMessageFrame's
// display refresh FUN_00788750 SetTexts/anchors/shows one per visible
// line). The paint-tail flush walks the icon records and queues each to
// line). When the string is built, and again when it moves
// (TextBlockSetStringPos), its icon records are applied to
// `Text::InlineTexturePool`, which configures a pooled engine-managed
// CSimpleTexture ANCHORED TO THE OWNING FONTSTRING at the pen offset —
// exactly how 4.3.4's UpdateEmbeddedTextures anchors its embedded
// textures. The engine draws the region every frame (residency) and the
// anchor system moves it with its line on every scroll/shift (zero
// per-frame work, no render transforms, no mid-render mutation).
// textures. The fontstring draws the textures with its text, and the
// anchor system moves them with their line (no per-frame work, no render
// transforms, no mid-render mutation).
//
// Supports the full positional payload
// `|Tpath:height:width:offsetX:offsetY:texW:texH:left:right:top:bottom:r:g:b|t`
@@ -1855,21 +1856,16 @@ static const Game::HookAutoRegister _emitterHook{Offsets::FUN_TEXT_EMITTER,
reinterpret_cast<void *>(&Emitter_h),
reinterpret_cast<void **>(&g_emitterOriginal)};
// --- paint co-hook: queue recorded icons as region placements ---------------
using Paint_t = void(__fastcall *)(void *layout);
Paint_t g_paintOriginal = nullptr;
// --- icon placements -------------------------------------------------------
// Builds the region placements for `node`'s recorded icons, expressed RELATIVE
// to the owning fontstring `fs`'s rect min corner (the pool anchors them there,
// so the engine moves them with the line). Fills `out` and returns true ONLY
// when everything the placement needs is ready this instant — K live (raster
// globals written) and the fs rect resolved. Returns false otherwise, and the
// caller must NOT queue an empty set (that would hide the icons and the dedup
// would freeze them hidden — the scroll-landing bug's second head). Shared by
// the paint flush and the rebuild refresh (RefreshIcons) so both produce
// bit-identical placements (the pool's dedup depends on that). The per-icon
// geometry is what the emitter recorded — see its icon loop.
// caller applies nothing (an empty set would hide the icons). Shared by the
// rebuild (RefreshIcons) and the move (MoveIcons). The per-icon geometry is
// what the emitter recorded — see its icon loop.
bool ComputePlacementsForNode(void *node, void *fs,
std::vector<Text::InlineTexturePool::Placement> &out) {
if (!LooksReadable(node) || !LooksReadable(fs))
@@ -1881,6 +1877,12 @@ bool ComputePlacementsForNode(void *node, void *fs,
if (!(K.x > 1.0f) || !(K.y > 1.0f))
return false;
auto *n = reinterpret_cast<uint8_t *>(node);
// The origin is the pixel anchor only while the node is laid out: with no
// built lines, the origin finalize (FUN_TEXT_NODE_FINALIZE_ORIGIN) copies
// the raw normalized position into it and returns before the justify and
// the pixel rounding. Callers lay the node out first (FUN_TEXT_ENSURE_BUILT).
if (Game::Read<int>(n, Offsets::OFF_TEXT_NODE_BUILT_LINES) == 0)
return false;
const float ox = Game::Read<float>(n, Offsets::OFF_TEXT_NODE_ORIGIN_X);
const float oy = Game::Read<float>(n, Offsets::OFF_TEXT_NODE_ORIGIN_Y);
// Same pixel-snap mode the emitter honours (bit-7 clear) — gates the
@@ -1927,13 +1929,15 @@ bool ComputePlacementsForNode(void *node, void *fs,
return true;
}
// Walks the layout's live render nodes and, for each recorded icon, computes
// its screen geometry (node-local pen coords translated by the node's screen
// origin +0x70/+0x74 — the SAME transform the paint pass applies to glyph
// batches) and queues it to Text::InlineTexturePool as a placement RELATIVE TO
// THE OWNING FONTSTRING. Runs after the original paint so icon coords and the
// fs rect are read in one coherent snapshot; the pool applies placements on
// the next FrameTick (regions are never mutated mid-render).
// --- paint co-hook: upkeep of the painted nodes ------------------------------
using Paint_t = void(__fastcall *)(void *layout);
Paint_t g_paintOriginal = nullptr;
// Walks the layout's live render nodes after the original paint: re-dirties a
// stuck-blockless fontstring, drops stale icon records, and mirrors the live
// alpha into baked glyph colours. Icon placement is not done here — the
// rebuild and the move apply it (RefreshIcons, MoveIcons).
void FlushLayout(void *layout) {
if (!LooksReadable(layout))
return;
@@ -1948,13 +1952,10 @@ void FlushLayout(void *layout) {
auto *n = reinterpret_cast<uint8_t *>(node);
void *const next = Game::Read<void *>(n, linkOff + 4);
// Resolve the owning fontstring up front: a node with NO icons must
// still clear its fontstring's regions — the fs may have just been
// re-SetText'd from icon text to plain text (chat line slot reuse).
// A node only speaks for its fontstring while it IS the fontstring's
// CURRENT text node (fs+0xF8 → handle+8): around a rebuild, the old and
// new node can both be walked in one paint, and letting the stale one
// queue (especially a clear) made icons vanish nondeterministically.
// Resolve the owning fontstring up front. A node only speaks for its
// fontstring while it IS the fontstring's CURRENT text node (fs+0xF8 →
// handle+8): around a rebuild, the old and new node can both be walked
// in one paint.
void *fs = nullptr;
{
auto ow = g_nodeOwner.find(node);
@@ -1981,7 +1982,7 @@ void FlushLayout(void *layout) {
// which lied on pfUI chat lines and made the old node-text scan erase
// LIVE records). A node with records whose owning fs currently shows
// text WITHOUT any |T (e.g. a recycled nameplate name that inherited a
// dead emote node's address) is stale: erase and clear. False matches
// dead emote node's address) is stale: erase. False matches
// can only false-KEEP (safe), never false-erase.
// (NOTE: do NOT build-version records against the builder counter — the
// builder runs every paint but only emits when dirty, so a version
@@ -1995,8 +1996,6 @@ void FlushLayout(void *layout) {
}
}
if (it == g_nodeIcons.end() || it->second.empty()) {
if (fs != nullptr)
Text::InlineTexturePool::QueuePlacements(fs, {});
node = next;
continue;
}
@@ -2020,9 +2019,9 @@ void FlushLayout(void *layout) {
// put while the icons faded. Mirror the live alpha into every
// baked colour, change-detected on each page's first entry (all
// baked alphas are uniform — the engine's own |c splice writes the
// node alpha too). One-frame lag (flush runs post-paint), same as
// the icon fade mirror. Chat (bit-3 clear) is excluded: the engine
// re-bakes those on colour change itself.
// node alpha too). One-frame lag (flush runs post-paint). Chat
// (bit-3 clear) is excluded: the engine re-bakes those on colour
// change itself.
if ((Game::Read<uint32_t>(n, Offsets::OFF_TEXT_NODE_FLAGS) & 8u) != 0) {
const uint32_t liveColor = Game::Read<uint32_t>(n, Offsets::OFF_TEXT_NODE_COLOR);
auto baked = g_nodeBakedColor.find(node);
@@ -2055,18 +2054,6 @@ void FlushLayout(void *layout) {
}
}
}
// Geometry + readiness gate factored into ComputePlacementsForNode
// (shared with the rebuild refresh, RefreshIcons, so both produce
// bit-identical placements — the pool dedup depends on it). It
// returns false when K or the fs rect isn't ready; SKIP the queue
// then and retry next paint. An empty queue here would HIDE the
// line's icons and the dedup would freeze it hidden forever
// (identical empty re-queues never dirty) — the scroll-landing
// bug's second head, where lines painted before K was available
// queued {} and stayed iconless until their text changed.
std::vector<Text::InlineTexturePool::Placement> places;
if (ComputePlacementsForNode(node, fs, places))
Text::InlineTexturePool::QueuePlacements(fs, std::move(places));
node = next;
}
}
@@ -2101,8 +2088,7 @@ static const Game::HookAutoRegister _paintHook{Offsets::FUN_TEXT_PAINT,
// the paint makes, FUN_TEXT_ENSURE_BUILT, idempotent) and applies the
// placements at once. The icons then draw with the text in the same frame
// wherever the string was rebuilt: a chat line laid out by its frame, a
// tooltip line, a rect change. The paint flush stays the backstop for a
// string whose placements can not be computed yet (K or the rect not ready).
// tooltip line, a rect change.
using EnsureBuilt_t = int(__fastcall *)(void *node);
@@ -2124,7 +2110,7 @@ void RefreshIcons(void *fs) {
reinterpret_cast<EnsureBuilt_t>(Offsets::FUN_TEXT_ENSURE_BUILT)(node);
std::vector<Text::InlineTexturePool::Placement> places;
if (ComputePlacementsForNode(node, fs, places))
Text::InlineTexturePool::ApplyNow(fs, std::move(places));
Text::InlineTexturePool::Apply(fs, std::move(places));
}
// SEH latch mirroring SafeFlush — a fault disables the whole feature for the
@@ -2137,6 +2123,53 @@ void SafeRefreshIcons(void *fs) {
}
}
// --- moves ---------------------------------------------------------------------
//
// A fontstring that moves without changing size keeps its built string: its
// rect callback (FUN_FONTSTRING_ON_FRAME_SIZE_CHANGED), SetTextOffset and the
// animation translation only move it, through TextBlockSetStringPos, which
// re-finalizes the node origin before it returns. The origin is rounded to
// whole render-target pixels, so the icons' offsets from the fontstring rect
// change with the move (up to 0.9 px measured over chat scrolls). Re-applying
// them after each move keeps every icon on its glyphs' pixel grid. The node
// may not be laid out at the move (a colour change invalidates it until the
// next paint), so the move lays it out first, as the rebuild does.
using SetStringPos_t = void(__fastcall *)(void *block, const float *position);
SetStringPos_t g_setStringPosOriginal = nullptr;
void MoveIcons(void *block) {
void *node = Game::Read<void *>(block, Offsets::OFF_TEXTBLOCK_NODE);
if (!LooksReadable(node))
return;
void *fs = OwningFontStringOf(node);
if (fs == nullptr || g_nodeIcons.find(node) == g_nodeIcons.end())
return;
reinterpret_cast<EnsureBuilt_t>(Offsets::FUN_TEXT_ENSURE_BUILT)(node);
std::vector<Text::InlineTexturePool::Placement> places;
if (ComputePlacementsForNode(node, fs, places))
Text::InlineTexturePool::Apply(fs, std::move(places));
}
// SEH latch mirroring SafeRefreshIcons.
void SafeMoveIcons(void *block) {
__try {
MoveIcons(block);
} __except (EXCEPTION_EXECUTE_HANDLER) {
g_inlineEnabled = false;
}
}
void __fastcall SetStringPos_h(void *block, const float *position) {
g_setStringPosOriginal(block, position);
if (g_inlineEnabled && LooksReadable(block))
SafeMoveIcons(block);
}
static const Game::HookAutoRegister _setStringPosHook{
Offsets::FUN_TEXTBLOCK_SET_STRING_POS, reinterpret_cast<void *>(&SetStringPos_h),
reinterpret_cast<void **>(&g_setStringPosOriginal)};
// --- Lua control surface ---------------------------------------------------
// _classicapi_InlineTexEnable([on]) -> enabled. The feature kill switch (also
+88 -171
View File
@@ -42,10 +42,10 @@ using SetPoint_t = void(__thiscall *)(void *anchor, int point, void *relAnchor,
float x, float y, int flag);
using Realize_t = void(__thiscall *)(void *anchor, int flag);
using SetTexCoord_t = void(__thiscall *)(void *tex, const float *coords4);
using SetLayoutScale_t = int(__thiscall *)(void *layout, float scale, int force);
using DeletingDestructor_t = void(__thiscall *)(void *region, int flags);
using Emit_t = void(__fastcall *)(void *region, void *edx, void *batch);
using NotifyLayerChanged_t = void(__fastcall *)(void *region);
using OnColorChanged_t = void(__fastcall *)(void *fs, void *edx, int changed);
// LAA-aware pointer sanity probe: Text::LooksReadable (text/PtrProbe.h).
@@ -55,25 +55,15 @@ using NotifyLayerChanged_t = void(__fastcall *)(void *region);
struct IconRegion {
void *tex = nullptr;
std::string path;
// Accumulated offset-scale correction, converged from rect readback (see
// the verification pass in Maintain). Starts at 1; survives reuse (the
// resolver scale is a property of the fontstring's scale, not the
// placement).
float corr = 1.0f;
};
// Keyed by FONTSTRING (stable across SetText — text nodes are reallocated per
// rebuild, so a node key would orphan textures every chat scroll step: the
// "wall of icons" bug).
struct FsPlacements {
std::vector<Placement> want; // queued by the paint hook
bool dirty = false;
std::vector<Placement> want; // the placements the textures carry
std::vector<IconRegion> regions; // textures currently serving this fs
int shown = 0; // how many of `regions` the fs draws
// The fs colour key (folded BGRA colors[0] dword) last applied to the
// drawn textures (the fade mirror — see FsColorKey below). Re-applied on
// change only.
uint32_t appliedColor = 0xFFFFFFFFu;
};
std::unordered_map<void *, FsPlacements> g_fsIcons;
@@ -103,7 +93,7 @@ void OnRegionDestroyed(void *region) {
const Frame::RegionDestruction::AutoSubscribe _regionDestructionSub{&OnRegionDestroyed};
// Latched off by Maintain's SEH guard on a fault; re-armed on /reload (see
// Latched off by the pool's SEH guards on a fault; re-armed on /reload (see
// PrepareForReload). Mirrors InlineTexture.cpp's g_inlineEnabled paint latch.
bool g_maintainDisabled = false;
@@ -112,7 +102,8 @@ bool g_maintainDisabled = false;
// fader animates each visible line fontstring's alpha through the fs SetColor
// every frame (see OFF_FONTSTRING_COLOR_ARRAY's derivation), and the engine
// keeps the byte folded with the frame-chain effective alpha. Count 0 = never
// coloured = opaque white default.
// coloured = opaque white default. The icons have no frame, so this is the
// only alpha they get (see OnColorChanged_h).
uint32_t FsColorKey(const void *fs) {
if (Game::Read<uint32_t>(fs, Offsets::OFF_FONTSTRING_COLOR_COUNT) < 1u)
return 0xFFFFFFFFu;
@@ -172,17 +163,6 @@ void DeleteRegion(void *tex) {
vtable[Offsets::VTBL_REGION_DELETING_DESTRUCTOR / sizeof(void *)](tex, 1);
}
// Gives the texture the fontstring's scale, as a draw layer gives a region its
// frame's (AddRegionToLayer 0x0076A860, through the same layout slot).
void MatchScale(void *tex, void *fs) {
const float scale = Game::Read<float>(fs, Offsets::OFF_LAYOUT_SCALE);
if (!(scale > 0.0f) || Game::Read<float>(tex, Offsets::OFF_LAYOUT_SCALE) == scale)
return;
void *layout = static_cast<uint8_t *>(tex) + Offsets::OFF_REGION_ANCHOR;
auto *vtable = Game::Read<SetLayoutScale_t *>(layout, 0);
vtable[Offsets::VTBL_LAYOUT_SET_LAYOUT_SCALE / sizeof(void *)](layout, scale, 0);
}
// Applies one placement to one texture: image, texcoords, color (with the
// line's fade alpha folded in), and the two anchor points expressed relative
// to the owning fontstring's BOTTOMLEFT (so the engine moves the icon with its
@@ -210,42 +190,27 @@ void ApplyPlacement(IconRegion &r, void *fs, const Placement &p, uint32_t fsColo
const uint32_t color = FadedColor(p, fsColor);
reinterpret_cast<SetColor_t>(Offsets::FUN_FONTSTRING_SET_COLOR)(r.tex, &color);
// Placement coords are in RESOLVED-rect (anchor) units, but anchor
// resolution multiplies STORED SetPoint offsets by the positioned region's
// effective scale chain (+0x7C — uiScale × per-frame scales). Verified from
// the probe: a 50px SetPoint offset stored as 0.0319 internal resolved to a
// rect at 0.0290 = 0.0319 × s (s = 0.91). So divide the desired resolved
// delta by the texture's own scale before storing.
float sReg = Game::Read<float>(r.tex, Offsets::OFF_LAYOUT_SCALE);
if (!(sReg > 0.01f && sReg < 100.0f))
sReg = Game::Read<float>(f, Offsets::OFF_LAYOUT_SCALE);
const float inv = (sReg > 0.01f && sReg < 100.0f) ? 1.0f / sReg : 1.0f;
// Single deterministic placement; the resolver's true offset scale is
// converged by the verification pass in Maintain via r.corr (a same-call
// rect readback is unreliable: fresh textures read zeros and reused pooled
// textures read their PREVIOUS placement — that poisoned fix rendered the
// 14px crest at 7.4px).
const float scale = inv * r.corr;
// Placement coords are in resolved-rect (anchor) units. The resolver places
// a point at the positioned region's own layout scale × the stored offset
// + the relative edge (RelativePointGetX/Y 0x7A2F90/0x7A3070); the texture
// has no frame, so nothing changes the ctor's scale of 1 (CLayoutFrame
// 0x00767680) and the offsets land exactly as given, as 4.3.4's
// CSimpleEmbeddedTexture's do.
auto setPoint = reinterpret_cast<SetPoint_t>(Offsets::FUN_REGION_SET_POINT);
void *texAnchor = reinterpret_cast<uint8_t *>(r.tex) + Offsets::OFF_REGION_ANCHOR;
void *fsAnchor = f + Offsets::OFF_REGION_ANCHOR;
setPoint(texAnchor, Offsets::FRAMEPOINT_BOTTOMLEFT, fsAnchor, Offsets::FRAMEPOINT_BOTTOMLEFT,
p.x0 * scale, p.y0 * scale, 1);
p.x0, p.y0, 1);
setPoint(texAnchor, Offsets::FRAMEPOINT_TOPRIGHT, fsAnchor, Offsets::FRAMEPOINT_BOTTOMLEFT,
p.x1 * scale, p.y1 * scale, 1);
p.x1, p.y1, 1);
reinterpret_cast<Realize_t>(Offsets::FUN_REGION_LAYOUT_REALIZE)(texAnchor, 0);
}
// Apply the queued `want` for one fs to its textures: create and configure
// each, and clear the dirty flag. The layer batch copies the texture set,
// images and colour counts when it is built (FUN_00772FD0), so the
// fontstring's layer is marked for a rebuild — the call SetTexture makes for
// a texture in a layer. Shared by MaintainImpl's dirty branch and the
// synchronous ApplyNow path. Caller supplies the folded fs colour
// (FsColorKey) so both paths fold the same fade.
void ApplyDirtyBranch(void *fs, FsPlacements &np, uint32_t fsColor) {
np.dirty = false;
// Applies `want` to the fontstring's textures: create and configure each. The
// layer batch copies the texture set, images and colour counts when it is
// built (FUN_00772FD0), so the fontstring's layer is marked for a rebuild —
// the call SetTexture makes for a texture in a layer.
void ApplyPlacements(void *fs, FsPlacements &np, uint32_t fsColor) {
const int want = static_cast<int>(np.want.size());
for (int i = 0; i < want; ++i) {
if (i >= static_cast<int>(np.regions.size())) {
@@ -255,97 +220,32 @@ void ApplyDirtyBranch(void *fs, FsPlacements &np, uint32_t fsColor) {
np.regions.push_back(IconRegion{tex, std::string()});
}
IconRegion &r = np.regions[static_cast<size_t>(i)];
MatchScale(r.tex, fs);
ApplyPlacement(r, fs, np.want[static_cast<size_t>(i)], fsColor);
}
np.shown = (want < static_cast<int>(np.regions.size()))
? want
: static_cast<int>(np.regions.size());
np.appliedColor = fsColor;
reinterpret_cast<NotifyLayerChanged_t>(Offsets::FUN_REGION_NOTIFY_LAYER_CHANGED)(fs);
}
// Per-frame tick (FrameTick — glue AND world): apply queued placements
// (deferred out of the text paint). Wrapped by Maintain() below; kept
// destructor-holding C++ objects out of the SEH frame (MSVC won't allow __try
// in a function that needs object unwinding).
// Per-frame tick (FrameTick — glue AND world): deletes orphaned textures.
// Wrapped by Maintain() below; kept destructor-holding C++ objects out of the
// SEH frame (MSVC won't allow __try in a function that needs object
// unwinding).
void MaintainImpl() {
if (!g_orphans.empty()) {
std::vector<void *> orphans;
orphans.swap(g_orphans);
for (void *tex : orphans)
DeleteRegion(tex);
}
for (auto &entry : g_fsIcons) {
void *fs = entry.first;
FsPlacements &np = entry.second;
// The line's live folded colour (see FsColorKey) — folded into every
// color write below and mirrored on change.
const uint32_t fsColor = FsColorKey(fs);
if (np.dirty) {
ApplyDirtyBranch(fs, np, fsColor);
} else if (np.shown > 0 && fsColor != np.appliedColor) {
// FADE MIRROR: the ScrollingMessageFrame fader animates the line
// fontstring's color alpha every frame, and the glue AddonList
// swaps title RGB on toggle; keep the icon textures' colour in
// lockstep (alpha everywhere, value-follow on glue — see
// FadedColor) so inline icons fade/dim with their text. The batch
// reads the colour through a pointer, so no rebuild. Change-
// driven — steady state costs one dword compare.
np.appliedColor = fsColor;
const int live = (np.shown < static_cast<int>(np.want.size()))
? np.shown
: static_cast<int>(np.want.size());
for (int i = 0; i < live && i < static_cast<int>(np.regions.size()); ++i) {
IconRegion &r = np.regions[static_cast<size_t>(i)];
const uint32_t color = FadedColor(np.want[static_cast<size_t>(i)], fsColor);
reinterpret_cast<SetColor_t>(Offsets::FUN_FONTSTRING_SET_COLOR)(r.tex, &color);
}
}
// Convergence pass: compare each drawn texture's RESOLVED width against
// its wanted width and fold the ratio into the texture's correction.
// The resolver's true offset scale is whatever it is (uiScale chains,
// pfUI frame scales) — a tick or two of this converges the placement
// exactly and self-heals any stale-pool or timing artifact. 0.5%
// deadband.
const int live = (np.shown < static_cast<int>(np.want.size()))
? np.shown
: static_cast<int>(np.want.size());
for (int i = 0; i < live && i < static_cast<int>(np.regions.size()); ++i) {
IconRegion &r = np.regions[static_cast<size_t>(i)];
const Placement &p = np.want[static_cast<size_t>(i)];
const float wantW = p.x1 - p.x0;
if (wantW <= 1e-6f)
continue;
const float *rr = reinterpret_cast<const float *>(
reinterpret_cast<uint8_t *>(r.tex) + Offsets::OFF_REGION_RECT);
const float gotW = (rr[3] > rr[1]) ? (rr[3] - rr[1]) : (rr[1] - rr[3]);
if (gotW <= 1e-7f) {
ApplyPlacement(r, fs, p, fsColor); // rect not resolved yet — re-kick
continue;
}
const float err = gotW / wantW;
if (err > 1.005f || err < 0.995f) {
r.corr *= wantW / gotW;
if (r.corr < 0.05f)
r.corr = 0.05f;
else if (r.corr > 20.0f)
r.corr = 20.0f;
ApplyPlacement(r, fs, p, fsColor);
}
}
}
if (g_orphans.empty())
return;
std::vector<void *> orphans;
orphans.swap(g_orphans);
for (void *tex : orphans)
DeleteRegion(tex);
}
// SEH latch mirroring InlineTexture.cpp's SafeFlush: the tick drives engine
// texture calls (SetTexture with addon-supplied paths, SetPoint) from
// paint-time data, so a fault disables maintenance for the session instead of
// crashing the client. A /reload re-arms it (PrepareForReload). The __try body
// holds no C++ objects — see MaintainImpl.
// SEH latch mirroring InlineTexture.cpp's SafeFlush: the pool drives engine
// texture calls (SetTexture with addon-supplied paths, SetPoint), so a fault
// disables it for the session instead of crashing the client. A /reload
// re-arms it (PrepareForReload). The __try body holds no C++ objects — see
// MaintainImpl.
void Maintain() {
if (g_maintainDisabled)
return;
@@ -356,26 +256,27 @@ void Maintain() {
}
}
// Synchronous apply for ONE fs. Applies only when its entry is still dirty
// (i.e. QueuePlacements did NOT dedup the re-queue).
void ApplyNowImpl(void *fs) {
// Applies `icons` to one fontstring unless its textures already carry them.
void ApplyImpl(void *fs, std::vector<Placement> &icons) {
auto it = g_fsIcons.find(fs);
if (it == g_fsIcons.end())
return;
if (it == g_fsIcons.end()) {
if (icons.empty())
return; // nothing drawn, nothing wanted — don't create state
it = g_fsIcons.emplace(fs, FsPlacements{}).first;
}
FsPlacements &np = it->second;
if (!np.dirty)
return; // deduped re-queue: already applied, nothing to do
ApplyDirtyBranch(fs, np, FsColorKey(fs));
if (np.want == icons && np.shown == static_cast<int>(icons.size()))
return;
np.want = std::move(icons);
ApplyPlacements(fs, np, FsColorKey(fs));
}
// SEH split mirroring Maintain/MaintainImpl — the __try body holds no C++
// objects needing unwinding (see MaintainImpl). A fault latches the same
// maintenance kill switch as the tick path.
void SafeApplyNow(void *fs) {
// SEH split mirroring Maintain/MaintainImpl, on the same kill switch.
void SafeApply(void *fs, std::vector<Placement> &icons) {
if (g_maintainDisabled)
return;
__try {
ApplyNowImpl(fs);
ApplyImpl(fs, icons);
} __except (EXCEPTION_EXECUTE_HANDLER) {
g_maintainDisabled = true;
}
@@ -410,35 +311,52 @@ void __fastcall Emit_h(void *fs, void *edx, void *batch) {
const Game::HookAutoRegister _emitHook{Offsets::FUN_FONTSTRING_EMIT, reinterpret_cast<void *>(&Emit_h),
reinterpret_cast<void **>(&g_origEmit)};
} // namespace
// The fontstring's colour change (FUN_FONTSTRING_ON_COLOR_CHANGED), where
// 4.3.4's CSimpleFontString::OnColorChanged copies the string's alpha into its
// embedded textures. Every change of the fs colour ends here, folded by the
// time the original returns, so the icons take the line's fade (and, on glue,
// its value — see FadedColor) in the same call. The batch reads the colour
// through a pointer, so no rebuild.
OnColorChanged_t g_origOnColorChanged = nullptr;
void QueuePlacements(void *fs, std::vector<Placement> &&icons) {
if (fs == nullptr)
return;
auto it = g_fsIcons.find(fs);
if (it == g_fsIcons.end()) {
if (icons.empty())
return; // nothing drawn, nothing wanted — don't create state
FsPlacements np;
np.want = std::move(icons);
np.dirty = true;
g_fsIcons.emplace(fs, std::move(np));
void MirrorFade(void *fs) {
const auto it = g_fsIcons.find(fs);
if (it == g_fsIcons.end())
return;
const FsPlacements &np = it->second;
const uint32_t fsColor = FsColorKey(fs);
for (int i = 0; i < np.shown; ++i) {
const uint32_t color = FadedColor(np.want[static_cast<size_t>(i)], fsColor);
reinterpret_cast<SetColor_t>(Offsets::FUN_FONTSTRING_SET_COLOR)(
np.regions[static_cast<size_t>(i)].tex, &color);
}
FsPlacements &np = it->second;
if (np.want == icons)
return; // identical re-queue (the per-paint steady state) — no work
np.want = std::move(icons);
np.dirty = true;
}
void ApplyNow(void *fs, std::vector<Placement> &&icons) {
// Queue first (sets want+dirty, dedups an unchanged re-queue), then apply
// synchronously for this fs. Deduped re-queues leave the entry not-dirty,
// so SafeApplyNow no-ops — a steady state costs one compare, same as
// QueuePlacements.
QueuePlacements(fs, std::move(icons));
SafeApplyNow(fs);
// SEH split mirroring Maintain/MaintainImpl, on the same kill switch.
void SafeMirrorFade(void *fs) {
if (g_maintainDisabled)
return;
__try {
MirrorFade(fs);
} __except (EXCEPTION_EXECUTE_HANDLER) {
g_maintainDisabled = true;
}
}
void __fastcall OnColorChanged_h(void *fs, void *edx, int changed) {
g_origOnColorChanged(fs, edx, changed);
SafeMirrorFade(fs);
}
const Game::HookAutoRegister _colorHook{Offsets::FUN_FONTSTRING_ON_COLOR_CHANGED,
reinterpret_cast<void *>(&OnColorChanged_h),
reinterpret_cast<void **>(&g_origOnColorChanged)};
} // namespace
void Apply(void *fs, std::vector<Placement> &&icons) {
if (fs != nullptr)
SafeApply(fs, icons);
}
void Release(void *fs) {
@@ -448,7 +366,6 @@ void Release(void *fs) {
// The rebuild that called this marks the fontstring's layer itself.
it->second.want.clear();
it->second.shown = 0;
it->second.dirty = false;
}
void PrepareForReload() {
+17 -24
View File
@@ -17,14 +17,16 @@
// CSimpleEmbeddedTexture model.
//
// One pooled CSimpleTexture per inline icon, anchored RELATIVE TO THE OWNING
// FONTSTRING at offsets converted from pen space via the fs+0x7C scale bridge
// (see InlineTexture.cpp's FlushLayout). As in 4.3.4 the texture has no frame,
// FONTSTRING at offsets converted from pen space (see InlineTexture.cpp's
// ComputePlacementsForNode). As in 4.3.4 the texture has no frame,
// so it is in no draw layer: the fontstring draws it. Its draw call
// (FUN_FONTSTRING_EMIT, 4.3.4's CSimpleFontString::Draw → QueueTextures) adds
// the icons to the layer batch right after its text, so an icon draws exactly
// when its line's text does - shown, hidden, faded out, off screen - in the
// same frame. Engine-drawn → resident by construction; engine-anchored →
// tracks the fontstring's movement for free.
// tracks the fontstring's movement. The placements are applied when the
// string is built and again after each move, since the move re-rounds the
// glyph origin (see InlineTexture.cpp's MoveIcons).
#include <cstdint>
#include <string>
@@ -34,12 +36,10 @@ namespace Text::InlineTexturePool {
// One icon's target geometry, in anchor-space units RELATIVE TO THE OWNING
// FONTSTRING's rect min corner (y up, same units as the region rect at +0x64).
// Computed entirely at PAINT time — icon coords and fs rect read in the same
// flush, a coherent snapshot — so the pool applies it verbatim with no
// apply-time rect read (an apply-time read raced the chat relayout after
// SetText and parked icons off their line, where the dedup froze them: the
// scroll-landing "randomly hidden icon" bug). Relative offsets are also
// position-invariant, so scrolling a line re-queues nothing.
// Computed from the laid-out node and the fs rect in one read, so the pool
// applies it verbatim with no apply-time rect read (an apply-time read raced
// the chat relayout after SetText and parked icons off their line: the
// scroll-landing "randomly hidden icon" bug).
struct Placement {
std::string path;
float x0, y0, x1, y1;
@@ -48,26 +48,19 @@ struct Placement {
};
// Exact compare is correct here: unchanged layouts reproduce bit-identical
// floats, and that's precisely the "nothing moved" case the dedup wants.
// floats, and that's precisely the "nothing changed" case Apply skips.
inline bool operator==(const Placement &a, const Placement &b) {
return a.x0 == b.x0 && a.y0 == b.y0 && a.x1 == b.x1 && a.y1 == b.y1 && a.color == b.color &&
a.u0 == b.u0 && a.v0 == b.v0 && a.u1 == b.u1 && a.v1 == b.v1 && a.path == b.path;
}
// Queue the icon set for a FONTSTRING (the stable entity — text nodes die on
// every SetText, so textures must not be keyed by node). Safe from the paint
// hook: only records data; the textures are configured on the next FrameTick.
// Identical re-queues are deduped, so calling every paint is cheap. An empty
// vector stops the fontstring drawing icons.
void QueuePlacements(void *fs, std::vector<Placement> &&icons);
// Like QueuePlacements, but ALSO applies the placements to their textures
// immediately (synchronously) instead of waiting for the next FrameTick, and
// marks the fontstring's layer for a batch rebuild so the icons draw with the
// text. Deduped against the current want, so a no-change re-apply is a cheap
// no-op. Faults are caught (latches the same maintenance kill switch as the
// tick path).
void ApplyNow(void *fs, std::vector<Placement> &&icons);
// Applies the icon set of a FONTSTRING (the stable entity — text nodes die on
// every SetText, so textures must not be keyed by node) to its textures at
// once and marks its layer for a batch rebuild, so the icons draw with the
// text. A set equal to the one applied is skipped. An empty vector stops the
// fontstring drawing icons. Faults are caught (latches the pool's kill
// switch, re-armed on /reload).
void Apply(void *fs, std::vector<Placement> &&icons);
// The fontstring's built string was replaced: it draws no icons until new
// placements arrive (4.3.4's FreeEmbeddedTextures at the top of UpdateString).