// This file is part of ClassicAPI.
//
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
// of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with
// ClassicAPI. If not, see .
// Persistent name cache — see NameCache.h for the motivating use case.
//
// Two persistence files:
//
// `WTF\Account\\ClassicAPI.txt`
// Account-level settings. Single `PersistentNameCacheEnabled=1`
// line for now; other ClassicAPI features may layer here later.
// Loaded on first need (when the account-name global is
// populated by the engine's login flow). Hand-edits survive.
//
// `WTF\Account\\\ClassicAPI_NameCache.txt`
// Per-realm cache contents. v2 format. One entry per line:
// `guidHi guidLo classID raceID sex name`
// (fields tab-separated). Loaded once the realm name is
// available post-login. Saved when (a) a recent write hasn't
// been flushed AND (b) at least 30 seconds have elapsed since
// the prior save, OR (c) DLL teardown / `Flush()` is called.
//
// Population sources:
// 1. The engine's NameCache writer (`FUN_PLAYER_INFO_CACHE_WRITE`)
// — every SMSG_NAME_QUERY_RESPONSE the engine processes flows
// through here. Covers chat, group/raid sync, guild roster
// updates, visible-object resolution.
// 2. `C_PlayerCache.RememberPlayer(guid, name, classToken)` from
// Lua — lets addons feed in sources the engine cache doesn't
// touch directly (e.g. /who results parsed via GetWhoInfo,
// mouseover, target).
// 3. **Visible-object sweep** (opt-in via `C_PlayerCache.SetScanEnabled`):
// walks the engine's live visible-object list every ~10s on
// the existing `Frame::RegisterEvent` hook. Picks up every
// player in render range whether or not the engine has issued
// a SMSG_NAME_QUERY for them. Same primitive
// VanillaMinimapTracking uses for its blip rendering, so we
// know the path is safe and cheap.
//
// Lookups are GUID-keyed, so the "deleted character recreated with
// same name, different class" failure mode of name-keyed caches
// (libunitscan, etc.) doesn't apply — different GUIDs are different
// entries, period.
#include "NameCache.h"
#include "Game.h"
#include "Offsets.h"
#include "guid/Guid.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
namespace Player::NameCache {
namespace {
// Backstop flush interval — explicit `Flush()` calls from DllMain's
// `FrameScript_Initialize` hook (covers /reload and /logout) and
// `DLL_PROCESS_DETACH` (clean /quit) are the primary save path. The
// in-`Remember` `MaybeFlush` runs only as a defensive measure for
// long sessions that never reload AND end via hard process kill
// (task manager, OS crash) — in that case we bound data loss to
// roughly this interval. 5 minutes was chosen as a compromise:
// long enough that routine play has zero in-flight I/O, short
// enough that a rare bad-shutdown loses at most ~5 min of new
// entries.
constexpr DWORD kFlushIntervalMs = 5 * 60 * 1000;
// ChrClasses.dbc max ID. Anything above this is a corrupt input.
constexpr uint32_t kMaxClassID = 16;
// ChrRaces.dbc max ID. Vanilla has 8 (Human..Troll); allow some
// headroom for private-server custom races.
constexpr uint32_t kMaxRaceID = 16;
// Wire sex values are 0/1. Any higher value is corrupt input.
constexpr uint32_t kMaxSex = 1;
// Visible-object scan throttle. 10s is short enough that walking
// through a city populates entries quickly, long enough that idle
// players in a static zone do basically nothing.
constexpr DWORD kScanIntervalMs = 10 * 1000;
std::unordered_map g_entries;
bool g_enabled = false;
bool g_scanEnabled = false;
bool g_settingsLoaded = false;
bool g_cacheLoaded = false;
bool g_dirty = false;
DWORD g_lastSaveTick = 0;
DWORD g_lastScanTick = 0;
// ----- engine globals helpers (mirrors EquipmentSet::Storage) -----
const char *ReadAccountName() {
return *reinterpret_cast(
static_cast(Offsets::VAR_ACCOUNT_NAME_PTR));
}
const char *ReadRealmName() {
auto *info = *reinterpret_cast(
static_cast(Offsets::VAR_REALM_INFO_PTR));
if (info == nullptr)
return nullptr;
return *reinterpret_cast(
info + Offsets::OFF_REALM_INFO_NAME);
}
// ----- path resolution -----
std::string SettingsPath() {
const char *account = ReadAccountName();
if (account == nullptr || account[0] == '\0')
return {};
std::string out = "WTF\\Account\\";
out += account;
out += "\\ClassicAPI.txt";
return out;
}
std::string CachePath() {
const char *account = ReadAccountName();
if (account == nullptr || account[0] == '\0')
return {};
const char *realm = ReadRealmName();
if (realm == nullptr || realm[0] == '\0')
return {};
std::string out = "WTF\\Account\\";
out += account;
out += '\\';
out += realm;
out += "\\ClassicAPI_NameCache.txt";
return out;
}
// ----- settings load/save -----
void LoadSettingsIfNeeded() {
if (g_settingsLoaded)
return;
const std::string path = SettingsPath();
if (path.empty())
return; // pre-login; retry on next call (g_settingsLoaded stays false)
g_settingsLoaded = true; // path resolved — even an empty file is "loaded"
std::ifstream file(path);
if (!file.is_open())
return; // no settings file = all defaults (disabled)
std::string line;
while (std::getline(file, line)) {
while (!line.empty() && (line.back() == '\r' || line.back() == '\n'
|| line.back() == ' ' || line.back() == '\t'))
line.pop_back();
if (line.empty() || line[0] == '#')
continue;
auto eq = line.find('=');
if (eq == std::string::npos)
continue;
const std::string key = line.substr(0, eq);
const std::string value = line.substr(eq + 1);
if (key == "PersistentNameCacheEnabled")
g_enabled = (value == "1" || value == "true");
else if (key == "NameCacheScanEnabled")
g_scanEnabled = (value == "1" || value == "true");
}
}
void SaveSettings() {
const std::string path = SettingsPath();
if (path.empty())
return;
const std::string tmp = path + ".tmp";
{
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
if (!out.is_open())
return;
out << "# ClassicAPI account-level settings\n";
out << "PersistentNameCacheEnabled=" << (g_enabled ? 1 : 0) << "\n";
out << "NameCacheScanEnabled=" << (g_scanEnabled ? 1 : 0) << "\n";
if (!out)
return;
}
std::remove(path.c_str());
std::rename(tmp.c_str(), path.c_str());
}
// ----- cache load/save -----
// Lightweight name sanitizer — vanilla player names are 2..12 ASCII
// letters, but for paranoia drop anything that would break a line
// (tab, newline) and cap length. Anything else passes through.
std::string SanitizeName(const char *name) {
if (name == nullptr)
return {};
std::string out;
for (const char *p = name; *p && out.size() < 16; ++p) {
const char c = *p;
if (c == '\t' || c == '\r' || c == '\n')
continue;
out.push_back(c);
}
return out;
}
void LoadCacheIfNeeded() {
if (g_cacheLoaded)
return;
const std::string path = CachePath();
if (path.empty())
return; // pre-realm; retry on next call (g_cacheLoaded stays false)
g_cacheLoaded = true;
std::ifstream file(path);
if (!file.is_open())
return; // first run for this realm
std::string line;
while (std::getline(file, line)) {
while (!line.empty() && (line.back() == '\r' || line.back() == '\n'))
line.pop_back();
if (line.empty() || line[0] == '#')
continue;
// tab-separated: hi lo classID raceID sex name
std::istringstream is(line);
std::string hiStr, loStr, classStr, raceStr, sexStr, name;
if (!(is >> hiStr >> loStr >> classStr >> raceStr >> sexStr))
continue;
// Consume the single tab/space, then read remaining name
// as-is (no spaces in vanilla names but tolerate them).
while (is.peek() == ' ' || is.peek() == '\t')
is.get();
std::getline(is, name);
if (name.empty())
continue;
const uint32_t hi = static_cast(std::strtoul(hiStr.c_str(), nullptr, 16));
const uint32_t lo = static_cast(std::strtoul(loStr.c_str(), nullptr, 16));
const uint32_t classID = static_cast(std::strtoul(classStr.c_str(), nullptr, 10));
const uint32_t raceID = static_cast(std::strtoul(raceStr.c_str(), nullptr, 10));
const uint32_t sex = static_cast(std::strtoul(sexStr.c_str(), nullptr, 10));
if (lo == 0 && hi == 0)
continue;
if (classID > kMaxClassID || raceID > kMaxRaceID || sex > kMaxSex)
continue;
const uint64_t guid = (static_cast(hi) << 32) | lo;
Entry e;
e.guid = guid;
e.name = SanitizeName(name.c_str());
e.classID = classID;
e.raceID = raceID;
e.sex = sex;
if (!e.name.empty())
g_entries[guid] = std::move(e);
}
}
void SaveCache() {
const std::string path = CachePath();
if (path.empty())
return;
const std::string tmp = path + ".tmp";
{
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
if (!out.is_open())
return;
out << "# ClassicAPI name cache v2 (per-realm)\n";
out << "# guidHi\tguidLo\tclassID\traceID\tsex\tname\n";
for (const auto &kv : g_entries) {
const Entry &e = kv.second;
char buf[80];
std::snprintf(buf, sizeof(buf), "%08X\t%08X\t%u\t%u\t%u\t",
static_cast(e.guid >> 32),
static_cast(e.guid),
e.classID, e.raceID, e.sex);
out << buf << e.name << "\n";
}
if (!out)
return;
}
std::remove(path.c_str());
std::rename(tmp.c_str(), path.c_str());
g_dirty = false;
g_lastSaveTick = GetTickCount();
}
void MaybeFlush() {
if (!g_dirty)
return;
const DWORD now = GetTickCount();
if ((now - g_lastSaveTick) < kFlushIntervalMs)
return;
SaveCache();
}
// ----- engine NameCache hook -----
// `__thiscall(this = cache, packet, guidLo, guidHi)`. We forward to
// the original first (so the engine settles its entry and dispatches
// callbacks), then read the same fields back out of the packet and
// mirror them into our store.
using CacheWrite_t = void(__thiscall *)(void *self, const uint8_t *packet,
uint32_t guidLo, uint32_t guidHi);
CacheWrite_t CacheWrite_o = nullptr;
void __fastcall CacheWrite_h(void *self, void *edx, const uint8_t *packet,
uint32_t guidLo, uint32_t guidHi) {
// __fastcall stub forwards to __thiscall — MSVC's free-function
// __fastcall lays out (ECX=self, EDX=unused, stack=packet, lo, hi),
// matching the engine's __thiscall(self, packet, lo, hi).
CacheWrite_o(self, packet, guidLo, guidHi);
(void)edx;
if (!g_enabled)
return;
if (packet == nullptr)
return;
if (guidLo == 0 && guidHi == 0)
return;
LoadCacheIfNeeded();
const char *name = reinterpret_cast(
packet + Offsets::OFF_PLAYER_INFO_NAME);
const uint32_t classID = *reinterpret_cast(
packet + Offsets::OFF_PLAYER_INFO_CLASS);
const uint32_t raceID = *reinterpret_cast(
packet + Offsets::OFF_PLAYER_INFO_RACE);
const uint32_t sex = *reinterpret_cast(
packet + Offsets::OFF_PLAYER_INFO_SEX);
if (name[0] == '\0')
return;
if (classID == 0 || classID > kMaxClassID)
return;
const uint64_t guid = (static_cast(guidHi) << 32) | guidLo;
Entry &e = g_entries[guid];
const std::string sanitized = SanitizeName(name);
bool changed = false;
if (e.guid != guid) {
e.guid = guid;
changed = true;
}
if (e.name != sanitized) {
e.name = sanitized;
changed = true;
}
if (e.classID != classID) {
e.classID = classID;
changed = true;
}
// Race/sex sanity-check against the same maxes Load enforces.
// Out-of-range values mean the packet didn't carry them (some
// entry types skip these fields); preserve any prior real data.
if (raceID != 0 && raceID <= kMaxRaceID && e.raceID != raceID) {
e.raceID = raceID;
changed = true;
}
if (sex <= kMaxSex && e.sex != sex) {
e.sex = sex;
changed = true;
}
if (changed) {
g_dirty = true;
MaybeFlush();
}
}
static const Game::HookAutoRegister _hookreg{
Offsets::FUN_PLAYER_INFO_CACHE_WRITE,
reinterpret_cast(&CacheWrite_h),
reinterpret_cast(&CacheWrite_o)};
// ----- visible-object scan -----
// Engine iterator over the live visible-object list. Internally walks
// the linked list at [playerObj + 0xAC] and calls our callback once
// per object with (ECX = context, [stack] = uint64_t guid).
// Returning 0 from the callback stops iteration; 1 continues.
using EnumVisibleObjects_t = bool(__fastcall *)(void *callback, void *context);
using EnumVisibleObjectsCallback_t = int(__fastcall *)(void *context, void *edx,
uint64_t guid);
// GUID → CGObject pointer resolver with type-mask filter. Returns
// NULL if the GUID isn't loaded or its object type doesn't match the
// mask. We pass TYPEMASK_PLAYER for our player-only sweep.
using ObjectPtr_t = void *(__fastcall *)(uint32_t typeMask, void *unused,
uint64_t guid, int unused2);
// CGObject vftable's GetName slot. Slot 22 = byte offset 22 * 4 = 0x58.
// VanillaMinimapTracking calls obj->vftable->GetName(obj) the same way
// in its NameLookupCallback; verified working against the 1.12 binary.
constexpr size_t kVftableGetNameSlot = 22;
// Reads `obj->vftable[slot]` as a __thiscall function pointer and
// invokes it on `obj`. Lets us call GetName without committing to a
// full vftable struct definition.
const char *CallGetName(void *obj) {
using GetName_t = const char *(__thiscall *)(void *self);
auto *vftable = *reinterpret_cast(obj);
auto getName = reinterpret_cast(vftable[kVftableGetNameSlot]);
return getName(obj);
}
// Reads race/class/sex bytes off a CGUnit_C's m_objectFields
// descriptor (`UNIT_FIELD_BYTES_0` packs them at +0x78..+0x7A).
// Field path matches Script_UnitClass's general-token branch.
// Returns all zeros if the descriptor pointer is null.
struct UnitBytes0 {
uint32_t raceID;
uint32_t classID;
uint32_t sex;
};
UnitBytes0 ReadBytes0(void *unit) {
UnitBytes0 out{0, 0, 0};
auto *descriptor = *reinterpret_cast(
reinterpret_cast(unit)
+ Offsets::OFF_CGUNIT_OBJECT_FIELDS);
if (descriptor == nullptr)
return out;
out.raceID = descriptor[Offsets::OFF_UNIT_DESCRIPTOR_RACE_BYTE];
out.classID = descriptor[Offsets::OFF_UNIT_DESCRIPTOR_CLASS_BYTE];
out.sex = descriptor[Offsets::OFF_UNIT_DESCRIPTOR_SEX_BYTE];
return out;
}
// Reads the local player's GUID from the engine's CGPlayer_C global
// at [0x00B41414 + 0xC0]. Used to skip "scan yourself" — the local
// player's CGObject is the head of the visible-object list, and its
// vftable's GetName slot empirically returns a sentinel pointer (0x1)
// rather than a real string in 1.12.1. Either slot 22 isn't GetName
// on the local CGPlayer_C type, or it is but returns 0x1 to mean
// "no remote name; ask the local source." Either way we don't need
// to cache ourselves — we have the data via every other path.
uint64_t LocalPlayerGUID() {
auto *player = *reinterpret_cast(
static_cast(Offsets::VAR_LOCAL_PLAYER_PTR));
if (player == nullptr)
return 0;
return *reinterpret_cast(
player + Offsets::OFF_LOCAL_PLAYER_GUID);
}
// Pointer sanity check before dereferencing. The CGObject vftable
// GetName slot has at least one known case where it returns 0x1
// instead of a real `const char *` (see LocalPlayerGUID note). Any
// "pointer" below 0x10000 is invalid for a 32-bit user-space
// address, so a cheap lower-bound check catches the sentinel case
// without needing per-object-type vftable awareness.
bool LooksLikeStringPointer(const void *p) {
return reinterpret_cast(p) >= 0x10000;
}
// Callback invoked once per visible object during a scan. Filters to
// players (NPCs and pets have ephemeral, reusable GUIDs — caching
// them is worse than useless) and feeds name + class into Remember().
int __fastcall ScanCallback(void * /*context*/, void * /*edx*/, uint64_t guid) {
if (guid == 0)
return 1;
// Skip ourselves — see LocalPlayerGUID comment for the crash
// we hit when calling GetName on the local CGPlayer's vftable.
if (guid == LocalPlayerGUID())
return 1;
auto resolver = reinterpret_cast(
static_cast(Offsets::FUN_CLNT_OBJ_MGR_OBJECT_PTR));
void *obj = resolver(Offsets::TYPEMASK_PLAYER, nullptr, guid, 0);
if (obj == nullptr)
return 1; // not a player (or not currently loaded)
const char *name = CallGetName(obj);
if (!LooksLikeStringPointer(name) || name[0] == '\0')
return 1;
const UnitBytes0 bytes0 = ReadBytes0(obj);
if (bytes0.classID == 0 || bytes0.classID > kMaxClassID)
return 1;
Remember(guid, name, bytes0.classID, bytes0.raceID, bytes0.sex);
return 1; // keep walking
}
void ScanVisibleObjects() {
auto enumerate = reinterpret_cast(
static_cast(Offsets::FUN_CLNT_OBJ_MGR_ENUM_VISIBLE_OBJECTS));
enumerate(reinterpret_cast(&ScanCallback), nullptr);
}
void MaybeScan() {
if (!g_enabled || !g_scanEnabled)
return;
const DWORD now = GetTickCount();
if ((now - g_lastScanTick) < kScanIntervalMs && g_lastScanTick != 0)
return;
g_lastScanTick = now;
LoadCacheIfNeeded();
ScanVisibleObjects();
}
// ----- Lua surface -----
// Thin shim around the centralized `Guid::Parse` so this TU's Lua
// surface keeps a local symbol with its existing call shape.
bool ParseGUID(const char *str, uint64_t *outGUID) {
return Guid::Parse(str, outGUID);
}
// Returns the ChrClasses.dbc record ID for a class token like
// `"WARRIOR"`, `"MAGE"`, etc. Case-insensitive. 0 if not matched.
// 1.12 has 9 player classes; we walk the DBC each call (cheap — 9
// records, each filename a few bytes) rather than building a static
// table that risks getting out-of-sync.
uint32_t ResolveClassToken(const char *token) {
if (token == nullptr || *token == '\0')
return 0;
const int count = *reinterpret_cast(
static_cast(Offsets::VAR_CHRCLASSES_COUNT));
const uint8_t *const *records = *reinterpret_cast(
static_cast(Offsets::VAR_CHRCLASSES_RECORDS));
if (records == nullptr)
return 0;
for (int i = 1; i <= count; ++i) {
const uint8_t *rec = records[i];
if (rec == nullptr)
continue;
const char *filename = *reinterpret_cast(
rec + Offsets::OFF_CHRCLASSES_FILENAME);
if (filename == nullptr)
continue;
// Case-insensitive compare; vanilla tokens are uppercase
// ("WARRIOR", "MAGE", ...) and modern Classic uses the same.
const char *a = filename;
const char *b = token;
bool match = true;
while (*a && *b) {
char ca = *a, cb = *b;
if (ca >= 'a' && ca <= 'z') ca -= 32;
if (cb >= 'a' && cb <= 'z') cb -= 32;
if (ca != cb) { match = false; break; }
++a; ++b;
}
if (match && *a == '\0' && *b == '\0')
return static_cast(i);
}
return 0;
}
// Same shape as ResolveClassToken but walks ChrRaces.dbc.
uint32_t ResolveRaceToken(const char *token) {
if (token == nullptr || *token == '\0')
return 0;
const int count = *reinterpret_cast(
static_cast(Offsets::VAR_CHRRACES_COUNT));
const uint8_t *const *records = *reinterpret_cast(
static_cast(Offsets::VAR_CHRRACES_RECORDS));
if (records == nullptr)
return 0;
for (int i = 1; i <= count; ++i) {
const uint8_t *rec = records[i];
if (rec == nullptr)
continue;
const char *filename = *reinterpret_cast(
rec + Offsets::OFF_CHRRACES_FILENAME);
if (filename == nullptr)
continue;
const char *a = filename;
const char *b = token;
bool match = true;
while (*a && *b) {
char ca = *a, cb = *b;
if (ca >= 'a' && ca <= 'z') ca -= 32;
if (cb >= 'a' && cb <= 'z') cb -= 32;
if (ca != cb) { match = false; break; }
++a; ++b;
}
if (match && *a == '\0' && *b == '\0')
return static_cast(i);
}
return 0;
}
// `C_PlayerCache.RememberPlayer(guid, name, classToken [, raceToken
// [, sex]])` — stores the entry in the persistent cache. Class and
// race tokens are uppercase engine tokens (`"WARRIOR"`, `"NIGHTELF"`,
// etc.); sex is `0` (male) or `1` (female), matching the wire-format
// convention the engine cache stores. Trailing args are optional —
// passing only the first three preserves the old 3-arg signature.
// Returns `true` on success, `false` if the cache is disabled or the
// required args are malformed.
int __fastcall Script_C_PlayerCache_RememberPlayer(void *L) {
if (!IsEnabled()) {
Game::Lua::PushBoolean(L, 0);
return 1;
}
if (!Game::Lua::IsString(L, 1) || !Game::Lua::IsString(L, 2)
|| !Game::Lua::IsString(L, 3)) {
Game::Lua::Error(L,
"Usage: C_PlayerCache.RememberPlayer(guid, name, classToken [, raceToken [, sex]])");
return 0;
}
uint64_t guid;
if (!ParseGUID(Game::Lua::ToString(L, 1), &guid) || guid == 0) {
Game::Lua::PushBoolean(L, 0);
return 1;
}
const char *name = Game::Lua::ToString(L, 2);
if (name == nullptr || name[0] == '\0') {
Game::Lua::PushBoolean(L, 0);
return 1;
}
const char *classToken = Game::Lua::ToString(L, 3);
const uint32_t classID = ResolveClassToken(classToken);
// Optional race + sex. Missing / non-string / unknown values
// resolve to 0, which Remember() treats as "leave existing value
// alone" — so a 3-arg call preserves any prior race/sex data.
uint32_t raceID = 0;
if (Game::Lua::IsString(L, 4))
raceID = ResolveRaceToken(Game::Lua::ToString(L, 4));
uint32_t sex = 0;
if (Game::Lua::IsNumber(L, 5)) {
const double raw = Game::Lua::ToNumber(L, 5);
if (raw >= 0 && raw <= static_cast(kMaxSex))
sex = static_cast(raw);
}
// Remember treats sex==0 as "leave alone" since male and "unknown"
// share the same wire value. To flip a wrongly-cached female back
// to male, the SMSG hook path (which does direct assignment) is
// the route — RememberPlayer is for additive updates from addon
// sources that may or may not know sex.
Remember(guid, name, classID, raceID, sex);
Game::Lua::PushBoolean(L, 1);
return 1;
}
// `C_PlayerCache.SetEnabled(bool)` — opt-in toggle for the persistent
// name cache. Persists to the account-level settings file. Enabling
// triggers a lazy load of any prior cache contents for the current
// realm.
int __fastcall Script_C_PlayerCache_SetEnabled(void *L) {
LoadSettingsIfNeeded();
bool desired = false;
if (Game::Lua::IsNumber(L, 1))
desired = Game::Lua::ToNumber(L, 1) != 0;
else
desired = Game::Lua::ToBoolean(L, 1) != 0;
if (g_enabled != desired) {
g_enabled = desired;
SaveSettings();
if (g_enabled) {
LoadCacheIfNeeded();
} else {
// Flush any pending writes before going quiet.
if (g_dirty)
SaveCache();
}
}
return 0;
}
int __fastcall Script_C_PlayerCache_IsEnabled(void *L) {
LoadSettingsIfNeeded();
Game::Lua::PushBoolean(L, g_enabled ? 1 : 0);
return 1;
}
// `C_PlayerCache.SetScanEnabled(bool)` — opt-in toggle for the
// visible-object sweep. Independent of the cache toggle: turning
// this on without `C_PlayerCache.SetEnabled(true)` does nothing
// (scan results would have nowhere to go). Persists to the same
// account-level settings file.
int __fastcall Script_C_PlayerCache_SetScanEnabled(void *L) {
LoadSettingsIfNeeded();
bool desired = false;
if (Game::Lua::IsNumber(L, 1))
desired = Game::Lua::ToNumber(L, 1) != 0;
else
desired = Game::Lua::ToBoolean(L, 1) != 0;
if (g_scanEnabled != desired) {
g_scanEnabled = desired;
SaveSettings();
}
return 0;
}
int __fastcall Script_C_PlayerCache_IsScanEnabled(void *L) {
LoadSettingsIfNeeded();
Game::Lua::PushBoolean(L, g_scanEnabled ? 1 : 0);
return 1;
}
void RegisterLuaFunctions() {
Game::Lua::RegisterTableFunction("C_PlayerCache", "RememberPlayer",
&Script_C_PlayerCache_RememberPlayer);
Game::Lua::RegisterTableFunction("C_PlayerCache", "SetEnabled",
&Script_C_PlayerCache_SetEnabled);
Game::Lua::RegisterTableFunction("C_PlayerCache", "IsEnabled",
&Script_C_PlayerCache_IsEnabled);
Game::Lua::RegisterTableFunction("C_PlayerCache", "SetScanEnabled",
&Script_C_PlayerCache_SetScanEnabled);
Game::Lua::RegisterTableFunction("C_PlayerCache", "IsScanEnabled",
&Script_C_PlayerCache_IsScanEnabled);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace
const Entry *Lookup(uint64_t guid) {
if (!g_enabled)
return nullptr;
LoadCacheIfNeeded();
auto it = g_entries.find(guid);
if (it == g_entries.end())
return nullptr;
return &it->second;
}
void Remember(uint64_t guid, const char *name, uint32_t classID,
uint32_t raceID, uint32_t sex) {
if (!g_enabled || guid == 0 || name == nullptr || name[0] == '\0')
return;
LoadCacheIfNeeded();
if (classID > kMaxClassID)
classID = 0;
if (raceID > kMaxRaceID)
raceID = 0;
if (sex > kMaxSex)
sex = 0;
Entry &e = g_entries[guid];
const std::string sanitized = SanitizeName(name);
bool changed = false;
if (e.guid != guid) {
e.guid = guid;
changed = true;
}
if (e.name != sanitized) {
e.name = sanitized;
changed = true;
}
// 0 means "caller doesn't know"; don't overwrite real data with
// unknown. Only update on real → real change.
if (classID != 0 && e.classID != classID) {
e.classID = classID;
changed = true;
}
if (raceID != 0 && e.raceID != raceID) {
e.raceID = raceID;
changed = true;
}
// sex == 0 is ambiguous (male AND "unknown"); we only treat
// non-zero (1 = female) as authoritative. Means we can't flip
// a wrongly-cached female back to male via Remember — but the
// SMSG hook path uses direct assignment so it self-corrects.
if (sex != 0 && e.sex != sex) {
e.sex = sex;
changed = true;
}
if (changed) {
g_dirty = true;
MaybeFlush();
}
}
bool IsEnabled() {
LoadSettingsIfNeeded();
return g_enabled;
}
void SetEnabled(bool enabled) {
LoadSettingsIfNeeded();
if (g_enabled == enabled)
return;
g_enabled = enabled;
SaveSettings();
if (g_enabled)
LoadCacheIfNeeded();
else if (g_dirty)
SaveCache();
}
void Flush() {
if (!g_enabled || !g_dirty)
return;
// SaveCache resolves the path itself — returns silently if realm
// name isn't available yet (pre-login).
SaveCache();
}
void Tick() {
MaybeScan();
}
} // namespace Player::NameCache