// 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 .
// Engine-region rendering for inline-|T icons — see the header. One pooled
// CSimpleTexture per visible icon, anchored to its owning fontstring; the
// engine draws it every frame like any UI region, so the texture is resident
// by construction and the icon moves with its line for free.
//
// A CSimpleTexture renders as a gxu text node whose page texture IS the
// region's CGxTex: the layout paint (FUN_005c8fe0) binds it (GxRsSet 0x17) and
// submits its quad EVERY FRAME the region is shown.
#include "text/InlineTexturePool.h"
#include "Game.h"
#include "Offsets.h"
#include "frame/Region.h"
#include "frame/RegionDestruction.h"
#include "text/PtrProbe.h"
#include "tick/FrameTick.h"
#include // SEH (__try/__except, EXCEPTION_EXECUTE_HANDLER)
#include
#include
#include
namespace Text::InlineTexturePool {
namespace {
using SetTexture_t = uint32_t(__thiscall *)(void *tex, const char *path, int a, uint32_t blend,
int b);
using SetColor_t = void(__thiscall *)(void *tex, const void *colorBGRA);
using SetPoint_t = void(__thiscall *)(void *anchor, int point, void *relAnchor, int relPoint,
float x, float y, int flag);
using Realize_t = void(__thiscall *)(void *anchor, int flag);
using ShowHide_t = void(__fastcall *)(void *tex);
// LAA-aware pointer sanity probe: Text::LooksReadable (text/PtrProbe.h).
using SetTexCoord_t = void(__thiscall *)(void *tex, const float *coords4);
using SetParentAndLayer_t = void(__thiscall *)(void *region, void *parentFrame, int layer,
int show);
// --- region placement state --------------------------------------------------
// A pooled icon region and the config it currently carries (for dedup).
struct IconRegion {
void *tex = nullptr;
void *parent = 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 parent chain, 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 regions every chat scroll step: the
// "wall of icons" bug).
struct FsPlacements {
std::vector want; // queued by the paint hook
bool dirty = false;
std::vector regions; // engine regions currently serving this fs
int shown = 0; // how many of `regions` are visible
// Maintain-tick of the last QueuePlacements touch (deduped ones included).
// A LIVE painted icon line is re-queued every paint; a parked/orphaned fs
// (recycled chat line whose node never rebuilds — the "ghost icons at the
// parked position" class) stops being touched entirely, so its regions
// expire via the freshness check in Maintain.
uint32_t lastTouchTick = 0;
// The fs colour key (folded BGRA colors[0] dword) last applied to the
// shown regions (the fade mirror — see FsColorKey below). Re-applied on
// change only.
uint32_t appliedColor = 0xFFFFFFFFu;
};
std::unordered_map g_fsIcons;
uint32_t g_maintainTick = 0;
// Every pooled icon region still alive, so OnRegionDestroyed can tell ours
// from the rest in one lookup.
std::unordered_set g_iconRegions;
// The regions of keys destroyed since the last tick. Their shown regions are
// hidden there, never from inside the destructor that reported the death.
std::vector> g_orphans;
// Drops `tex` from `regions`. For a live key's list, the regions after it now
// serve the wrong placements, so the key is re-placed.
void DropRegion(std::vector ®ions, void *tex, FsPlacements *np) {
for (size_t i = 0; i < regions.size(); ++i) {
if (regions[i].tex != tex)
continue;
regions.erase(regions.begin() + static_cast(i));
if (np != nullptr) {
if (static_cast(i) < np->shown)
--np->shown;
np->dirty = true;
}
return;
}
}
// Frame::RegionDestruction. A destroyed key fontstring takes its entry with it
// at once: its block goes back to the region pool and can come back as an
// unrelated fontstring at the same address, which must start with no entry.
// Its regions live on, parented to its parent frame (unless that frame is the
// one dying, when they are reported here too), and are hidden at the next
// tick. A destroyed icon region is dropped wherever it is held. This runs
// inside a frame's destructor, so it changes no region itself.
//
// ACCEPTED LEAK: an orphan's regions are hidden, not reclaimed. They stay on
// their parent frame until it dies (/reload frees all of them). Chat and
// tooltip fontstrings are a reused, never-destroyed set, so only destroyed
// transient |T fontstrings leave regions behind.
void OnRegionDestroyed(void *region) {
const auto it = g_fsIcons.find(region);
if (it != g_fsIcons.end()) {
g_orphans.push_back(std::move(it->second.regions));
g_fsIcons.erase(it);
return;
}
if (g_iconRegions.erase(region) == 0)
return;
for (auto &entry : g_fsIcons)
DropRegion(entry.second.regions, region, &entry.second);
for (std::vector &orphan : g_orphans)
DropRegion(orphan, region, nullptr);
}
const Frame::RegionDestruction::AutoSubscribe _regionDestructionSub{&OnRegionDestroyed};
// Latched off by Maintain's SEH guard on a fault; re-armed on /reload (see
// PrepareForReload). Mirrors InlineTexture.cpp's g_inlineEnabled paint latch.
bool g_maintainDisabled = false;
void Show(void *tex) {
// Show no-ops unless the desired-shown flag (+0xC4) is set; engine callers
// always write it first (see the region RE notes).
*reinterpret_cast(reinterpret_cast(tex) +
Offsets::OFF_REGION_DESIRED_SHOWN) = 1;
reinterpret_cast(Offsets::FUN_FONTSTRING_SHOW)(tex);
}
void Hide(void *tex) {
*reinterpret_cast(reinterpret_cast(tex) +
Offsets::OFF_REGION_DESIRED_SHOWN) = 0;
reinterpret_cast(Offsets::FUN_FONTSTRING_HIDE)(tex);
}
// The fontstring's live folded colour (slot 0's BGRA dword) — THE FADE
// SIGNAL. Its alpha byte is the chat-fade channel: the ScrollingMessageFrame's
// 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.
uint32_t FsColorKey(const void *fs) {
if (Game::Read(fs, Offsets::OFF_FONTSTRING_COLOR_COUNT) < 1u)
return 0xFFFFFFFFu;
const uint8_t *colors = Game::Read(fs, Offsets::OFF_FONTSTRING_COLOR_ARRAY);
if (!LooksReadable(colors))
return 0xFFFFFFFFu;
return *reinterpret_cast(colors); // slot 0, BGRA
}
// Placement colour with the fs's live colour folded in. The markup tint's own
// alpha (0xFF except explicit tints) is modulated by the line's live alpha —
// everywhere. On the GLUE screen the icon's brightness ALSO follows the text
// colour's VALUE (max of R/G/B): the glue AddonList greys disabled entries
// through SetTextColor RGB alone (alpha stays 1.0), so value-follow is the
// only channel that dims a disabled addon title's icons with its text. It can
// never TINT — a gold or red title has a 255-max channel, factor 1.0, icons
// untouched — and it is gated to glue (no local player) so in-world text
// colours (guild green, whisper pink) keep icons exactly as before.
uint32_t FadedColor(const Placement &p, uint32_t fsColor) {
const uint32_t a = ((p.color >> 24) * (fsColor >> 24)) / 0xFFu;
uint32_t rgb = p.color & 0x00FFFFFFu;
const bool inGlue =
*reinterpret_cast(Offsets::VAR_LOCAL_PLAYER_PTR) == nullptr;
if (inGlue) {
const uint32_t b = fsColor & 0xFFu, g = (fsColor >> 8) & 0xFFu,
r = (fsColor >> 16) & 0xFFu;
uint32_t value = r > g ? r : g;
if (b > value)
value = b;
if (value < 0xFFu) {
const uint32_t pr = ((rgb >> 16) & 0xFFu) * value / 0xFFu;
const uint32_t pg = ((rgb >> 8) & 0xFFu) * value / 0xFFu;
const uint32_t pb = (rgb & 0xFFu) * value / 0xFFu;
rgb = (pr << 16) | (pg << 8) | pb;
}
}
return (a << 24) | rgb;
}
// Creates a bare pooled CSimpleTexture parented to `parent` (ARTWORK).
void *CreateRegion(void *parent) {
void *tex = Frame::Region::CreateTexture(parent, Offsets::DRAWLAYER_ARTWORK, 1);
if (tex == nullptr)
return nullptr;
g_iconRegions.insert(tex);
return tex;
}
// Applies one placement to one region: texture, 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
// line for free).
void ApplyPlacement(IconRegion &r, void *fs, const Placement &p, uint32_t fsColor) {
auto *f = reinterpret_cast(fs);
// Placement coords are FS-RELATIVE (from the fs rect's min corner), computed
// at PAINT time in the same flush as the icon coords. Do NOT read the fs
// rect here: an apply-time read raced the chat relayout (SetText briefly
// invalidates the rect) and parked icons off their line, where the dedup
// then froze them — the scroll-landing "randomly hidden icon" bug.
if (r.path != p.path) {
const uint32_t blend = Game::Read(Offsets::VAR_TEXTURE_BLEND_DEFAULT);
reinterpret_cast(Offsets::FUN_SIMPLETEXTURE_SET_TEXTURE)(r.tex, p.path.c_str(),
0, blend, 0);
r.path = p.path;
}
// The engine's 4-float texcoord rect is Y-FIRST INTERLEAVED — {v0, u0, v1,
// u1} — matching its {yA, left, yB, right} rect convention (diagnosed
// in-game: {u0,v0,u1,v1} rendered the raid-mark moon crop as the circle
// cell). v is top-down, same as the |T payload's top/bottom fields.
const float coords[4] = {p.v0, p.u0, p.v1, p.u1};
reinterpret_cast(Offsets::FUN_SIMPLETEXTURE_SET_TEXCOORD)(r.tex, coords);
const uint32_t color = FadedColor(p, fsColor);
reinterpret_cast(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 region's own scale before storing.
float sReg = Game::Read(r.tex, Offsets::OFF_LAYOUT_SCALE);
if (!(sReg > 0.01f && sReg < 100.0f))
sReg = Game::Read(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 regions read zeros and reused pooled
// regions read their PREVIOUS placement — that poisoned fix rendered the
// 14px crest at 7.4px).
const float scale = inv * r.corr;
auto setPoint = reinterpret_cast(Offsets::FUN_REGION_SET_POINT);
void *texAnchor = reinterpret_cast(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);
setPoint(texAnchor, Offsets::FRAMEPOINT_TOPRIGHT, fsAnchor, Offsets::FRAMEPOINT_BOTTOMLEFT,
p.x1 * scale, p.y1 * scale, 1);
reinterpret_cast(Offsets::FUN_REGION_LAYOUT_REALIZE)(texAnchor, 0);
Show(r.tex);
}
// Apply the queued `want` for one fs to its regions: create/reparent/configure
// each, hide surplus from a previously-larger set, and clear the dirty flag.
// Reads the fs's live parent at call time. Shared by MaintainImpl's dirty
// branch and the synchronous ApplyNow path (pre-render). 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;
void *parent = *reinterpret_cast(reinterpret_cast(fs) +
Offsets::OFF_REGION_PARENT);
if (!LooksReadable(parent))
return;
const int want = static_cast(np.want.size());
for (int i = 0; i < want; ++i) {
if (i >= static_cast(np.regions.size())) {
void *tex = CreateRegion(parent);
if (tex == nullptr)
break;
np.regions.push_back(IconRegion{tex, parent, std::string()});
}
IconRegion &r = np.regions[static_cast(i)];
if (r.parent != parent) {
reinterpret_cast(Offsets::FUN_REGION_SET_PARENT_AND_LAYER)(
r.tex, parent, Offsets::DRAWLAYER_ARTWORK, 0);
r.parent = parent;
}
ApplyPlacement(r, fs, np.want[static_cast(i)], fsColor);
}
// Hide surplus pooled regions from a previous, larger icon set.
for (int i = want; i < np.shown; ++i)
if (i < static_cast(np.regions.size()))
Hide(np.regions[static_cast(i)].tex);
np.shown = (want < static_cast(np.regions.size()))
? want
: static_cast(np.regions.size());
np.appliedColor = fsColor;
}
// Per-frame tick (FrameTick — glue AND world): apply queued placements
// (deferred out of the text paint — regions must never be mutated mid-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).
void MaintainImpl() {
++g_maintainTick;
// Hide the regions of keys destroyed since the last tick (see
// OnRegionDestroyed). Every region still listed is alive.
for (const std::vector &orphan : g_orphans)
for (const IconRegion &r : orphan)
Hide(r.tex);
g_orphans.clear();
for (auto it = g_fsIcons.begin(); it != g_fsIcons.end();) {
void *fs = it->first;
FsPlacements &np = it->second;
// Freshness expiry: a LIVE painted icon line re-queues every paint, so
// its touch stamp stays current. A parked/orphaned fs (recycled chat
// line whose node never rebuilds and may not even be walked) stops
// being touched — hide its regions and drop the stale want so nothing
// ghosts at the parked position. ~1s at a per-frame tick.
constexpr uint32_t kWantTTL = 60;
if (np.shown > 0 && g_maintainTick - np.lastTouchTick > kWantTTL) {
for (int i = 0; i < np.shown && i < static_cast(np.regions.size()); ++i)
Hide(np.regions[static_cast(i)].tex);
np.shown = 0;
np.want.clear();
np.dirty = false;
++it;
continue;
}
// Mirror the fontstring's own visibility EVERY tick, not just on dirty:
// expired/hidden chat lines get their fs Hidden by the message frame,
// and our regions are parented to the CHAT FRAME (regions can't parent
// regions), so they don't inherit the line's own hide. Every key is a
// live fontstring (OnRegionDestroyed drops a destroyed one at once).
const bool fsShown =
*reinterpret_cast(reinterpret_cast(fs) +
Offsets::OFF_REGION_ACTUALLY_SHOWN) != 0;
if (!fsShown) {
for (int i = 0; i < np.shown && i < static_cast(np.regions.size()); ++i)
Hide(np.regions[static_cast(i)].tex);
np.shown = 0;
np.dirty = true; // re-place if/when the fs shows again
++it;
continue;
}
// 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 regions' colour in
// lockstep (alpha everywhere, value-follow on glue — see
// FadedColor) so inline icons fade/dim with their text. Change-
// driven — steady state costs one dword compare.
np.appliedColor = fsColor;
const int live = (np.shown < static_cast(np.want.size()))
? np.shown
: static_cast(np.want.size());
for (int i = 0; i < live && i < static_cast(np.regions.size()); ++i) {
IconRegion &r = np.regions[static_cast(i)];
if (r.tex == nullptr)
continue;
const uint32_t color = FadedColor(np.want[static_cast(i)], fsColor);
reinterpret_cast(Offsets::FUN_FONTSTRING_SET_COLOR)(r.tex, &color);
}
}
// Convergence pass: compare each shown region's RESOLVED width against
// its wanted width and fold the ratio into the region'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(np.want.size()))
? np.shown
: static_cast(np.want.size());
for (int i = 0; i < live && i < static_cast(np.regions.size()); ++i) {
IconRegion &r = np.regions[static_cast(i)];
const Placement &p = np.want[static_cast(i)];
const float wantW = p.x1 - p.x0;
if (r.tex == nullptr || wantW <= 1e-6f)
continue;
const float *rr = reinterpret_cast(
reinterpret_cast(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);
}
}
++it;
}
}
// SEH latch mirroring InlineTexture.cpp's SafeFlush: the tick drives engine
// region calls (SetTexture with addon-supplied paths, SetPoint, Show) 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.
void Maintain() {
if (g_maintainDisabled)
return;
__try {
MaintainImpl();
} __except (EXCEPTION_EXECUTE_HANDLER) {
g_maintainDisabled = true;
}
}
// Synchronous apply for ONE fs (the pre-render early path). Applies only when
// the fs is a live, actually-shown fontstring and its entry is still dirty
// (i.e. QueuePlacements did NOT dedup the re-queue). Otherwise it leaves the
// entry for the normal tick path — best-effort, so a not-yet-shown or
// deduped line simply falls back to the one-frame-lagged behaviour.
void ApplyNowImpl(void *fs) {
auto it = g_fsIcons.find(fs);
if (it == g_fsIcons.end())
return;
FsPlacements &np = it->second;
if (!np.dirty)
return; // deduped re-queue: already applied, nothing to do
// Match Maintain's own visibility gate (actually-shown latch). The SMF's
// per-line Show realizes this synchronously before we run, so a visible
// line passes; a line not yet shown is left dirty for the tick path.
const bool fsShown =
*reinterpret_cast(reinterpret_cast(fs) +
Offsets::OFF_REGION_ACTUALLY_SHOWN) != 0;
if (!fsShown)
return;
ApplyDirtyBranch(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) {
if (g_maintainDisabled)
return;
__try {
ApplyNowImpl(fs);
} __except (EXCEPTION_EXECUTE_HANDLER) {
g_maintainDisabled = true;
}
}
// FrameTick, not WorldTick: icon regions are UI objects that also exist on the
// glue screen (addon-list titles with |T emotes), and FrameTick fires wherever
// the UI renders — glue and world. (An earlier FrameTick attempt was blamed
// for an in-world regression and reverted; that was the LAA pointer-bound
// phantom — see laa-pointer-bounds / dc61f77. Single tick is the clean design.)
static const Tick::FrameTick::AutoSubscribe _tick{&Maintain};
} // namespace
void QueuePlacements(void *fs, std::vector &&icons) {
if (fs == nullptr)
return;
auto it = g_fsIcons.find(fs);
if (it == g_fsIcons.end()) {
if (icons.empty())
return; // nothing shown, nothing wanted — don't create state
FsPlacements np;
np.want = std::move(icons);
np.dirty = true;
np.lastTouchTick = g_maintainTick;
g_fsIcons.emplace(fs, std::move(np));
return;
}
FsPlacements &np = it->second;
np.lastTouchTick = g_maintainTick; // freshness — deduped touches count too
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 &&icons) {
// Queue first (sets want+dirty+touch, dedups an unchanged re-queue), then
// apply synchronously for this fs. Deduped
// re-queues leave the entry not-dirty, so SafeApplyNow no-ops — a
// per-paint steady state costs one compare, same as QueuePlacements.
QueuePlacements(fs, std::move(icons));
SafeApplyNow(fs);
}
void PrepareForReload() {
// The reload teardown frees the icon regions (they die with their parent
// frames); only forget the pointers — never Hide/free them.
g_fsIcons.clear();
g_iconRegions.clear();
g_orphans.clear();
g_maintainDisabled = false; // re-arm the SEH latch for the fresh UI
}
static const Game::ReloadAutoRegister _reloadReg{&PrepareForReload};
} // namespace Text::InlineTexturePool