Repository navigation
Expand file tree
/
Copy pathIdentity.cpp
More file actions
500 lines (446 loc) · 20.7 KB
/
Copy pathIdentity.cpp
File metadata and controls
500 lines (446 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// 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 "cache/Record.h"
#include "group/Roster.h"
#include "storm/List.h"
#include "unit/Identity.h"
#include "Game.h"
#include "Offsets.h"
#include "glue/EnterWorld.h"
#include "guid/Guid.h"
#include "nameplate/Walk.h"
#include "object/Resolve.h"
#include "unit/TokenEvents.h"
#include <cstdint>
#include <cstdio>
#include <cstring>
namespace Unit::Identity {
using TokenToGUID_t = uint64_t(__fastcall *)(const char *token);
// `FUN_UNIT_FIND_BY_NAME` — see Offsets.h. The distance bound is passed as
// the float bit pattern the engine's own callers use (FLT_MAX = no limit).
using FindUnitByName_t = uint64_t(__fastcall *)(const char *name, uint32_t typeMask,
int mode, int exactMatch,
uint32_t maxDistance);
static constexpr uint32_t kMaxDistanceFltMax = 0x7F7FFFFF;
// The selected character's GUID, captured at the glue "Enter World" click
// (the Glue::EnterWorld subscriber below) — i.e. before the engine has
// created the in-world player object whose +0xC0 holds the live GUID.
// `PlayerGuid()` serves this as a fallback during the early-login window so
// `UnitGUID("player")` answers from addon-load time instead of returning nil
// until SMSG_UPDATE_OBJECT lands (≈PLAYER_LOGIN). 0 = not captured yet.
// Overwritten on every enter, so a character switch can't serve a stale GUID;
// only ever read when the live engine value is still 0, and identical to it
// once that's populated.
static uint64_t g_charSelectGuid = 0;
static void OnEnterWorld(const uint8_t *character) {
g_charSelectGuid = Game::Read<uint64_t>(character, Offsets::OFF_GLUE_CHAR_GUID);
}
static const Glue::EnterWorld::AutoSubscribe _enterWorld{&OnEnterWorld};
// FUN_TOKEN_TO_GUID's `"player"` path resolves the GUID by looking the
// local player up in the engine's object manager: it calls FUN_00468550
// to read `[VAR_LOCAL_PLAYER_PTR + 0xC0]`, then `FUN_00468460(type=0x10,
// guid)` against the object manager — and returns 0 if that lookup
// misses, even though `+0xC0` already holds the right GUID. The
// object-manager entry can drop transiently (zone transitions, brief
// CGPlayer rebuilds) while `+0xC0` stays valid, so for the bare
// `"player"` token we read the canonical pointer directly. Modern
// WoW's `UnitGUID("player")` doesn't gate on object-manager state
// either. Suffixed tokens (`"playertarget"` and the like) still go
// through the engine so the chained `.target` walk works.
//
// The engine populates `+0xC0` from SMSG_UPDATE_OBJECT processing in the
// main loop, which happens AFTER `FrameScript_Initialize` (and the addon
// load pass it triggers) finishes — so the engine value is 0 at addon
// file-load on first login. We bridge that window with `g_charSelectGuid`,
// captured at the glue "Enter World" click (see the co-hook above): the
// selected character's GUID is known well before the player object exists,
// and it's the same value `+0xC0` will hold once it's live. So
// `UnitGUID("player")` / `PlayerGuid()` answer correctly from addon-load
// time. (The player *object* still doesn't exist until `+0xC0` populates —
// this only makes the GUID *value* available early, for keying SavedVariables,
// comparisons, our aura/cast caster checks, etc.)
uint64_t PlayerGuid() {
auto *player = Game::Read<uint8_t *>(Offsets::VAR_LOCAL_PLAYER_PTR);
if (player != nullptr) {
const uint64_t guid =
Game::Read<uint64_t>(player, Offsets::OFF_LOCAL_PLAYER_GUID);
if (guid != 0)
return guid; // live engine value — authoritative
}
return g_charSelectGuid; // early-login fallback (0 until char-select)
}
const uint8_t *PlayerObject() {
// Resolve the player's CGObject straight from the object manager by GUID —
// one hash lookup, no token-string parsing, and non-throwing: the resolver
// returns null when the GUID isn't loaded (pre-world) instead of raising,
// so this is safe from any context (world tick, packet send hook, Lua
// callback). The GUID comes from PlayerGuid() — 0 before char-select, which
// short-circuits to null here. NOT VAR_LOCAL_PLAYER_PTR: its +0xC0 is only
// the GUID, not the canonical CGPlayer whose descriptor is readable.
const uint64_t guid = PlayerGuid();
if (guid == 0)
return nullptr;
return static_cast<const uint8_t *>(
Object::ByGuid(Offsets::TYPEMASK_PLAYER, guid, "ClassicAPI", 0));
}
const uint8_t *PlayerInventoryManager() {
const uint8_t *player = PlayerObject();
if (player == nullptr)
return nullptr;
return player + Offsets::OFF_PLAYER_INVENTORY_MANAGER;
}
const uint8_t *PlayerDescriptor() {
const uint8_t *player = PlayerObject();
if (player == nullptr)
return nullptr;
return Object::Fields(player);
}
uint8_t Race(const uint8_t *fields) {
return fields != nullptr ? Game::Read<uint8_t>(fields, Offsets::OFF_UNIT_DESCRIPTOR_RACE_BYTE)
: 0;
}
uint8_t Class(const uint8_t *fields) {
return fields != nullptr ? Game::Read<uint8_t>(fields, Offsets::OFF_UNIT_DESCRIPTOR_CLASS_BYTE)
: 0;
}
uint8_t Sex(const uint8_t *fields) {
return fields != nullptr ? Game::Read<uint8_t>(fields, Offsets::OFF_UNIT_DESCRIPTOR_SEX_BYTE)
: 0;
}
uint64_t OwnerGuid(const void *unitObject) {
if (unitObject == nullptr)
return 0;
auto *desc = Object::Fields(unitObject);
if (desc == nullptr)
return 0;
const uint64_t charmer = Game::Read<uint64_t>(desc, Offsets::OFF_UNIT_FIELD_CHARMEDBY);
if (charmer != 0)
return charmer;
return Game::Read<uint64_t>(desc, Offsets::OFF_UNIT_FIELD_CREATEDBY);
}
uint32_t CreatedBySpell(const void *unitObject) {
const uint8_t *desc = Object::Fields(unitObject);
return desc != nullptr ? Game::Read<uint32_t>(desc, Offsets::OFF_UNIT_FIELD_CREATED_BY_SPELL)
: 0;
}
bool IsPlayerToken(const char *token) {
if (token == nullptr)
return false;
// Mirror Script_UnitClass/Script_UnitRace byte-for-byte: they compare the
// token via Storm's SStrCmpI(token, "player", 0x7FFFFFFF) (the call at
// 0x005183B0), not the CRT _stricmp. Same case-insensitive result for the
// ASCII literal, but routed through the engine's own comparator.
return Game::StrCmpI(token, "player") == 0;
}
uint64_t GuidForToken(const char *token) {
if (IsPlayerToken(token))
return PlayerGuid();
auto fn = reinterpret_cast<TokenToGUID_t>(Offsets::FUN_TOKEN_TO_GUID);
return fn(token);
}
const uint8_t *PlayerInfoRecord(uint64_t guid) {
if (guid == 0)
return nullptr;
// A null callback only looks up: it never sends a query.
const uint64_t owner = 0;
return Cache::Record::GetPlayer(guid, &owner, nullptr, nullptr, false);
}
const char *NameForGuid(uint64_t guid) {
const uint8_t *rec = PlayerInfoRecord(guid);
if (rec == nullptr)
return nullptr;
const char *name = Game::Ptr<const char>(rec, Offsets::OFF_PLAYER_INFO_NAME);
return (name != nullptr && *name != '\0') ? name : nullptr;
}
const char *NameForUnit(const void *unit, const char **outRealm) {
using GetName_t = const char *(__thiscall *)(const void *unit, const char **outRealm);
return reinterpret_cast<GetName_t>(
static_cast<uintptr_t>(Offsets::FUN_OBJECT_GET_NAME))(unit, outRealm);
}
void ForEachCachedPlayer(CachedPlayerVisitor visit, void *context) {
// Walk the cache's node list the way its save routine NameCacheSave
// (0x0055EC70) does, and read each node's record back through the engine's
// own lookup — which also skips nodes whose query is still pending.
const auto *cache = reinterpret_cast<const void *>(
static_cast<uintptr_t>(Offsets::VAR_PLAYER_NAME_CACHE));
const auto linkOffset = Game::Read<uintptr_t>(cache, Offsets::OFF_NAME_CACHE_LINK_OFFSET);
for (auto node = Game::Read<uintptr_t>(cache, Offsets::OFF_NAME_CACHE_FIRST_NODE);
Storm::IsNode(node);
node = Game::Read<uintptr_t>(node + linkOffset + 4)) { // TSLink {prev, next}
const auto guid = Game::Read<uint64_t>(node + Offsets::OFF_NAME_CACHE_NODE_GUID);
const uint8_t *rec = PlayerInfoRecord(guid);
if (rec != nullptr && !visit(guid, rec, context))
return;
}
}
// `UnitGUID(unit)` — returns the unit's 64-bit GUID formatted as a
// hex string `"0xHHHHHHHHLLLLLLLL"` (16 hex digits, hi dword first).
//
// 1.12 GUIDs are plain 64-bit integers — no type-prefix system like
// modern WoW's `"Player-1234-..."` / `"Creature-0-..."` shapes. Vanilla
// addons that tracked units across events used this `"0x..."` format,
// and 3.3.5's `Script_UnitGUID` (at `0x0060E630` in the Frostmourne
// client) emits the same shape after a much longer code path that
// special-cases sentinel GUID values introduced post-2.x.
//
// Returns `nil` if:
// - the unit token resolves to a GUID of zero (e.g. `"target"`
// when nothing's targeted; `"partyN"` when the slot is empty).
//
// Works for out-of-range party / raid members. The engine maintains
// a parallel GUID array populated by `SMSG_GROUP_LIST` that's
// independent of whether the unit's CGObject is currently active
// in the client. We call `FUN_TOKEN_TO_GUID` directly rather than
// going through `FUN_RESOLVE_UNIT_TOKEN` — the latter does an extra
// `FUN_00468460` step that returns NULL when the CGObject isn't
// live, which is why earlier versions of `UnitGUID` returned nil
// for `"party1"` when the member was on a different continent.
//
// A string that is no unit token answers nil, as in `Script_UnitName` and
// the other engine unit-token consumers (unit/TokenExtensions.cpp).
static int __fastcall Script_UnitGUID(void *L) {
if (!Game::Lua::IsString(L, 1)) {
Game::Lua::Error(L, "Usage: UnitGUID(\"unit\")");
return 0;
}
const char *token = Game::Lua::ToString(L, 1);
if (token == nullptr)
return 0;
const uint64_t guid = GuidForToken(token);
if (guid == 0)
return 0;
char buf[Guid::STRING_SIZE];
Game::Lua::PushString(L, Guid::FormatAsString(guid, buf, sizeof buf));
return 1;
}
// `UnitTokenFromGUID(guid)` — best-effort reverse lookup: given a unit
// GUID, return the first unit token currently mapped to that GUID, or
// nil if none of the known tokens point at it.
//
// The search walks the modern retail token order with post-vanilla
// tokens dropped (no `vehicle`, `arenaN`, `arenapetN`, `bossN` — those
// post-date 1.12 and `FUN_TOKEN_TO_GUID` knows none of them). `nameplateN`, `focus` and the soft targets are included — we
// hook the token resolver so the engine recognizes them (see
// `unit/TokenExtensions.cpp`, `unit/Focus.cpp`, `target/SoftInteract.cpp`
// and `target/SoftUnit.cpp`). Order matches retail with the dropped
// tokens skipped in place:
//
// player → pet → party1..4 → partypet1..4 → raid1..40
// → raidpet1..40 → nameplate1..N → target → focus
// → npc → mouseover → softenemy → softfriend → softinteract
//
// `markN` is not in retail's list, so it is never returned here.
//
// The result is inherently unstable — multiple tokens can map to the
// same GUID at once (your target IS your mouseover IS your party1), and
// the mapping changes across frames as `SMSG_GROUP_LIST` /
// `SMSG_AURA_UPDATE` etc. fire. Same caveat as modern's API; addons
// that cache the return should re-verify with `UnitGUID(token)`
// before each use.
//
// Returns `nil` if the input string isn't a parseable GUID, or the
// GUID is zero, or no token currently maps to it.
const char *TokenFromGUID(uint64_t target, char *buf, size_t bufSize) {
if (target == 0)
return nullptr;
auto set = [&](const char *token) -> const char * {
std::snprintf(buf, bufSize, "%s", token);
return buf;
};
auto check = [&](const char *token) -> bool {
return GuidForToken(token) == target;
};
if (check("player")) return set("player");
if (check("pet")) return set("pet");
// Cap each indexed-token scan at the actual populated slot
// count, read straight out of engine memory. Solo skips all 88
// group tokens; a 5-person party scans 8 instead of 88. Raid
// and party are NOT mutually exclusive — in a 40-man raid the
// engine still tracks the player's 5-person subgroup in the
// party array, so we iterate both independently when both have
// populated slots.
//
// Party count = number of non-zero GUIDs in the 4-slot party
// GUID array. Same walk `Script_GetNumPartyMembers` does
// internally (`FUN_004E86D0`), inlined here.
const int partyCount = Group::Roster::PartyCount();
const int raidCount = Group::Roster::RaidCount();
for (int i = 1; i <= partyCount; ++i) {
std::snprintf(buf, bufSize, "party%d", i);
if (GuidForToken(buf) == target) return buf;
}
for (int i = 1; i <= partyCount; ++i) {
std::snprintf(buf, bufSize, "partypet%d", i);
if (GuidForToken(buf) == target) return buf;
}
for (int i = 1; i <= raidCount; ++i) {
std::snprintf(buf, bufSize, "raid%d", i);
if (GuidForToken(buf) == target) return buf;
}
for (int i = 1; i <= raidCount; ++i) {
std::snprintf(buf, bufSize, "raidpet%d", i);
if (GuidForToken(buf) == target) return buf;
}
// Visible nameplates. The slot array is SPARSE (retail-exact slot
// assignment — freed middle slots stay as gaps until reused), so we
// scan `1..GetSlotCount()` and skip empties rather than stopping at
// the first 0. Compares GUIDs directly, skipping the token-resolver
// hook + SStrCmpI cost per index.
const int plateCount = NamePlate::Events::GetSlotCount();
for (int i = 1; i <= plateCount; ++i) {
if (NamePlate::Events::GetGUIDByIndex(i) == target) {
std::snprintf(buf, bufSize, "nameplate%d", i);
return buf;
}
}
if (check("target")) return set("target");
if (check("focus")) return set("focus");
if (check("npc")) return set("npc");
if (check("mouseover")) return set("mouseover");
if (check("softenemy")) return set("softenemy");
if (check("softfriend")) return set("softfriend");
if (check("softinteract")) return set("softinteract");
return nullptr;
}
int TokensForGUID(uint64_t guid, char (*out)[32], int maxTokens) {
if (guid == 0 || out == nullptr || maxTokens <= 0)
return 0;
int n = 0;
// Engine-native tokens via the reverse map. It fills a shared static
// array and returns its base; snapshot each string into `out` before we
// do anything re-entrant. Non-throwing (count 0 pre-world).
using TokensFromGuid_t =
const char *const *(__fastcall *)(const uint64_t *guid, int *outCount);
int nativeCount = 0;
const char *const *natives = reinterpret_cast<TokensFromGuid_t>(
static_cast<uintptr_t>(Offsets::FUN_UNIT_TOKENS_FROM_GUID))(&guid,
&nativeCount);
if (natives != nullptr) {
for (int i = 0; i < nativeCount && n < maxTokens; ++i) {
const char *tok = natives[i];
if (tok == nullptr)
continue;
// SuperWoW patches this reverse map to ALSO emit the caster's raw
// GUID string ("0x…") as a token (it makes GUID strings valid unit
// tokens). Skip it — the standard tokens are what retail-compat
// addons expect; echoing the GUID we were handed is noise.
if (tok[0] == '0' && (tok[1] == 'x' || tok[1] == 'X'))
continue;
std::snprintf(out[n], 32, "%s", tok);
++n;
}
}
// ClassicAPI's tokens, which the engine's map can't produce: the same
// list the engine's unit events reach.
return n + Unit::TokenEvents::TokensOf(guid, out + n, maxTokens - n);
}
static int __fastcall Script_UnitTokenFromGUID(void *L) {
if (!Game::Lua::IsString(L, 1)) {
Game::Lua::Error(L, "Usage: UnitTokenFromGUID(\"unitGUID\")");
return 0;
}
const char *guidStr = Game::Lua::ToString(L, 1);
uint64_t target = 0;
if (guidStr == nullptr || !Guid::Parse(guidStr, &target) || target == 0)
return 0;
char buf[32];
const char *token = TokenFromGUID(target, buf, sizeof buf);
if (token == nullptr)
return 0;
Game::Lua::PushString(L, token);
return 1;
}
uint64_t FindGuidByName(const char *name, uint32_t typeMask, bool exact, int mode) {
if (name == nullptr || name[0] == '\0')
return 0;
auto find = reinterpret_cast<FindUnitByName_t>(Offsets::FUN_UNIT_FIND_BY_NAME);
return find(name, typeMask, mode, exact ? 1 : 0, kMaxDistanceFltMax);
}
// `UnitTokenFromName(name [, exactMatch])` -> unit token, or nothing.
//
// The unit functions take the name of you, a group member or one of your
// pets directly (unit/TokenExtensions.cpp), but not anyone else's. This runs
// the engine's own by-name search — the one behind `TargetByName`, over every
// unit nearby — and reports the winner as something they accept.
//
// Prefers a standard token (`party1`, `target`, …) so callers get the
// stable, readable form, and falls back to the GUID literal for a unit no
// token names, since the resolver takes those too. `exactMatch` mirrors
// `TargetByName`: clear matches on the start of the name, set requires all
// of it.
static int __fastcall Script_UnitTokenFromName(void *L) {
if (!Game::Lua::IsString(L, 1)) {
Game::Lua::Error(L, "Usage: UnitTokenFromName(\"name\" [, exactMatch])");
return 0;
}
const char *name = Game::Lua::ToString(L, 1);
if (name == nullptr || name[0] == '\0')
return 0;
const uint64_t guid =
FindGuidByName(name, Offsets::TYPEMASK_UNIT, Game::Lua::ToBoolean(L, 2) != 0);
if (guid == 0)
return 0;
char buf[32];
if (const char *token = TokenFromGUID(guid, buf, sizeof buf)) {
Game::Lua::PushString(L, token);
return 1;
}
char guidBuf[Guid::STRING_SIZE];
Game::Lua::PushString(L, Guid::FormatAsString(guid, guidBuf, sizeof guidBuf));
return 1;
}
// --- Documentation ----------------------------------------------------------
namespace {
const Game::Doc::Field kUnitGUIDArgs[] = {
Game::Doc::Req("unit", "UnitToken"),
};
const Game::Doc::Field kUnitGUIDRets[] = {
Game::Doc::Opt("result", "WOWGUID", nullptr,
"A \"0x\" hex string; nil when the token names no unit."),
};
const Game::Doc::Function kUnitGUID{
"Returns the GUID of a unit, also for a group member out of range.", kUnitGUIDArgs,
kUnitGUIDRets, "UnitGlobals"};
const Game::Doc::Field kTokenFromGUIDArgs[] = {
Game::Doc::Req("unitGUID", "WOWGUID"),
};
const Game::Doc::Field kTokenFromGUIDRets[] = {
Game::Doc::Opt("unitToken", "string", nullptr,
"Nil when no unit token points at the GUID now."),
};
const Game::Doc::Function kUnitTokenFromGUID{
"Returns the first unit token that currently points at a GUID.", kTokenFromGUIDArgs,
kTokenFromGUIDRets, "UnitGlobals"};
const Game::Doc::Field kTokenFromNameArgs[] = {
Game::Doc::Req("name", "string"),
Game::Doc::Opt("exactMatch", "bool", "false",
"True requires the whole name; false matches the start of the name."),
};
const Game::Doc::Field kTokenFromNameRets[] = {
Game::Doc::Opt("unitToken", "string", nullptr,
"A standard token when one fits, else the unit's GUID; nil when no unit "
"matches."),
};
const Game::Doc::Function kUnitTokenFromName{
"Returns a unit token for the nearest unit with a name.", kTokenFromNameArgs,
kTokenFromNameRets, "UnitGlobals", true};
} // namespace
static void RegisterLuaFunctions() {
Game::Lua::RegisterGlobalFunction("UnitGUID", &Script_UnitGUID, &kUnitGUID);
Game::Lua::RegisterGlobalFunction("UnitTokenFromGUID", &Script_UnitTokenFromGUID,
&kUnitTokenFromGUID);
Game::Lua::RegisterGlobalFunction("UnitTokenFromName", &Script_UnitTokenFromName,
&kUnitTokenFromName);
}
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace Unit::Identity