fix(player): name cache keeps each player's realm and whole UTF-8 names

The persistent name cache cut names at 16 bytes. A Chinese character is
3 bytes in UTF-8, so a 6-character name lost part of its last
character. The limit is now the engine's own: the name cache store
(0x0055F310) copies the name with SStrCopy(dst, src, 0x30) and the
realm with SStrCopy(dst, src, 0x100), now PLAYER_INFO_NAME_SIZE and
PLAYER_INFO_REALM_SIZE in Offsets.h. A longer name from Lua is cut on
a UTF-8 lead byte, never inside a character.

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

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

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

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

Fixes #119
This commit is contained in:
Brues
2026-11-01 12:34:31 -06:00
parent 1ef8c5597a
commit 3ef6c4ffed
12 changed files with 502 additions and 366 deletions
+30 -21
View File
@@ -17835,16 +17835,19 @@ Storage:
- `WTF\Account\<account>\ClassicAPI.txt` — account-level settings
(`PersistentNameCacheEnabled`). The opt-in toggle stays
per-account.
- `WTF\ClassicAPI\<realmList>\<realm>\ClassicAPI_NameCache.txt` —
per-realm cache, **shared across every account on the same
server**. Keyed by the realmlist address (unambiguous server
identity, can't collide across unrelated private servers) plus the
realm name — so alts on different accounts pool into one file
rather than each rebuilding their own. Tab-separated text,
~30 bytes/entry, hand-editable. On first load with no shared file
yet, a pre-existing per-account cache
(`WTF\Account\<account>\<realm>\ClassicAPI_NameCache.txt`) is
migrated in automatically.
- `WTF\ClassicAPI\NameCache-<realm>@<realmList>.txt` — one cache
file for each realm, **shared across every account on the same
server**. The file name has the realm name and the realmlist
address, so two private servers with the same realm name do not
share a file. Alts on different accounts use the same file. Each
line is one player: the GUID, the name, the realm, the class, the
race, and the sex, with tabs between them. The realm is empty for a
player on your realm. You can edit the file by hand. If you used
the cache before, the old file
(`WTF\ClassicAPI\<realmList>\<realm>\ClassicAPI_NameCache.txt`) is
copied into the new file the first time you log in to that realm.
The old file and its empty folders are deleted after the new file
is saved.
### `GetPlayerInfoByGUID(guid)`
@@ -17888,8 +17891,7 @@ explicitly and fire a load-result event.
has been opted into, a per-realm on-disk cache extends coverage
across sessions. If the engine cache does not have the player,
`GetPlayerInfoByGUID` uses the persistent cache. It returns `name`,
`class`, `race`, and `sex` from storage. The persistent cache does
not store the realm, so `realm` is `""`.
`realm`, `class`, `race`, and `sex` from storage.
Returns `nil` only when both the engine and persistent caches miss.
**Implementation**: calls the engine's get-or-fetch primitive at
@@ -17926,8 +17928,8 @@ local name, realm = UnitNameFromGUID("0x0000000000000777")
`realm` is the realm that the server sends with the player's name.
It is `""` when the server sends no realm, and when the name comes
from your friends list or from the persistent cache. It is never
`nil`, so you can test `realm == ""`.
from your friends list. It is never `nil`, so you can test
`realm == ""`.
Doesn't trigger a network query on miss. To populate an unknown
GUID, either let the engine receive a `SMSG_NAME_QUERY_RESPONSE`
@@ -17965,8 +17967,12 @@ The function looks for the name in this order:
Steps 1–4 work when the persistent NameCache is off.
The name must be the full name. Case does not matter (`"gedwyr"`
finds `"Gedwyr"`). The `name` return is the name as the server stores
it, not the text you passed in.
finds `"Gedwyr"`). A name without a realm finds a player on your
realm. For a player from a different realm, pass `"Name-Realm"`, the
form that chat events give for the sender. Spaces in the realm name
do not matter. For a `"Name-Realm"` name, the function uses only
steps 4 and 5. The `name` return is the name as the server stores
it, without the realm, not the text you passed in.
The function only finds players, never NPCs. It does not send a query
to the server.
@@ -17998,8 +18004,11 @@ enabled or the required args are malformed.
- `guid` — `"0xHHHHHHHHLLLLLLLL"` string (same format `UnitGUID`
returns). 8-hex `"0xLLLLLLLL"` is also accepted (hi-dword zero).
- `name` — 1–12 ASCII chars (the character-name range). Tabs,
newlines, and high bytes are stripped.
- `name` — the name of a player on your realm, or `"Name-Realm"` for
a player from a different realm. Names in any language work, for
example Chinese. The cache keeps at most 47 bytes of a name (15
Chinese characters) and never cuts a character in two. Tabs and
line breaks are removed.
- `classToken` — uppercase token like `"WARRIOR"`, `"MAGE"`. Looked
up against `ChrClasses.dbc` filename field, case-insensitive.
Passing an unknown token keeps the entry's prior class (so a
@@ -18036,8 +18045,8 @@ name without erasing class.
The "deleted character recreated with same name, different class"
collision case that name-keyed caches suffer from doesn't apply
here: GUIDs are permanent for the life of a character, so
the new character has a different GUID and gets a different cache
entry.
the new character has a different GUID and replaces the old
character's entry.
### `C_PlayerCache.SetEnabled(enabled)`
@@ -18050,7 +18059,7 @@ client restarts.
When enabled:
- Every `SMSG_NAME_QUERY_RESPONSE` the engine processes is also
written to `WTF\Account\<account>\<realm>\ClassicAPI_NameCache.txt`.
written to `WTF\ClassicAPI\NameCache-<realm>@<realmList>.txt`.
- Lua-side `C_PlayerCache.RememberPlayer` calls become effective
(they're no-ops when the cache is disabled).
- `GetPlayerInfoByGUID` gains the cross-session fallback path
+6
View File
@@ -6092,6 +6092,12 @@ enum Offsets {
OFF_PLAYER_INFO_RACE = 0x138, // u32 (race ID 1..8)
OFF_PLAYER_INFO_SEX = 0x13C, // u32 (0=male, 1=female on wire)
OFF_PLAYER_INFO_CLASS = 0x140, // u32 (class ID 1..11)
// Capacities of the two inline strings, NUL included: the store copies
// them with SStrCopy(dst, src, 0x30) and SStrCopy(dst, src, 0x100)
// (0x0055F3B9, 0x0055F3D4). Names are UTF-8, so a Chinese character
// takes 3 of the 48 bytes.
PLAYER_INFO_NAME_SIZE = 0x30,
PLAYER_INFO_REALM_SIZE = 0x100,
// Visible-object iterator. Walks the engine's linked list of
// currently-in-range CGObjects (the same list the minimap blip
+58
View File
@@ -0,0 +1,58 @@
// 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 "FullName.h"
#include "Game.h"
#include "settings/Paths.h"
#include <cstring>
namespace Player::FullName {
namespace {
// The realm as the engine writes it into a full name: spaces and tabs removed.
std::string Squeeze(const char *realm) {
std::string out;
for (const char *p = realm; p != nullptr && *p != '\0'; ++p)
if (*p != ' ' && *p != '\t')
out.push_back(*p);
return out;
}
} // namespace
std::string Make(const char *name, const char *realm) {
if (name == nullptr || *name == '\0')
return {};
std::string out = name;
const std::string squeezed = Squeeze(realm);
if (squeezed.empty() ||
Game::StrCmpI(squeezed.c_str(), Squeeze(Settings::Paths::RealmName().c_str()).c_str()) == 0)
return out;
out += '-';
out += squeezed;
return out;
}
std::string Parse(const char *text) {
if (text == nullptr)
return {};
const char *dash = std::strchr(text, '-');
if (dash == nullptr)
return Make(text, nullptr);
return Make(std::string(text, dash).c_str(), dash + 1);
}
} // namespace Player::FullName
+39
View File
@@ -0,0 +1,39 @@
// 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 <string>
// A player's name as one string that also says which realm they are from: the
// bare name for a player on the session's realm, "Name-Realm" for one from
// another. It is the form the engine itself shows for a player from another
// realm: the chat handler (0x0049D8B3 on) and the battleground join notice add
// "-" and the realm with its spaces and tabs removed. So a sender name taken
// from a chat event looks the player up as it is. A character name can't hold
// '-', so the first one splits the two.
//
// Compare these with Game::StrCmpI, as the engine compares names: ASCII case
// does not matter.
namespace Player::FullName {
// `realm` as a name cache record holds it (`OFF_PLAYER_INFO_REALM`): "" for a
// player on this realm. A realm that names the session's own counts as "".
// Empty for an empty name.
std::string Make(const char *name, const char *realm);
// "Name" or "Name-Realm" text, from a chat event or typed by the user, in the
// same form as Make. Empty when there is no name before the '-'.
std::string Parse(const char *text);
} // namespace Player::FullName
+57 -27
View File
@@ -34,6 +34,7 @@
// chat won't be in the cache; once they whisper you (or you target
// them, or they appear in guild login spam), they will be.
#include "FullName.h"
#include "Game.h"
#include "Info.h"
#include "NameCache.h"
@@ -76,8 +77,7 @@ bool ParseGUID(const char *str, uint32_t &outHi, uint32_t &outLo) {
// Pushes `(localizedClass, englishClass, localizedRace, englishRace, sex,
// name, realm)` for a player GUID and returns 7, or pushes nothing and
// returns 0 if nothing knows that GUID. Engine name cache first, then the
// persistent NameCache (when enabled) — whose realm is always "", since it
// doesn't store one.
// persistent NameCache (when enabled).
int PushPlayerInfo(void *L, uint64_t guid) {
if (guid == 0)
return 0;
@@ -100,15 +100,14 @@ int PushPlayerInfo(void *L, uint64_t guid) {
classID = *reinterpret_cast<const uint32_t *>(
entry + Offsets::OFF_PLAYER_INFO_CLASS);
} else {
const std::string *cachedName = nullptr;
const NameCache::Entry *cached = NameCache::Lookup(guid, &cachedName);
if (cached == nullptr || cachedName == nullptr || cachedName->empty())
const NameCache::Entry *cached = NameCache::Lookup(guid);
if (cached == nullptr || cached->name.empty())
return 0;
name = cachedName->c_str();
name = cached->name.c_str();
realm = cached->realm.c_str();
classID = cached->classID;
race = cached->raceID;
sex = cached->sex;
realm = "";
}
const char *englishClass = DBC::ClassToken(classID);
@@ -163,10 +162,11 @@ int __fastcall Script_GetPlayerInfoByGUID(void *L) {
// back to the persistent NameCache (when enabled).
//
// `realm` is the server name the name cache record carries — the
// field SMSG_NAME_QUERY_RESPONSE fills for a cross-realm player. It's
// `""` when the record has none or the name came from the friends
// list / persistent cache. Retail documents both returns as non-nil
// strings, so the empty case pushes `""` rather than nil.
// field SMSG_NAME_QUERY_RESPONSE fills for a cross-realm player, which
// the persistent cache keeps too. It's `""` when the record has none
// or the name came from the friends list. Retail documents both
// returns as non-nil strings, so the empty case pushes `""` rather
// than nil.
//
// Returns nothing on:
// - Missing or non-string arg (raises an error rather than return).
@@ -236,7 +236,8 @@ int __fastcall Script_C_PlayerCache_GetPlayerInfoByName(void *L) {
// or not.
// 4. Persistent NameCache (when enabled) — players seen in earlier sessions.
// The realm comes from the engine's name cache record, through the getter's
// own out-param in step 1, as vanilla's UnitName reads it.
// own out-param in step 1, as vanilla's UnitName reads it, or from the
// persistent entry in step 4.
bool NameFromGuid(uint64_t guid, char *buf, size_t bufSize, const char **outRealm) {
if (guid == 0 || buf == nullptr || bufSize == 0)
return false;
@@ -261,15 +262,43 @@ bool NameFromGuid(uint64_t guid, char *buf, size_t bufSize, const char **outReal
}
}
const std::string *cachedName = nullptr;
const NameCache::Entry *cached = NameCache::Lookup(guid, &cachedName);
if (cached != nullptr && cachedName != nullptr && !cachedName->empty())
return CopyName(buf, cachedName->c_str(), bufSize);
const NameCache::Entry *cached = NameCache::Lookup(guid);
if (cached != nullptr && !cached->name.empty()) {
if (outRealm != nullptr)
*outRealm = cached->realm.c_str();
return CopyName(buf, cached->name.c_str(), bufSize);
}
return false;
}
// Resolution order, most live first:
// The GUID of the player the engine's name cache knows by `fullName`
// (`Player::FullName` form), or 0. Walks every loaded record, so it resolves
// anyone the engine has named this session whether or not they're in range.
// Passive — never fires a query. First match wins.
static uint64_t GuidForCachedName(const std::string &fullName) {
struct Search {
const std::string *fullName;
uint64_t guid;
} search{&fullName, 0};
Unit::Identity::ForEachCachedPlayer(
[](uint64_t guid, const uint8_t *rec, void *context) {
auto *s = static_cast<Search *>(context);
const std::string cached =
FullName::Make(Game::Ptr<const char>(rec, Offsets::OFF_PLAYER_INFO_NAME),
Game::Ptr<const char>(rec, Offsets::OFF_PLAYER_INFO_REALM));
if (cached.empty() || Game::StrCmpI(cached.c_str(), s->fullName->c_str()) != 0)
return true;
s->guid = guid;
return false;
},
&search);
return search.guid;
}
// Resolution order, most live first. `name` is "Name", or "Name-Realm" for a
// player from another realm (`Player::FullName`); only the two caches keep a
// player's realm, so such a name skips steps 1 and 2.
// 1. The engine's by-name search (`Unit::Identity::FindGuidByName`,
// players only, whole-name match) — party and raid members, including
// out-of-range ones, then every visible player.
@@ -278,18 +307,19 @@ bool NameFromGuid(uint64_t guid, char *buf, size_t bufSize, const char **outReal
// senders, group, guild, seen units), in range or not.
// 4. Persistent NameCache (when enabled) — players seen in earlier sessions.
uint64_t GuidFromName(const char *name) {
if (name == nullptr || *name == '\0')
const std::string fullName = FullName::Parse(name);
if (fullName.empty())
return 0;
if (const uint64_t guid = Unit::Identity::FindGuidByName(
name, Offsets::TYPEMASK_PLAYER, /*exact*/ true))
if (fullName.find('-') == std::string::npos) {
if (const uint64_t guid = Unit::Identity::FindGuidByName(
fullName.c_str(), Offsets::TYPEMASK_PLAYER, /*exact*/ true))
return guid;
if (const uint64_t guid = FriendList::GuidForName(fullName.c_str()))
return guid;
}
if (const uint64_t guid = GuidForCachedName(fullName))
return guid;
if (const uint64_t guid = FriendList::GuidForName(name))
return guid;
if (const uint64_t guid = Unit::Identity::GuidForCachedName(name))
return guid;
if (const NameCache::Entry *e = NameCache::LookupByName(name))
return e->guid;
return 0;
return NameCache::GuidForName(fullName);
}
static void RegisterLuaFunctions() {
+10 -7
View File
@@ -30,16 +30,19 @@ namespace Player::Info {
// name query of its own.
//
// `outRealm` (optional) receives the player's realm when the engine's name
// cache record carries one, and is left untouched otherwise -- initialize it.
// It points into that record, so read it before the next engine call.
// cache record or the persistent entry carries one, and may be left untouched
// otherwise -- initialize it. It points into that record or entry, so read it
// before the next engine call.
bool NameFromGuid(uint64_t guid, char *buf, size_t bufSize,
const char **outRealm = nullptr);
// Resolve a player's character name to their GUID, or 0. Chain: the engine's
// by-name search (party and raid members, including out-of-range ones, then
// visible players; whole name, case-insensitive) -> friends list -> the
// engine's name cache (anyone named this session) -> persistent NameCache. Players only, never creatures. Passive -- never
// triggers a name query.
// Resolve a player's name to their GUID, or 0. `name` is "Name", or
// "Name-Realm" for a player from another realm (`Player::FullName`; whole
// name, case-insensitive). Chain: the engine's by-name search (party and raid
// members, including out-of-range ones, then visible players) -> friends list
// -> the engine's name cache (anyone named this session) -> persistent
// NameCache; a "Name-Realm" skips the first two, which keep no realm. Players
// only, never creatures. Passive -- never triggers a name query.
uint64_t GuidFromName(const char *name);
} // namespace Player::Info
+257 -231
View File
@@ -23,19 +23,22 @@
// parse callbacks, and the registry handles load/save so neither
// this module nor `Charlist::Order` clobbers the other's lines.
//
// `WTF\ClassicAPI\<realmList>\<realm>\ClassicAPI_NameCache.txt`
// `WTF\ClassicAPI\NameCache-<realm>@<realmList>.txt`
// Per-realm cache contents, SHARED across every account on the
// same server. Keyed by realmlist address (unambiguous server
// identity — can't collide across unrelated private servers) plus
// the realm name, rather than by account, so alts on different
// accounts pool into one file. Not under `Account\`, so we create
// the directory tree ourselves. v4 format. One entry per line:
// `name guid classID raceID sex`
// (fields tab-separated). Loaded once the realm name is
// available post-login (migrating a pre-existing per-account file
// in on first load). 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.
// same server. Named by the realm plus the realmlist address
// (unambiguous server identity — can't collide across unrelated
// private servers), rather than by account, so alts on different
// accounts pool into one file. WoW doesn't make `WTF\ClassicAPI\`,
// so we create it. v5 format. One entry per line, fields
// tab-separated (a realm can hold spaces, and is empty for a player
// on this realm):
// `guid name realm classID raceID sex`
// Loaded once the realm name is available post-login (migrating
// the v4 file in on first load, and deleting it once v5 is saved;
// see `V4CachePath`). Saved when
// (a) a recent write hasn't been flushed AND (b) `kFlushIntervalMs`
// has 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`)
@@ -55,21 +58,22 @@
// queried again. The engine keeps names in memory only, so a
// fresh session starts empty and needs no import.
//
// Lookups are GUID-keyed. Names ARE the dedup signal though: vanilla
// server-side names are unique per realm, so a fresh GUID claiming a
// name we've already seen means the prior character was deleted and
// the name recycled. The old GUID is dead (server won't honor it
// again); keeping it just bloats the file. `EvictStaleGuidsForName`
// drops the old entry on each write so the cache holds one entry per
// name.
// Entries are GUID-keyed, like the engine's own cache. Full names are the
// dedup signal though: names are unique per realm, so a fresh GUID claiming a
// full name we've already seen means the prior character was deleted and the
// name recycled. The old GUID is dead (server won't honor it again); keeping
// it just bloats the file. `Upsert` drops the old entry on each write so the
// cache holds one entry per full name.
#include "NameCache.h"
#include "FullName.h"
#include "Game.h"
#include "Offsets.h"
#include "dbc/Names.h"
#include "guid/Guid.h"
#include "settings/Account.h"
#include "settings/Paths.h"
#include "unit/Identity.h"
#include <cstdint>
@@ -109,12 +113,9 @@ constexpr uint32_t kMaxRaceID = 16;
// Wire sex values are 0/1. Any higher value is corrupt input.
constexpr uint32_t kMaxSex = 1;
// Name-primary storage. Vanilla's per-realm name uniqueness makes
// name the natural identity key; deletion-recreation produces a new
// GUID for the same name, which inserts-replaces here instead of
// piling up dead entries the way a GUID-keyed map would.
//
// Keys compare ignoring ASCII case, the same rule as the engine's own
constexpr const char *kCacheDir = "WTF\\ClassicAPI";
// Full names compare ignoring ASCII case, the same rule as the engine's own
// name compares (SStrCmpI 0x0064A4C0 is a null-checked CRT _strnicmp), so
// `"gedwyr"` finds `"Gedwyr"`. A re-cased name for the same GUID takes the
// rename path in Upsert, so the newest spelling wins.
@@ -131,38 +132,27 @@ struct NameEqual {
return a.size() == b.size() && _strnicmp(a.c_str(), b.c_str(), a.size()) == 0;
}
};
std::unordered_map<std::string, Entry, NameHash, NameEqual> g_entries;
// `guid → name` reverse index. Maintained in lockstep with
// `g_entries`. Invariant: `g_guidIndex[guid] == name` iff
// `g_entries[name].guid == guid`.
std::unordered_map<uint64_t, std::string> g_guidIndex;
std::unordered_map<uint64_t, Entry> g_entries;
// Full name → GUID, maintained in lockstep with `g_entries`. Invariant:
// `g_byName[FullName::Make(e.name, e.realm)] == guid` iff
// `g_entries[guid] == e`.
std::unordered_map<std::string, uint64_t, NameHash, NameEqual> g_byName;
bool g_enabled = false;
bool g_cacheLoaded = false;
// The cache file the store holds, empty until the first load. Saves go here,
// never to the current realm's file: a session can log out and into another
// realm, and LoadCacheIfNeeded swaps the store when it does.
std::string g_loadedPath;
bool g_dirty = false;
DWORD g_lastSaveTick = 0;
// ----- engine globals helpers (mirrors EquipmentSet::Storage) -----
const char *ReadAccountName() {
return *reinterpret_cast<const char *const *>(
static_cast<uintptr_t>(Offsets::VAR_ACCOUNT_NAME_PTR));
}
const char *ReadRealmName() {
auto *info = *reinterpret_cast<uint8_t **>(
static_cast<uintptr_t>(Offsets::VAR_REALM_INFO_PTR));
if (info == nullptr)
return nullptr;
return *reinterpret_cast<const char *const *>(
info + Offsets::OFF_REALM_INFO_NAME);
}
// The v4 file this session migrated from, deleted once the v5 file is saved.
std::string g_migratedV4Path;
// ----- path resolution -----
// realmList CVar value (the realmlist address, e.g.
// "logon.turtle-wow.org") — the unambiguous server identity. Unlike the
// friendly realm name it can't collide across unrelated private servers,
// so it's the outer key for the shared cache path. Mirrors
// so it's part of the shared cache's file name. Mirrors
// `Security::CredStore`'s realm scoping.
const char *ReadRealmList() {
using GetRealmList_t = const char *(__fastcall *)(int forceRefresh);
@@ -170,10 +160,10 @@ const char *ReadRealmList() {
static_cast<uintptr_t>(Offsets::FUN_CVAR_REALM_LIST))(0);
}
// Filesystem-safe path component. We create these directories ourselves
// (WoW doesn't), so any character Windows rejects in a path — or that
// could surprise, like the space/apostrophe in "N'Zoth" — becomes '_'.
// Deterministic, so a realm always maps to the same folder.
// Filesystem-safe file-name part. Any character Windows rejects in a path —
// or that could surprise, like the apostrophe in "N'Zoth" or a realmlist's
// ":port" — becomes '_'. Deterministic, so a realm always maps to the same
// file.
std::string SanitizeComponent(const char *s) {
std::string out;
for (const char *p = s; p != nullptr && *p; ++p) {
@@ -187,58 +177,46 @@ std::string SanitizeComponent(const char *s) {
}
// Shared, server-specific cache path:
// WTF\ClassicAPI\<realmList>\<realmName>\ClassicAPI_NameCache.txt
// WTF\ClassicAPI\NameCache-<realm>@<realmList>.txt
// Not under Account\, so alts on different accounts of the same server
// share one pool. Empty (defer) until both realmlist + realm are known.
// share one pool. SanitizeComponent never writes '@', so the two names
// can't run into each other. Empty (defer) until both realmlist + realm
// are known.
std::string CachePath() {
const char *realmList = ReadRealmList();
if (realmList == nullptr || realmList[0] == '\0')
return {};
const char *realm = ReadRealmName();
if (realm == nullptr || realm[0] == '\0')
const std::string realm = Settings::Paths::RealmName();
if (realm.empty())
return {};
std::string out = "WTF\\ClassicAPI\\";
std::string out = kCacheDir;
out += "\\NameCache-";
out += SanitizeComponent(realm.c_str());
out += '@';
out += SanitizeComponent(realmList);
out += ".txt";
return out;
}
// The v4 file the v5 one replaced, for the one-time migration:
// WTF\ClassicAPI\<realmList>\<realm>\ClassicAPI_NameCache.txt
// Built exactly as v4 wrote it, so it matches the file already on disk.
std::string V4CachePath() {
const char *realmList = ReadRealmList();
if (realmList == nullptr || realmList[0] == '\0')
return {};
const std::string realm = Settings::Paths::RealmName();
if (realm.empty())
return {};
std::string out = kCacheDir;
out += '\\';
out += SanitizeComponent(realmList);
out += '\\';
out += SanitizeComponent(realm);
out += SanitizeComponent(realm.c_str());
out += "\\ClassicAPI_NameCache.txt";
return out;
}
// The pre-shared per-account path, used only to migrate an existing
// cache into the shared location on first load. Built exactly as it was
// written (raw account + realm, unsanitized) so it matches the file
// sitting in WoW's own folders.
std::string OldCachePath() {
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;
}
// Creates every parent directory of `filePath` (mkdir -p). WoW makes
// `WTF\` but not `WTF\ClassicAPI\...`, and ofstream won't create
// directories, so a save into a fresh realm folder would silently fail
// without this. CreateDirectory on an existing dir no-ops.
void EnsureParentDirs(const std::string &filePath) {
for (size_t pos = 0;;) {
const size_t slash = filePath.find('\\', pos);
if (slash == std::string::npos)
break; // remainder is the filename
if (slash > 0)
CreateDirectoryA(filePath.substr(0, slash).c_str(), nullptr);
pos = slash + 1;
}
}
// ----- account settings (registered with Settings::Account) -----
void SettingsReset() {
@@ -262,64 +240,81 @@ const Settings::Account::AutoRegister _accountSettings{
// ----- 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 {};
// A name or realm for a cache line: tabs and line breaks dropped (they would
// break the line), and at most `size - 1` bytes, the engine's own capacity for
// the field (`PLAYER_INFO_NAME_SIZE` / `PLAYER_INFO_REALM_SIZE`), so anything
// the engine stored fits. Names are UTF-8, and a cut never splits a
// character: a 16-byte cap here garbled the last of six Chinese characters
// (issue #119).
std::string SanitizeField(const char *s, size_t size) {
std::string out;
for (const char *p = name; *p && out.size() < 16; ++p) {
for (const char *p = s; p != nullptr && *p != '\0'; ++p) {
const char c = *p;
if (c == '\t' || c == '\r' || c == '\n')
continue;
out.push_back(c);
}
if (out.size() >= size) {
// Back up over continuation bytes (10xxxxxx) to the lead byte of the
// character the cut would split.
size_t cut = size - 1;
while (cut > 0 && (static_cast<unsigned char>(out[cut]) & 0xC0) == 0x80)
--cut;
out.resize(cut);
}
return out;
}
// Inserts or updates an entry keyed by `name`, maintaining the
// `g_guidIndex` reverse-map invariant. Handles three eviction cases:
std::string SanitizeName(const char *name) {
return SanitizeField(name, Offsets::PLAYER_INFO_NAME_SIZE);
}
std::string SanitizeRealm(const char *realm) {
return SanitizeField(realm, Offsets::PLAYER_INFO_REALM_SIZE);
}
// Inserts or updates the entry for `guid`, maintaining the `g_byName`
// invariant. Handles three cases:
//
// 1. A prior entry exists under this name with a different GUID
// (name recycled — character deleted and recreated). Drop the
// old entry and its guid-index entry.
// 2. A prior entry exists under this GUID with a different name
// (character renamed — rare in vanilla but defensible). Drop
// the old name entry and its guid-index entry.
// 3. Same name + same GUID — update in place.
// 1. Another GUID holds this full name (name recycled — character
// deleted and recreated). Drop that entry.
// 2. This GUID holds another full name (character renamed, or a
// re-cased spelling). Move it to the new name.
// 3. Same full name + same GUID — update in place.
//
// `classID` / `raceID` / `sex` of 0 mean "caller doesn't know" and
// don't overwrite an existing non-zero field. Returns true if any
// change occurred (caller marks the cache dirty for flushing).
bool Upsert(uint64_t guid, const std::string &name,
bool Upsert(uint64_t guid, const std::string &name, const std::string &realm,
uint32_t classID, uint32_t raceID, uint32_t sex) {
if (name.empty() || guid == 0)
return false;
const std::string fullName = FullName::Make(name.c_str(), realm.c_str());
bool changed = false;
// Case 1: same name under a different GUID — recycled name.
auto nameIt = g_entries.find(name);
if (nameIt != g_entries.end() && nameIt->second.guid != guid) {
g_guidIndex.erase(nameIt->second.guid);
g_entries.erase(nameIt);
// Case 1: the full name under a different GUID — recycled name.
auto nameIt = g_byName.find(fullName);
if (nameIt != g_byName.end() && nameIt->second != guid) {
g_entries.erase(nameIt->second);
g_byName.erase(nameIt);
changed = true;
}
// Case 2: same GUID under a different name — rename.
auto guidIt = g_guidIndex.find(guid);
if (guidIt != g_guidIndex.end() && guidIt->second != name) {
g_entries.erase(guidIt->second);
g_guidIndex.erase(guidIt);
// Case 2: this GUID under a different full name — rename.
auto it = g_entries.find(guid);
if (it == g_entries.end()) {
it = g_entries.emplace(guid, Entry{name, realm, 0, 0, 0}).first;
changed = true;
} else if (it->second.name != name || it->second.realm != realm) {
g_byName.erase(FullName::Make(it->second.name.c_str(), it->second.realm.c_str()));
it->second.name = name;
it->second.realm = realm;
changed = true;
}
g_byName[fullName] = guid;
// Case 3: insert or update in place.
Entry &e = g_entries[name];
if (e.guid != guid) {
e.guid = guid;
changed = true;
}
// Case 3: update the fields in place.
Entry &e = it->second;
if (classID != 0 && e.classID != classID) {
e.classID = classID;
changed = true;
@@ -334,15 +329,13 @@ bool Upsert(uint64_t guid, const std::string &name,
e.sex = sex;
changed = true;
}
g_guidIndex[guid] = name;
return changed;
}
// Parses v4 cache lines (`name\tguid\tclass\trace\tsex`) from `file`
// into the store. Name first since it's the primary key; GUID is a
// peripheral field carried for GUID-keyed lookups. Variable-width hex
// GUID (no leading zeros). Shared by the normal load and the one-time
// migration from the old per-account file.
// Parses v5 cache lines (`guid\tname\trealm\tclass\trace\tsex`) from `file`
// into the store. Split on tabs, not whitespace: a realm can hold spaces and
// is empty for a player on this realm. Variable-width hex GUID (no leading
// zeros).
void LoadFromStream(std::istream &file) {
std::string line;
while (std::getline(file, line)) {
@@ -352,32 +345,117 @@ void LoadFromStream(std::istream &file) {
continue;
std::istringstream is(line);
std::string name, guidStr, classStr, raceStr, sexStr;
if (!(is >> name >> guidStr >> classStr >> raceStr >> sexStr))
std::string guidStr, name, realm, classStr, raceStr, sexStr;
if (!std::getline(is, guidStr, '\t') || !std::getline(is, name, '\t') ||
!std::getline(is, realm, '\t') || !std::getline(is, classStr, '\t') ||
!std::getline(is, raceStr, '\t') || !std::getline(is, sexStr))
continue;
const std::string sanitized = SanitizeName(name.c_str());
const uint64_t guid = std::strtoull(guidStr.c_str(), nullptr, 16);
const uint32_t classID = static_cast<uint32_t>(std::strtoul(classStr.c_str(), nullptr, 10));
const uint32_t raceID = static_cast<uint32_t>(std::strtoul(raceStr.c_str(), nullptr, 10));
const uint32_t sex = static_cast<uint32_t>(std::strtoul(sexStr.c_str(), nullptr, 10));
if (guid == 0 || sanitized.empty())
continue;
if (classID > kMaxClassID || raceID > kMaxRaceID || sex > kMaxSex)
if (guid == 0 || classID > kMaxClassID || raceID > kMaxRaceID || sex > kMaxSex)
continue;
// Upsert handles the rare same-name / same-guid dedup if the
// file has duplicate rows (shouldn't, but defensive).
Upsert(guid, sanitized, classID, raceID, sex);
Upsert(guid, SanitizeName(name.c_str()), SanitizeRealm(realm.c_str()), classID,
raceID, sex);
}
}
void LoadCacheIfNeeded() {
if (g_cacheLoaded)
// Parses v4 cache lines (`name\tguid\tclass\trace\tsex`) for the one-time
// migration. v4 kept no realm, so every entry is a player on this realm. Names
// hold no whitespace, so the whitespace split v4 itself used is safe here.
void LoadV4FromStream(std::istream &file) {
std::string line;
while (std::getline(file, line)) {
if (line.empty() || line[0] == '#')
continue;
std::istringstream is(line);
std::string name, guidStr, classStr, raceStr, sexStr;
if (!(is >> name >> guidStr >> classStr >> raceStr >> sexStr))
continue;
const uint64_t guid = std::strtoull(guidStr.c_str(), nullptr, 16);
const uint32_t classID = static_cast<uint32_t>(std::strtoul(classStr.c_str(), nullptr, 10));
const uint32_t raceID = static_cast<uint32_t>(std::strtoul(raceStr.c_str(), nullptr, 10));
const uint32_t sex = static_cast<uint32_t>(std::strtoul(sexStr.c_str(), nullptr, 10));
if (guid == 0 || classID > kMaxClassID || raceID > kMaxRaceID || sex > kMaxSex)
continue;
Upsert(guid, SanitizeName(name.c_str()), std::string(), classID, raceID, sex);
}
}
// Deletes the migrated v4 file, then its `<realm>` and `<realmList>` folders.
// RemoveDirectory only removes an empty folder, so a server whose other
// realms have not migrated yet keeps its folder.
void DeleteMigratedV4() {
if (g_migratedV4Path.empty())
return;
DeleteFileA(g_migratedV4Path.c_str());
std::string dir = g_migratedV4Path;
for (int level = 0; level < 2; ++level) {
dir.erase(dir.find_last_of('\\'));
if (!RemoveDirectoryA(dir.c_str()))
break;
}
g_migratedV4Path.clear();
}
void SaveCache() {
if (g_loadedPath.empty())
return;
const std::string &path = g_loadedPath;
// WoW doesn't make `WTF\ClassicAPI\`, and the ofstream open below
// won't either. On an existing directory this is a no-op.
CreateDirectoryA(kCacheDir, nullptr);
const std::string tmp = path + ".tmp";
{
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
if (!out.is_open())
return;
// GUID first since it's the key. Variable-width hex — 1-8 digits
// for player GUIDs (the high dword is always 0), up to 16 if a
// non-player GUID ever lands here.
out << "# ClassicAPI name cache v5 (per-realm, shared across accounts)\n";
out << "# guid\tname\trealm\tclassID\traceID\tsex\n";
for (const auto &kv : g_entries) {
const Entry &e = kv.second;
char buf[48];
std::snprintf(buf, sizeof(buf), "%llX\t",
static_cast<unsigned long long>(kv.first));
out << buf << e.name << '\t' << e.realm;
std::snprintf(buf, sizeof(buf), "\t%u\t%u\t%u\n", e.classID, e.raceID, e.sex);
out << buf;
}
if (!out)
return;
}
std::remove(path.c_str());
if (std::rename(tmp.c_str(), path.c_str()) != 0)
return; // stays dirty, so the next flush tries again
g_dirty = false;
g_lastSaveTick = GetTickCount();
DeleteMigratedV4();
}
// Makes the store hold the current realm's cache: loads it on first use, and
// again whenever the session has moved to another realm. The old realm's
// unsaved entries are saved to its own file first, so one realm's players
// never land in another realm's file.
void LoadCacheIfNeeded() {
const std::string path = CachePath();
if (path.empty())
return; // pre-realm; retry on next call (g_cacheLoaded stays false)
g_cacheLoaded = true;
if (path.empty() || path == g_loadedPath)
return; // pre-realm (retry on next call), or already loaded
if (g_dirty)
SaveCache();
g_entries.clear();
g_byName.clear();
g_dirty = false;
g_migratedV4Path.clear();
g_loadedPath = path;
std::ifstream file(path);
if (file.is_open()) {
@@ -385,62 +463,18 @@ void LoadCacheIfNeeded() {
return;
}
// No shared file yet. One-time migration: seed from the old
// per-account file if it exists, then mark dirty so the next save
// writes the merged data into the shared path. Only when the shared
// file is absent — once it exists it's authoritative (a second
// account's old-only entries just repopulate via scan / SMSG).
const std::string oldPath = OldCachePath();
if (oldPath.empty())
return;
std::ifstream oldFile(oldPath);
if (oldFile.is_open()) {
LoadFromStream(oldFile);
// No v5 file yet. One-time migration: seed from the v4 file if it
// exists, then mark dirty so the next save writes v5. That save
// deletes the v4 file.
const std::string v4Path = V4CachePath();
std::ifstream v4File(v4Path);
if (v4File.is_open()) {
LoadV4FromStream(v4File);
g_dirty = true;
g_migratedV4Path = v4Path;
}
}
void SaveCache() {
const std::string path = CachePath();
if (path.empty())
return;
// `WTF\ClassicAPI\<realmList>\<realm>\` isn't created by WoW — make
// the tree first, else the ofstream open below silently fails.
EnsureParentDirs(path);
const std::string tmp = path + ".tmp";
{
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
if (!out.is_open())
return;
// Single hex GUID column with no leading zeros. Player GUIDs
// (all we cache today) write as 1-8 hex digits since the high
// dword is always 0; non-player GUIDs would naturally extend
// to up to 16 digits if any ever landed here.
// Name-primary v4 format. Name first since it's the primary
// identity (server-enforced unique per realm) and the natural
// sort/scan key when hand-editing. GUID is variable-width
// hex — 1-8 digits for player GUIDs, up to 16 if a non-player
// GUID ever lands here.
out << "# ClassicAPI name cache v4 (per-realm, shared across accounts)\n";
out << "# name\tguid\tclassID\traceID\tsex\n";
for (const auto &kv : g_entries) {
const std::string &name = kv.first;
const Entry &e = kv.second;
char buf[80];
std::snprintf(buf, sizeof(buf), "\t%llX\t%u\t%u\t%u",
static_cast<unsigned long long>(e.guid),
e.classID, e.raceID, e.sex);
out << name << buf << "\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;
@@ -460,6 +494,8 @@ void RememberRecord(uint64_t guid, const uint8_t *record) {
return;
const char *name = reinterpret_cast<const char *>(
record + Offsets::OFF_PLAYER_INFO_NAME);
const char *realm = reinterpret_cast<const char *>(
record + Offsets::OFF_PLAYER_INFO_REALM);
const uint32_t classID = *reinterpret_cast<const uint32_t *>(
record + Offsets::OFF_PLAYER_INFO_CLASS);
const uint32_t raceID = *reinterpret_cast<const uint32_t *>(
@@ -472,13 +508,12 @@ void RememberRecord(uint64_t guid, const uint8_t *record) {
return;
LoadCacheIfNeeded();
const std::string sanitized = SanitizeName(name);
// Out-of-range race/sex mean the record didn't carry them (some
// entry types skip these fields); pass 0 so `Upsert` preserves
// any prior real data.
const uint32_t safeRace = (raceID != 0 && raceID <= kMaxRaceID) ? raceID : 0;
const uint32_t safeSex = (sex <= kMaxSex) ? sex : 0;
if (Upsert(guid, sanitized, classID, safeRace, safeSex)) {
if (Upsert(guid, SanitizeName(name), SanitizeRealm(realm), classID, safeRace, safeSex)) {
g_dirty = true;
MaybeFlush();
}
@@ -529,13 +564,13 @@ bool ParseGUID(const char *str, uint64_t *outGUID) {
}
// `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.
// [, sex]])` — stores the entry in the persistent cache. `name` is the bare
// name of a player on this realm, or "Name-Realm" for one from another, as
// chat events name them. 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. 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::PushBool(L, 0);
@@ -552,8 +587,11 @@ int __fastcall Script_C_PlayerCache_RememberPlayer(void *L) {
Game::Lua::PushBoolean(L, 0);
return 1;
}
const char *name = Game::Lua::ToString(L, 2);
if (name == nullptr || name[0] == '\0') {
const char *text = Game::Lua::ToString(L, 2);
// A character name can't hold '-', so the first one starts the realm.
const char *dash = text != nullptr ? std::strchr(text, '-') : nullptr;
const std::string name = dash != nullptr ? std::string(text, dash) : std::string(text ? text : "");
if (name.empty()) {
Game::Lua::PushBoolean(L, 0);
return 1;
}
@@ -576,7 +614,7 @@ int __fastcall Script_C_PlayerCache_RememberPlayer(void *L) {
// 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);
Remember(guid, name.c_str(), dash != nullptr ? dash + 1 : "", classID, raceID, sex);
Game::Lua::PushBoolean(L, 1);
return 1;
}
@@ -615,34 +653,23 @@ const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace
const Entry *Lookup(uint64_t guid, const std::string **outName) {
if (outName != nullptr)
*outName = nullptr;
const Entry *Lookup(uint64_t guid) {
if (!IsEnabled())
return nullptr;
LoadCacheIfNeeded();
auto guidIt = g_guidIndex.find(guid);
if (guidIt == g_guidIndex.end())
return nullptr;
auto entryIt = g_entries.find(guidIt->second);
if (entryIt == g_entries.end())
return nullptr; // shouldn't happen if invariant holds
if (outName != nullptr)
*outName = &entryIt->first;
return &entryIt->second;
auto it = g_entries.find(guid);
return it != g_entries.end() ? &it->second : nullptr;
}
const Entry *LookupByName(const char *name) {
if (name == nullptr || name[0] == '\0' || !IsEnabled())
return nullptr;
uint64_t GuidForName(const std::string &fullName) {
if (fullName.empty() || !IsEnabled())
return 0;
LoadCacheIfNeeded();
auto it = g_entries.find(name);
if (it == g_entries.end())
return nullptr;
return &it->second;
auto it = g_byName.find(fullName);
return it != g_byName.end() ? it->second : 0;
}
void Remember(uint64_t guid, const char *name, uint32_t classID,
void Remember(uint64_t guid, const char *name, const char *realm, uint32_t classID,
uint32_t raceID, uint32_t sex) {
if (guid == 0 || name == nullptr || name[0] == '\0' || !IsEnabled())
return;
@@ -653,8 +680,7 @@ void Remember(uint64_t guid, const char *name, uint32_t classID,
raceID = 0;
if (sex > kMaxSex)
sex = 0;
const std::string sanitized = SanitizeName(name);
if (Upsert(guid, sanitized, classID, raceID, sex)) {
if (Upsert(guid, SanitizeName(name), SanitizeRealm(realm), classID, raceID, sex)) {
g_dirty = true;
MaybeFlush();
}
@@ -686,8 +712,8 @@ void SetEnabled(bool enabled) {
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 writes to the file the store was loaded from — returns
// silently if nothing is loaded yet (pre-login).
SaveCache();
}
+37 -53
View File
@@ -16,68 +16,53 @@
#include <cstdint>
#include <string>
// Opt-in persistent name cache, keyed by **name**. When enabled,
// every SMSG_NAME_QUERY_RESPONSE the engine processes — plus
// anything fed in via `C_PlayerCache.RememberPlayer` from Lua — is
// persisted to `WTF\Account\<acct>\<realm>\ClassicAPI_NameCache.txt`
// and survives across sessions on the same realm. Shared across all
// characters on that account+realm, so a 50-character bank alt's
// cache is available to the player's main without duplication.
// Opt-in persistent name cache. When enabled, every SMSG_NAME_QUERY_RESPONSE
// the engine processes, plus anything fed in via `C_PlayerCache.RememberPlayer`
// from Lua, is persisted to one file per realm,
// `WTF\ClassicAPI\NameCache-<realm>@<realmList>.txt`, and survives across
// sessions. Every account and character on that realm shares it.
//
// Use case: addons like pfUI's libunitscan currently keep their own
// per-character SVPC name DB to color chat names by class. With
// this enabled, `GetPlayerInfoByGUID` / `GetPlayerInfoByName` falls
// back to the persistent cache on engine miss, so chat coloring
// Just Works after a /reload — and the data isn't duplicated 50
// times.
// Use case: addons like pfUI's libunitscan keep their own per-character SVPC
// name DB to color chat names by class. With this enabled,
// `GetPlayerInfoByGUID` / `GetPlayerInfoByName` fall back to the persistent
// cache on an engine miss, so chat coloring works after a /reload without the
// data being duplicated per character.
//
// Storage model: **name is the primary key**. Vanilla 1.12 enforces
// per-realm name uniqueness server-side, so each name maps to at
// most one live character. GUIDs are unstable — character deletion
// + recreation produces a new GUID for the same name — so keying by
// GUID would mean storing dead identities and needing a name-based
// eviction pass to clean them up. Keying by name makes dedup
// natural (insert-replaces) and eliminates the stale-GUID problem.
// A `guid → name` reverse index gives O(1) lookups in both
// directions. GUIDs are still persisted so addons can recover a
// name from a stored GUID (combat-log replay, etc.).
// Storage model: one entry per GUID, the engine name cache's own key, holding
// the name and the realm the server reported for the player. A name index on
// the full name (`Player::FullName`) answers the reverse lookup. Names are
// unique per realm, so a new GUID under a full name means the character was
// deleted and the name reused: the old entry goes. The file is per realm
// because player GUIDs are a per-realm counter.
namespace Player::NameCache {
struct Entry {
uint64_t guid; // full 64-bit GUID (hi << 32 | lo)
uint32_t classID; // ChrClasses.dbc record ID (1..9), 0 if unknown
uint32_t raceID; // ChrRaces.dbc record ID (1..8), 0 if unknown
uint32_t sex; // 0 = male, 1 = female (wire convention), 0 if unknown
std::string name; // as the server sent it
std::string realm; // the record's server name: "" for a player on this realm
uint32_t classID; // ChrClasses.dbc record ID, 0 if unknown
uint32_t raceID; // ChrRaces.dbc record ID, 0 if unknown
uint32_t sex; // 0 = male, 1 = female (wire convention), 0 if unknown
};
// O(1) lookup by GUID via the reverse index. On hit, returns a
// pointer to the entry and writes the player's name to `*outName`.
// On miss, returns nullptr and sets `*outName` to nullptr. The
// returned pointer and `*outName` are stable until the next
// `Remember` / eviction; treat as transient.
//
// The name out-param is the entry's key in the primary map —
// passing it by pointer keeps it cheap (no string copy) and lets
// the caller read both halves from one lookup.
const Entry *Lookup(uint64_t guid, const std::string **outName);
// The entry for `guid`, or nullptr. The pointer and its strings are stable
// until the next `Remember` or engine name response; treat them as transient.
const Entry *Lookup(uint64_t guid);
// O(1) lookup by whole name, ignoring ASCII case like the engine's own
// name compares, so `"gedwyr"` finds `"Gedwyr"`. Returns nullptr if no
// entry has that name.
// The GUID of the player known by `fullName` (`Player::FullName` form: "Name"
// on this realm, "Name-Realm" from another; ASCII case ignored), or 0.
//
// Used by `C_PlayerCache.GetPlayerInfoByName` for the case where
// an addon has a player's name (e.g., from a `|Hplayer:Name|h`
// chat link or `CHAT_MSG_SYSTEM` string) but no GUID —
// a CHAT_MSG_* event's arg12 is "" whenever the name sits in the
// message text rather than being the sender.
const Entry *LookupByName(const char *name);
// Used by `C_PlayerCache.GetPlayerInfoByName` for the case where an addon has a
// player's name (e.g., from a `|Hplayer:Name|h` chat link or `CHAT_MSG_SYSTEM`
// string) but no GUID — a CHAT_MSG_* event's arg12 is "" whenever the name sits
// in the message text rather than being the sender.
uint64_t GuidForName(const std::string &fullName);
// Adds or updates an entry. Zero values for classID/raceID/sex are
// treated as "caller doesn't know" and don't overwrite existing
// real data — only present (non-zero) fields replace prior values.
// Marks the cache dirty for the next persistence flush.
void Remember(uint64_t guid, const char *name, uint32_t classID,
// Adds or updates an entry. `realm` is "" for a player on this realm. Zero
// values for classID/raceID/sex are treated as "caller doesn't know" and don't
// overwrite existing real data — only present (non-zero) fields replace prior
// values. Marks the cache dirty for the next persistence flush.
void Remember(uint64_t guid, const char *name, const char *realm, uint32_t classID,
uint32_t raceID, uint32_t sex);
// Opt-in toggle. State persists to `WTF\Account\<acct>\ClassicAPI.txt`.
@@ -90,8 +75,7 @@ void SetEnabled(bool enabled);
// Writes any dirty in-memory state to disk. No-op if the cache is
// disabled, isn't dirty, or the file path can't be resolved yet
// (pre-realm). Called from DllMain's reload + detach hooks; safe to
// call any time. Bounded by GetTickCount-based throttling internally,
// so calling repeatedly in tight succession is cheap.
// call any time.
void Flush();
} // namespace Player::NameCache
+5
View File
@@ -52,6 +52,11 @@ std::string AccountName() {
return Usable(account) ? std::string(account) : std::string();
}
std::string RealmName() {
const char *realm = ReadRealmName();
return Usable(realm) ? std::string(realm) : std::string();
}
std::string AccountFile(const char *leaf) {
const char *account = ReadAccountName();
if (!Usable(account))
+3
View File
@@ -34,6 +34,9 @@ namespace Settings::Paths {
// The logged-in account name, upper-cased by the engine. Empty before login.
std::string AccountName();
// The name of the realm the session is on. Empty before one is chosen.
std::string RealmName();
// `WTF\Account\<account>\<leaf>` — for data shared by every character on the
// account. Empty until the account is known.
std::string AccountFile(const char *leaf);
-20
View File
@@ -221,26 +221,6 @@ void ForEachCachedPlayer(CachedPlayerVisitor visit, void *context) {
}
}
uint64_t GuidForCachedName(const char *name) {
if (name == nullptr || *name == '\0')
return 0;
struct Search {
const char *name;
uint64_t guid;
} search{name, 0};
ForEachCachedPlayer(
[](uint64_t guid, const uint8_t *rec, void *context) {
auto *s = static_cast<Search *>(context);
const char *cached = Game::Ptr<const char>(rec, Offsets::OFF_PLAYER_INFO_NAME);
if (*cached == '\0' || Game::StrCmpI(cached, s->name) != 0)
return true;
s->guid = guid;
return false;
},
&search);
return search.guid;
}
// `UnitGUID(unit)` — returns the unit's 64-bit GUID formatted as a
// hex string `"0xHHHHHHHHLLLLLLLL"` (16 hex digits, hi dword first).
//
-7
View File
@@ -141,13 +141,6 @@ const char *NameForGuid(uint64_t guid);
// passive peek: a player whose name isn't cached yet gets a name query.
const char *NameForUnit(const void *unit, const char **outRealm = nullptr);
// The GUID of the player the NameCache knows as `name` (whole name, case-
// insensitive — the engine's own ignore-by-name compare), or 0. Walks every
// loaded record, so it resolves anyone the engine has named this session
// (chat senders, group, guild, seen units) whether or not they're in range.
// Passive — never fires a query. First match wins.
uint64_t GuidForCachedName(const char *name);
// Calls `visit(guid, record, context)` for every loaded NameCache record
// (`record` as PlayerInfoRecord returns it; nodes whose query is still pending
// are skipped). Stops early when `visit` returns false. Passive — never fires