From a46d823b018d2a0dbac994e0011d922aa214d968 Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:42:15 -0500 Subject: [PATCH] feat(quest): completed quests on Turtle-lineage servers QueryQuestsCompleted, GetQuestsCompleted, C_QuestLog.IsQuestFlaggedCompleted, C_QuestLog.GetAllCompletedQuestIDs and QUEST_QUERY_COMPLETE, on Turtle clients only. The server answers `.queststatuses` with TWQUEST guild addon messages from the player, split at 2000 characters; the shorter last message is the end of the list, so no timers are needed. The DLL sends the request itself on SMSG_LOGIN_VERIFY_WORLD (the earliest request the server answers), after each turn-in, and from QueryQuestsCompleted. It reads every answer at the packet funnel, checks that the sender is the player, replaces the list and fires QUEST_QUERY_COMPLETE. A turned-in quest goes into the list at once; the server's next answer takes repeatable quests out again. The list lives through /reload. Net::OutPacket replaces the two hand-built CDataStore senders (item cache resend, SetPVP). Replaces the closed Lua collector of PR #86. --- README.md | 3 +- TODO.md | 32 ++--- docs/API.md | 91 +++++++++++++ src/Offsets.h | 19 +++ src/cache/Query.cpp | 37 +----- src/net/PacketReader.h | 14 ++ src/net/PacketWriter.cpp | 67 ++++++++++ src/net/PacketWriter.h | 45 +++++++ src/pvp/Flag.cpp | 29 +--- src/quest/Completed.cpp | 278 +++++++++++++++++++++++++++++++++++++++ 10 files changed, 542 insertions(+), 73 deletions(-) create mode 100644 src/net/PacketWriter.cpp create mode 100644 src/net/PacketWriter.h create mode 100644 src/quest/Completed.cpp diff --git a/README.md b/README.md index 01f18445..62e4b9c2 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ In the Frame rows, a name that starts with `:` is a method of the widget that th | [Pet](docs/API.md#pet) | `IsPetAttackAction`, `IsAtStableMaster` | | [PlayerInfo](docs/API.md#playerinfo) | `C_PlayerInfo.CanUseItem`, `C_PlayerInfo.GetClass`, `C_PlayerInfo.GetName`, `C_PlayerInfo.GetRace`, `C_PlayerInfo.GetSex`, `C_PlayerInfo.GUIDIsCreature`, `C_PlayerInfo.GUIDIsGameObject`, `C_PlayerInfo.GUIDIsPet`, `C_PlayerInfo.GUIDIsPlayer`, `C_PlayerInfo.IsConnected` | | [Profiling](docs/API.md#profiling) | `GetAddOnCPUUsage`, `GetAddOnMemoryUsage`, `GetEventCPUUsage`, `GetFrameCPUUsage`, `GetFunctionCPUUsage`, `GetScriptCPUUsage`, `ResetCPUUsage`, `UpdateAddOnCPUUsage`, `UpdateAddOnMemoryUsage` | -| [Quest](docs/API.md#quest) | `C_QuestLog.GetInfo`, `C_QuestLog.GetNumQuestObjectives`, `C_QuestLog.GetQuestDetails`, `C_QuestLog.GetQuestLogTitle`, `C_QuestLog.GetHeaderIndexForQuest`, `C_QuestLog.GetLogIndexForQuestID`, `C_QuestLog.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogCompletionText`, `GetQuestLogLeaderBoardID` | +| [Quest](docs/API.md#quest) | `C_QuestLog.GetInfo`, `C_QuestLog.GetNumQuestObjectives`, `C_QuestLog.GetQuestDetails`, `C_QuestLog.GetQuestLogTitle`, `C_QuestLog.GetHeaderIndexForQuest`, `C_QuestLog.GetLogIndexForQuestID`, `C_QuestLog.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogCompletionText`, `GetQuestLogLeaderBoardID` (Turtle WoW only: `C_QuestLog.GetAllCompletedQuestIDs`, `C_QuestLog.IsQuestFlaggedCompleted`, `GetQuestsCompleted`, `QueryQuestsCompleted`) | | [Sound](docs/API.md#sound) | `C_Sound.GetRecentSoundFiles`, `C_Sound.GetSoundScaledVolume`, `C_Sound.IsPlaying`, `C_Sound.PlayItemSound`, `C_Sound.PlaySound`, `C_Sound.PlaySoundWithOptions`, `C_Sound.PlayVocalErrorSound`, `MuteSoundFile`, `PlaySound`, `PlaySoundFile`, `StopSound`, `UnmuteSoundFile` | | [Spell](docs/API.md#spell) | `C_Spell.CancelSpellByID`, `C_Spell.CastAtCursor`, `C_Spell.CastAtUnit`, `C_Spell.CastingInfo`, `C_Spell.ChannelInfo`, `C_Spell.DoesSpellExist`, `C_Spell.GetSchoolString`, `C_Spell.GetSpellCastCount`, `C_Spell.GetSpellCooldown`, `C_Spell.GetSpellDescription`, `C_Spell.GetSpellDispelType`, `C_Spell.GetSpellEffectInfo`, `C_Spell.GetSpellEffectMechanics`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLevelInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellLossOfControlCooldown`, `C_Spell.GetSpellMechanicByID`, `C_Spell.GetSpellName`, `C_Spell.GetSpellPowerCost`, `C_Spell.GetSpellRadius`, `C_Spell.GetSpellReagents`, `C_Spell.GetSpellRequiredTargetLevel`, `C_Spell.GetSpellSubtext`, `C_Spell.GetSpellTexture`, `C_Spell.IsAutoAttackSpell`, `C_Spell.IsCurrentSpell`, `C_Spell.IsNextMeleeSpell`, `C_Spell.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellInRange`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.ResetsMeleeSwing`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `CanDualWield`, `CancelSpellByName`, `CancelUnitBuff`, `CastSpellByID`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetCritChance`, `GetRangedCritChance`, `GetSpellBaseCooldown`, `GetSpellBonusDamage`, `GetSpellBonusHealing`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellRequiredTargetLevel`, `GetSpellSchool`, `IsAttackSpell`, `IsAutoRepeatSpell`, `IsConsumableSpell`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange` | | [SpellBook](docs/API.md#spellbook) | `C_SpellBook.ContainsAnyDisenchantSpell`, `C_SpellBook.GetCurrentLevelSpells`, `C_SpellBook.GetNumSpellBookSkillLines`, `C_SpellBook.GetPlayerSpellsByAura`, `C_SpellBook.GetSkillLineIndexByID`, `C_SpellBook.GetSkillLineName`, `C_SpellBook.GetSkillLineRank`, `C_SpellBook.GetSpellBookItemCastCount`, `C_SpellBook.GetSpellBookItemInfo`, `C_SpellBook.GetSpellBookItemLossOfControlCooldownDuration`, `C_SpellBook.GetSpellBookItemLossOfControlCooldownInfo`, `C_SpellBook.GetSpellBookItemSkillLineIndex`, `C_SpellBook.GetSpellBookSkillLineInfo`, `C_SpellBook.GetSpellLevelLearned`, `C_SpellBook.GetSpellSkillLine`, `C_SpellBook.IsAutoAttackSpellBookItem`, `C_SpellBook.IsClassTalentSpellBookItem`, `C_SpellBook.IsRangedAutoAttackSpellBookItem`, `FindSpellBookSlotByID` | @@ -309,6 +309,7 @@ when launching with `-console`), not as Lua functions. See the | `PLAYER_TOTEM_UPDATE` | `totemSlot` | | `QUEST_ACCEPTED` | `questLogIndex, questID` | | `QUEST_DATA_LOAD_RESULT` | `questID, success` | +| `QUEST_QUERY_COMPLETE` | *(none)* (Turtle WoW only) | | `QUEST_REMOVED` | `questID` | | `QUEST_TURNED_IN` | `questID, xpReward, moneyReward` | | `SOUNDKIT_FINISHED` | `soundHandle` (only for sounds played with `runFinishCallback`) | diff --git a/TODO.md b/TODO.md index 0e20f02a..654bb9fc 100644 --- a/TODO.md +++ b/TODO.md @@ -5,23 +5,25 @@ Candidates for new DLL functions, prioritized. All are things the addon polyfills badly, hackily, or not at all, and where engine access is the right answer. -## ~~1. `C_QuestLog.IsQuestFlaggedCompleted(questID)`~~ — NOT FEASIBLE in 1.12 +## ~~1. `C_QuestLog.IsQuestFlaggedCompleted(questID)`~~ — DONE (Turtle-lineage servers) -The original TODO note ("engine maintains a completed-quests bitfield in -client memory") was based on 3.3.5 / WotLK semantics. Vanilla 1.12 has no -equivalent: neither `QueryQuestsCompleted` nor `GetQuestsCompleted` -exists, the protocol has no `CMSG_QUERY_QUESTS_COMPLETED`, and the -client doesn't track historical completions. The polyfill at -`Util/C_QuestLog.lua:5-8` works on Frostmourne (3.3.5a) where those -functions exist; on the 1.12 Octo client they're absent. +Stock 1.12 has no completed-quests query and keeps no quest history, so +this exists only where the server offers the list another way. Turtle WoW +and its forks answer the player command `.queststatuses` with `TWQUEST` +guild addon messages from the player, split at 2000 characters, the last +message always shorter (probed: 2003, 2004, 0) - an exact end marker. -Servers that want to expose this in 1.12 (notably Turtle WoW) do it -via the `CHAT_MSG_ADDON` channel — the addon sends `.queststatus` over -guild/whisper chat and the server replies with addon-channel messages -the addon parses. Fundamentally async, server-specific, and requires -SavedVariables-style persistence across sessions to amortize the -round-trip — all of which belong on the Lua side, not in this DLL. -There's nothing the DLL can usefully add here. +[src/quest/Completed.cpp](src/quest/Completed.cpp) does it all in the DLL, +Turtle clients only: it sends the request itself (on +SMSG_LOGIN_VERIFY_WORLD, after each turn-in, and from +`QueryQuestsCompleted`), reads every answer at the packet funnel (sender +must be the player), and keeps the live list behind `GetQuestsCompleted`, +`C_QuestLog.IsQuestFlaggedCompleted` and +`C_QuestLog.GetAllCompletedQuestIDs`; `QUEST_QUERY_COMPLETE` fires per +answer. No disk cache: the first answer lands one round trip after +PLAYER_ENTERING_WORLD, because the server sends the player object (which +fires PLAYER_LOGIN) before it reads any request. Replaces the closed Lua +collector of PR #86. ## ~~2. `C_Spell.GetSpellDescription(spellID)`~~ — DONE diff --git a/docs/API.md b/docs/API.md index 48cd43da..7f30f6d6 100644 --- a/docs/API.md +++ b/docs/API.md @@ -237,6 +237,7 @@ build instructions. - [`PLAYER_SWING` event](#player_swing-event) - [`PLAYER_SWING_RANGE_UPDATE` event](#player_swing_range_update-event) - [`QUEST_ACCEPTED` event](#quest_accepted-event) + - [`QUEST_QUERY_COMPLETE` event](#quest_query_complete-event) - [`QUEST_REMOVED` event](#quest_removed-event) - [`QUEST_TURNED_IN` event](#quest_turned_in-event) - [`SOUNDKIT_FINISHED` event](#soundkit_finished-event) @@ -774,6 +775,11 @@ build instructions. - [`C_QuestLog.IsQuestDataCachedByID(questID)`](#c_questlogisquestdatacachedbyidquestid) - [`GetQuestLogLeaderBoardID(objectiveIndex [, questIndex])`](#getquestlogleaderboardidobjectiveindex--questindex) - [`GetQuestLogCompletionText([questLogIndex])`](#getquestlogcompletiontextquestlogindex) + - [Completed quests](#completed-quests) + - [`QueryQuestsCompleted()`](#queryquestscompleted) + - [`GetQuestsCompleted([questTable])`](#getquestscompletedquesttable) + - [`C_QuestLog.IsQuestFlaggedCompleted(questID)`](#c_questlogisquestflaggedcompletedquestid) + - [`C_QuestLog.GetAllCompletedQuestIDs()`](#c_questloggetallcompletedquestids) - [A turn-in always prints "*quest* completed."](#a-turn-in-always-prints-quest-completed) - [Sound](#sound) @@ -5675,6 +5681,16 @@ When the static data for a quest is not in the client cache yet, the event waits for the server to answer. The delay is one round trip. The system message waits with it, so the order does not change. +### `QUEST_QUERY_COMPLETE` event + +Fires on a Turtle WoW client when a copy of the list of completed quests +arrives from the server. The event has no payload. Read the list with +`GetQuestsCompleted` or `C_QuestLog.GetAllCompletedQuestIDs`. + +The event fires a short time after each login, and after each request for +the list. A request can come from `QueryQuestsCompleted`, from a quest +turn-in, or from another addon. See [Completed quests](#completed-quests). + ### `QUEST_REMOVED` event Fires once per quest leaving the local quest log, with the questID as @@ -17879,6 +17895,81 @@ print(GetQuestLogCompletionText()) -- "Kill 12 Kobold Laborers, then return to Marshal McBride at Northshire Abbey." ``` +### Completed quests + +The functions in this group give the quests that the character has +completed. They exist only on a Turtle WoW client, or on a client that is +built on it. On other clients, they are not defined. + +The server keeps the list of completed quests. The client gets a copy of +the list at these times: + +- At each login, a short time after `PLAYER_ENTERING_WORLD`. Until then, + the list is empty. +- After each `QueryQuestsCompleted` call. +- After each quest turn-in. +- When an addon sends the `.queststatuses` chat command. + +Each copy replaces the list, and then `QUEST_QUERY_COMPLETE` fires. + +The list does not include repeatable quests. When you turn in a quest, the +quest goes into the list before `QUEST_TURNED_IN` fires. A repeatable quest +stays in the list until the next copy arrives. + +The list stays after `/reload`. The server sends the copy as +`CHAT_MSG_ADDON` messages with the prefix `TWQUEST`, so other addons also +see these messages. + +### `QueryQuestsCompleted()` + +Turtle WoW only (see [Completed quests](#completed-quests)). Sends a +request for the list of completed quests to the server, and returns at +once. When the list arrives, `QUEST_QUERY_COMPLETE` fires. + +Each call sends a request. If the server does not answer, the event does +not fire. For example, the server ignores a request that it gets during the +loading screen of a teleport. + +```lua +local f = CreateFrame("Frame") +f:RegisterEvent("QUEST_QUERY_COMPLETE") +f:SetScript("OnEvent", function() + local completed = GetQuestsCompleted() + -- completed[questID] is true for each completed quest +end) +QueryQuestsCompleted() +``` + +### `GetQuestsCompleted([questTable])` + +Turtle WoW only (see [Completed quests](#completed-quests)). Returns a +table in which the key of each completed quest is its quest ID and the +value is `true`. + +- If you give `questTable`, the function adds the quests to that table and + returns it. +- If you do not give a table, the function returns a new table. + +The function returns the list that the client has now. It does not send a +request. + +```lua +if GetQuestsCompleted()[4813] then + -- The Fragments Within is complete +end +``` + +### `C_QuestLog.IsQuestFlaggedCompleted(questID)` + +Turtle WoW only (see [Completed quests](#completed-quests)). Returns `true` +if the quest is in the list of completed quests, and `false` if not. Until +the list arrives after login, the function returns `false` for all quests. + +### `C_QuestLog.GetAllCompletedQuestIDs()` + +Turtle WoW only (see [Completed quests](#completed-quests)). Returns an +array of the completed quest IDs, from the lowest ID to the highest. + ### A turn-in always prints "*quest* completed." Every quest turn-in puts `ERR_QUEST_COMPLETE_S` ("Bashal'Aran completed.") diff --git a/src/Offsets.h b/src/Offsets.h index 9320f49f..c6e06245 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -2328,6 +2328,11 @@ enum Offsets { OFF_PENDING_CHAT_CHANNEL = 0x2C, // char[0x80] OFF_PENDING_CHAT_FLAGS = 0xB8, // char[5] SMSG_MESSAGECHAT = 0x96, + // Outgoing chat: u32 type, u32 language, a C-string target for whisper + // (6) and channel (14) only, then the C-string text. SendChatMessage + // sends the race's default language; CGPlayer_C::SetAFK / ClearAFK send + // language 0 (benilla-re ui/chatsend "The chat packet"). + CMSG_MESSAGECHAT = 0x95, // CHAT_MSG_* event fire, `__fastcall(text, chatType)` + 6 stack args // (senderName, languageID, channelString, targetName, flags, channel // record), RET 0x18. Three callers: FUN_CHAT_DISPATCH, FUN_0049B1B0 @@ -9535,6 +9540,14 @@ enum Offsets { // pre-validate. FUN_SCRIPT_GET_TALENT_INFO = 0x004F3200, + // SMSG_LOGIN_VERIFY_WORLD — the server's answer to CMSG_PLAYER_LOGIN, + // and only to it (a world transfer sends SMSG_NEW_WORLD): u32 map, the + // position and facing. Its handler is registered last by 0x00401570 + // (benilla-re ui/worldenter). The server sends it from the same call + // that puts the player in the world and then sends the player's own + // object (tortoise-wow WorldSession::HandlePlayerLogin → Map::Add). + SMSG_LOGIN_VERIFY_WORLD = 0x236, + // Game-time struct populated by SMSG_LOGIN_VERIFY_WORLD / // SMSG_LOGIN_SETTIMESPEED. The engine maintains it as the current // server clock, advanced by an internal tick handler. `Script_GetGameTime` @@ -10178,6 +10191,7 @@ enum Offsets { // hook the per-opcode handler directly to keep our gate narrow. // Hooked by `Quest::TurnedIn` to fire `QUEST_TURNED_IN(questID, xp, money)`. FUN_QUEST_GIVER_QUEST_COMPLETE_HANDLER = 0x005DC400, + SMSG_QUESTGIVER_QUEST_COMPLETE = 0x191, // The two tests that keep " completed." out of chat for a quest in // the middle of a chain. The handler above looks the quest up in the quest @@ -11292,6 +11306,11 @@ enum Offsets { FUN_DATASTORE_PUT_GUID = 0x00418370, // CDataStore::PutInt8 — `__thiscall(this, u8)`, RET 4. Disassembled. FUN_DATASTORE_PUT_U8 = 0x00418070, + // CDataStore::PutString — `__thiscall(this, const char *)`, RET 4: puts + // strlen+1 bytes (the terminator included) through 0x00418570; a null + // string sets last error 0x57 and puts nothing. Disassembled; the chat + // packet's text (benilla-re ui/chatsend). + FUN_DATASTORE_PUT_CSTRING = 0x00418430, VTABLE_CDATASTORE = 0x007FF9E4, // ClientServices::Send — `__thiscall void(CDataStore *packet)`: sends on // the current connection through FUN_NET_SEND when one exists (benilla-re diff --git a/src/cache/Query.cpp b/src/cache/Query.cpp index 1a2f658c..042023de 100644 --- a/src/cache/Query.cpp +++ b/src/cache/Query.cpp @@ -15,45 +15,18 @@ #include "Game.h" #include "Offsets.h" +#include "net/PacketWriter.h" namespace Cache::Query { -namespace { - -// The engine's stack CDataStore (see Offsets::VTABLE_CDATASTORE). -struct DataStore { - uintptr_t vtable; - void *buffer; - uint32_t base; - uint32_t alloc; - uint32_t size; - uint32_t read; -}; -static_assert(sizeof(DataStore) == 0x18, "CDataStore layout"); - -using PutU32_t = void(__thiscall *)(DataStore *self, uint32_t value); -using PutGuid_t = void(__thiscall *)(DataStore *self, uint32_t lo, uint32_t hi); -using Send_t = void(__thiscall *)(DataStore *self); -using Free_t = void(__thiscall *)(DataStore *self, void **buffer, uint32_t *base, uint32_t *alloc); - -} // namespace - // The send of FUN_DBCACHE_ITEMSTATS_GET_RECORD (0x0055BB18..0x0055BB89), // step for step. Every DBCache clone builds the same packet. void Send(void *cache, uint32_t key) { - DataStore packet{Offsets::VTABLE_CDATASTORE, nullptr, 0, 0, 0, 0xFFFFFFFF}; - const auto putU32 = reinterpret_cast(Offsets::FUN_DATASTORE_PUT_U32); - putU32(&packet, Game::Read(cache, Offsets::OFF_DBCACHE_QUERY_OPCODE)); - putU32(&packet, key); + Net::OutPacket packet(Game::Read(cache, Offsets::OFF_DBCACHE_QUERY_OPCODE)); + packet.PutU32(key); if (Game::Read(cache, Offsets::OFF_DBCACHE_OWNER_FLAG) != 0) - reinterpret_cast(Offsets::FUN_DATASTORE_PUT_GUID)(&packet, 0, 0); - packet.read = 0; - reinterpret_cast(Offsets::FUN_CLIENT_SERVICES_SEND)(&packet); - if (packet.alloc != 0xFFFFFFFF) { - const auto release = - *reinterpret_cast(Offsets::VTABLE_CDATASTORE + sizeof(uintptr_t)); - release(&packet, &packet.buffer, &packet.base, &packet.alloc); - } + packet.PutGuid(0); + packet.Send(); } } // namespace Cache::Query diff --git a/src/net/PacketReader.h b/src/net/PacketReader.h index 27178f9d..ff02e6f7 100644 --- a/src/net/PacketReader.h +++ b/src/net/PacketReader.h @@ -54,6 +54,20 @@ T Read(CDataStore *p) { return val; } +// Returns the next `n` bytes in place and advances the cursor past them, as +// the engine's `CDataStore::GetDataInSitu` (0x00419AC0) does for chat text. +// On overrun it poisons `m_read` and returns null. The bytes live in the +// packet, so read them before the subscriber returns. +inline const uint8_t *ReadBytes(CDataStore *p, uint32_t n) { + if (p->m_read > p->m_size || n > p->m_size - p->m_read) { + p->m_read = p->m_size + 1; + return nullptr; + } + const uint8_t *at = p->m_buffer - p->m_base + p->m_read; + p->m_read += n; + return at; +} + // Reads a WoW packed GUID: a 1-byte mask followed by one byte per set bit, // each contributing the corresponding byte of the 64-bit value. inline uint64_t ReadPackedGuid(CDataStore *p) { diff --git a/src/net/PacketWriter.cpp b/src/net/PacketWriter.cpp new file mode 100644 index 00000000..974439d2 --- /dev/null +++ b/src/net/PacketWriter.cpp @@ -0,0 +1,67 @@ +// 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. + +#include "net/PacketWriter.h" + +#include "Offsets.h" + +namespace Net { + +namespace { + +using PutU8_t = void(__thiscall *)(CDataStore *self, uint8_t value); +using PutU32_t = void(__thiscall *)(CDataStore *self, uint32_t value); +using PutGuid_t = void(__thiscall *)(CDataStore *self, uint32_t lo, uint32_t hi); +using PutString_t = void(__thiscall *)(CDataStore *self, const char *text); +using Send_t = void(__thiscall *)(CDataStore *self); +using Free_t = void(__thiscall *)(CDataStore *self, uint8_t **buffer, uint32_t *base, + uint32_t *alloc); + +static_assert(sizeof(CDataStore) == 0x18, "CDataStore layout"); + +} // namespace + +OutPacket::OutPacket(uint32_t opcode) + : m_store{reinterpret_cast(Offsets::VTABLE_CDATASTORE), nullptr, 0, 0, 0, + 0xFFFFFFFF} { + PutU32(opcode); +} + +OutPacket::~OutPacket() { + if (m_store.m_alloc != 0xFFFFFFFF) { + const auto release = + *reinterpret_cast(Offsets::VTABLE_CDATASTORE + sizeof(uintptr_t)); + release(&m_store, &m_store.m_buffer, &m_store.m_base, &m_store.m_alloc); + } +} + +void OutPacket::PutU8(uint8_t value) { + reinterpret_cast(Offsets::FUN_DATASTORE_PUT_U8)(&m_store, value); +} + +void OutPacket::PutU32(uint32_t value) { + reinterpret_cast(Offsets::FUN_DATASTORE_PUT_U32)(&m_store, value); +} + +void OutPacket::PutGuid(uint64_t guid) { + reinterpret_cast(Offsets::FUN_DATASTORE_PUT_GUID)( + &m_store, static_cast(guid), static_cast(guid >> 32)); +} + +void OutPacket::PutString(const char *text) { + reinterpret_cast(Offsets::FUN_DATASTORE_PUT_CSTRING)(&m_store, text); +} + +void OutPacket::Send() { + m_store.m_read = 0; + reinterpret_cast(Offsets::FUN_CLIENT_SERVICES_SEND)(&m_store); +} + +} // namespace Net diff --git a/src/net/PacketWriter.h b/src/net/PacketWriter.h new file mode 100644 index 00000000..c5fd88d3 --- /dev/null +++ b/src/net/PacketWriter.h @@ -0,0 +1,45 @@ +// 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. + +#pragma once + +#include "net/PacketReader.h" + +#include + +// Outgoing packets, built the way every client send builds one: a stack +// `CDataStore` with the engine's vtable, filled through the engine's own Put +// functions, sent through ClientServices::Send, then freed through the +// vtable's slot 1 (the send of FUN_DBCACHE_ITEMSTATS_GET_RECORD, +// 0x0055BB18..0x0055BB89, step for step). The first write is the opcode as a +// u32. ClientServices::Send drops the packet while there is no world +// connection (benilla-re net/server). + +namespace Net { + +class OutPacket { +public: + explicit OutPacket(uint32_t opcode); + ~OutPacket(); + OutPacket(const OutPacket &) = delete; + OutPacket &operator=(const OutPacket &) = delete; + + void PutU8(uint8_t value); + void PutU32(uint32_t value); + void PutGuid(uint64_t guid); + // A C string with its terminator. + void PutString(const char *text); + void Send(); + +private: + CDataStore m_store; +}; + +} // namespace Net diff --git a/src/pvp/Flag.cpp b/src/pvp/Flag.cpp index 821fc9e1..b8870118 100644 --- a/src/pvp/Flag.cpp +++ b/src/pvp/Flag.cpp @@ -15,6 +15,7 @@ #include "Game.h" #include "Offsets.h" #include "event/Custom.h" +#include "net/PacketWriter.h" #include "time/Clock.h" #include "unit/Identity.h" @@ -70,21 +71,6 @@ void SetRunning(bool running) { Event::Custom::Fire(_timerUpdate.Slot(), "%s", "player"); } -// The engine's stack CDataStore (see Offsets::VTABLE_CDATASTORE). -struct DataStore { - uintptr_t vtable; - void *buffer; - uint32_t base; - uint32_t alloc; - uint32_t size; - uint32_t read; -}; -static_assert(sizeof(DataStore) == 0x18, "CDataStore layout"); - -using PutU32_t = void(__thiscall *)(DataStore *self, uint32_t value); -using PutU8_t = void(__thiscall *)(DataStore *self, uint8_t value); -using Send_t = void(__thiscall *)(DataStore *self); -using Free_t = void(__thiscall *)(DataStore *self, void **buffer, uint32_t *base, uint32_t *alloc); using DisplayError_t = void(__cdecl *)(uint32_t id); using UnitFn_t = uint32_t(__thiscall *)(void *unit); @@ -138,16 +124,9 @@ int32_t ToggleTimer() { int __fastcall Script_SetPVP(void *L) { const bool enable = Game::Lua::IsNumber(L, 1) ? Game::Lua::ToNumber(L, 1) != 0.0 : Game::Lua::ToBoolean(L, 1) != 0; - DataStore packet{Offsets::VTABLE_CDATASTORE, nullptr, 0, 0, 0, 0xFFFFFFFF}; - reinterpret_cast(Offsets::FUN_DATASTORE_PUT_U32)(&packet, CMSG_TOGGLE_PVP); - reinterpret_cast(Offsets::FUN_DATASTORE_PUT_U8)(&packet, enable ? 1 : 0); - packet.read = 0; - reinterpret_cast(Offsets::FUN_CLIENT_SERVICES_SEND)(&packet); - if (packet.alloc != 0xFFFFFFFF) { - const auto release = - *reinterpret_cast(Offsets::VTABLE_CDATASTORE + sizeof(uintptr_t)); - release(&packet, &packet.buffer, &packet.base, &packet.alloc); - } + Net::OutPacket packet(CMSG_TOGGLE_PVP); + packet.PutU8(enable ? 1 : 0); + packet.Send(); return 0; } diff --git a/src/quest/Completed.cpp b/src/quest/Completed.cpp new file mode 100644 index 00000000..d6d5ee62 --- /dev/null +++ b/src/quest/Completed.cpp @@ -0,0 +1,278 @@ +// 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. + +// Completed quests on Turtle-lineage servers: `QueryQuestsCompleted`, +// `GetQuestsCompleted` and `QUEST_QUERY_COMPLETE` (3.3.5), and +// `C_QuestLog.IsQuestFlaggedCompleted` / `C_QuestLog.GetAllCompletedQuestIDs`. +// +// The 1.12 protocol has no completed-quests query and the client keeps no +// quest history. Turtle WoW's server and its forks answer the player command +// `.queststatuses` (tortoise-wow ChatHandler::HandleQuestStatusesCommand, +// SEC_PLAYER) with the character's rewarded quests, repeatable ones left out, +// as addon messages: chat type GUILD, language ADDON, sent by the player, text +// "TWQUEST\t ... ". It sends a message each time its text reaches +// MESSAGE_SPLIT characters and always sends what is left last, so every +// message but the last is at least MESSAGE_SPLIT long and the last is +// shorter - empty when the split fell on the end. An ID never spans two +// messages. Probed on a live Turtle-lineage server for one character: 2003, +// 2004, 0. +// +// The list: +// - is replaced by every complete answer, whoever asked (pfQuest, Questie, a +// typed command), and QUEST_QUERY_COMPLETE fires - as 3.3.5's +// SMSG_QUERY_QUESTS_COMPLETED_RESPONSE handler (0x005B5190) empties its +// list, refills it and signals the event on every response; +// - is asked for once per login, on SMSG_LOGIN_VERIFY_WORLD. The server reads +// chat only while the player is in the world (WorldSession::Update, +// STATUS_LOGGEDIN) and puts the player there in the call that sends this +// packet, so this is the earliest request it answers. The answer still +// lands after PLAYER_LOGIN and PLAYER_ENTERING_WORLD: that call also sends +// the player's own object, which fires both, before the server reads +// anything we send; +// - gets a quest turned in (SMSG_QUESTGIVER_QUEST_COMPLETE) at once, then +// the server is asked again. Only the server knows whether a quest is +// repeatable (quest_template SpecialFlags), and it leaves repeatable +// quests out (Player::RewardQuest sets their status back to NONE), so its +// answer takes them out again; +// - lives through /reload, when nothing is sent, and is emptied at the next +// login. +// +// The request is the packet `SendChatMessage(".queststatuses", "GUILD")` +// sends, without that function's AFK clear, and in language 0 like +// CGPlayer_C::SetAFK's packet: on SMSG_LOGIN_VERIFY_WORLD there is no player +// object to read the race's language from. The server parses commands before +// it looks up the guild (WorldSession::HandleMessagechatOpcode), so the +// request works without one, as pfQuest-turtle and Questie-Octo rely on. +// +// Only on a Turtle-lineage client (Turtle::Detected): elsewhere the text would +// reach guild chat, so nothing is sent and the functions stay absent. + +#include "Game.h" +#include "Offsets.h" +#include "event/Custom.h" +#include "net/PacketDispatch.h" +#include "net/PacketReader.h" +#include "net/PacketWriter.h" +#include "turtle/Detect.h" +#include "unit/Identity.h" + +#include +#include +#include +#include + +namespace Quest::Completed { + +namespace { + +constexpr uint8_t CHAT_MSG_GUILD = 3; +constexpr uint32_t LANG_UNIVERSAL = 0; +constexpr uint32_t LANG_ADDON = 0xFFFFFFFF; +constexpr char COMMAND[] = ".queststatuses"; +constexpr char PREFIX[] = "TWQUEST\t"; +constexpr uint32_t PREFIX_LENGTH = sizeof(PREFIX) - 1; +// HandleQuestStatusesCommand's MaxMessageSize. +constexpr uint32_t MESSAGE_SPLIT = 2000; + +// Sorted and unique: the last complete answer, plus quests turned in since. +std::vector g_completed; +// The IDs of the answer being received; they replace g_completed at its last +// message. +std::vector g_incoming; + +const Game::Doc::Event kQueryCompleteDoc{ + "QuestLog", "Fires when the list of completed quests arrives from the server.", {}}; +const Event::Custom::AutoReserve _reserve{"QUEST_QUERY_COMPLETE", &kQueryCompleteDoc}; + +void Request() { + Net::OutPacket packet(Offsets::CMSG_MESSAGECHAT); + packet.PutU32(CHAT_MSG_GUILD); + packet.PutU32(LANG_UNIVERSAL); + packet.PutString(COMMAND); + packet.Send(); +} + +bool IsCompleted(uint32_t questID) { + return std::binary_search(g_completed.begin(), g_completed.end(), questID); +} + +void OnLoginVerifyWorld() { + g_completed.clear(); + g_incoming.clear(); + if (Turtle::Detected()) + Request(); +} + +void OnQuestComplete(Net::CDataStore *packet) { + const uint32_t questID = Net::Read(packet); + if (packet->m_read > packet->m_size || questID == 0 || !Turtle::Detected()) + return; + const auto at = std::lower_bound(g_completed.begin(), g_completed.end(), questID); + if (at == g_completed.end() || *at != questID) + g_completed.insert(at, questID); + Request(); +} + +// SMSG_MESSAGECHAT for chat type GUILD: u8 type, u32 language, the sender's +// GUID, u32 length (the terminator counted), the text, u8 tag (benilla-re +// ui/chatevents "The chat message"; tortoise-wow ChatHandler::BuildChatPacket). +void OnChat(Net::CDataStore *packet) { + if (Net::Read(packet) != CHAT_MSG_GUILD || Net::Read(packet) != LANG_ADDON) + return; + const uint64_t sender = Net::Read(packet); + const uint32_t length = Net::Read(packet); + const auto *text = reinterpret_cast(Net::ReadBytes(packet, length)); + if (text == nullptr || length <= PREFIX_LENGTH || + std::memcmp(text, PREFIX, PREFIX_LENGTH) != 0) + return; + // Anyone in the guild can send a TWQUEST addon message; the server's + // answer comes from the player. + if (sender == 0 || sender != Unit::Identity::PlayerGuid()) + return; + + const char *ids = text + PREFIX_LENGTH; + const uint32_t idsLength = length - 1 - PREFIX_LENGTH; + uint32_t id = 0; + for (uint32_t i = 0; i < idsLength; ++i) { + const char c = ids[i]; + if (c >= '0' && c <= '9') { + id = id * 10 + static_cast(c - '0'); + } else { + if (id != 0) + g_incoming.push_back(id); + id = 0; + } + } + if (id != 0) + g_incoming.push_back(id); + + if (idsLength >= MESSAGE_SPLIT) + return; + std::sort(g_incoming.begin(), g_incoming.end()); + g_incoming.erase(std::unique(g_incoming.begin(), g_incoming.end()), g_incoming.end()); + g_completed.swap(g_incoming); + g_incoming.clear(); + Event::Custom::Fire(_reserve.Slot(), ""); +} + +void OnPacket(uint32_t opcode, Net::CDataStore *packet) { + switch (opcode) { + case Offsets::SMSG_MESSAGECHAT: + OnChat(packet); + break; + case Offsets::SMSG_LOGIN_VERIFY_WORLD: + OnLoginVerifyWorld(); + break; + case Offsets::SMSG_QUESTGIVER_QUEST_COMPLETE: + OnQuestComplete(packet); + break; + default: + break; + } +} + +const Net::PacketDispatch::AutoSubscribe _sub{&OnPacket}; + +// 3.3.5's Script_QueryQuestsCompleted (0x005B1BB0) sends its request every +// time, with no answer awaited. +int __fastcall Script_QueryQuestsCompleted(void *L) { + (void)L; + Request(); + return 0; +} + +// 3.3.5's Script_GetQuestsCompleted (0x005B5290): fills the table argument, +// or a new table, with [questID] = true. +int __fastcall Script_GetQuestsCompleted(void *L) { + if (Game::Lua::Type(L, 1) == Game::Lua::TYPE_TABLE) + Game::Lua::PushValue(L, 1); + else + Game::Lua::NewTable(L); + for (const uint32_t questID : g_completed) { + Game::Lua::PushNumber(L, static_cast(questID)); + Game::Lua::PushBoolean(L, 1); + Game::Lua::SetTable(L, -3); + } + return 1; +} + +int __fastcall Script_IsQuestFlaggedCompleted(void *L) { + if (!Game::Lua::IsNumber(L, 1)) { + Game::Lua::Error(L, "Usage: C_QuestLog.IsQuestFlaggedCompleted(questID)"); + return 0; + } + const double questID = Game::Lua::ToNumber(L, 1); + Game::Lua::PushBool(L, questID >= 1.0 && questID <= 4294967295.0 && + IsCompleted(static_cast(questID))); + return 1; +} + +int __fastcall Script_GetAllCompletedQuestIDs(void *L) { + Game::Lua::NewTable(L); + int index = 0; + for (const uint32_t questID : g_completed) { + Game::Lua::PushNumber(L, static_cast(++index)); + Game::Lua::PushNumber(L, static_cast(questID)); + Game::Lua::RawSet(L, -3); + } + return 1; +} + +// --- Documentation ---------------------------------------------------------- + +const Game::Doc::Function kQueryQuestsCompleted{ + "Asks the server for the completed quests; QUEST_QUERY_COMPLETE fires when they arrive.", + {}, {}, "QuestLogGlobals"}; + +const Game::Doc::Field kGetQuestsCompletedArgs[] = { + Game::Doc::Opt("questTable", "table", nullptr, + "The table to add the quests to. Without it, a new table."), +}; +const Game::Doc::Field kGetQuestsCompletedRets[] = { + Game::Doc::Req("completedQuests", "table", "Each completed quest ID, set to true."), +}; +const Game::Doc::Function kGetQuestsCompleted{ + "Returns the completed quests.", kGetQuestsCompletedArgs, kGetQuestsCompletedRets, + "QuestLogGlobals"}; + +const Game::Doc::Field kIsQuestFlaggedCompletedArgs[] = { + Game::Doc::Req("questID", "number"), +}; +const Game::Doc::Field kIsQuestFlaggedCompletedRets[] = { + Game::Doc::Req("isCompleted", "bool"), +}; +const Game::Doc::Function kIsQuestFlaggedCompleted{ + "Returns whether the character has completed a quest.", kIsQuestFlaggedCompletedArgs, + kIsQuestFlaggedCompletedRets}; + +const Game::Doc::Field kGetAllCompletedQuestIDsRets[] = { + Game::Doc::Req("quests", "table", "The completed quest IDs, from lowest to highest."), +}; +const Game::Doc::Function kGetAllCompletedQuestIDs{ + "Returns the IDs of the completed quests.", {}, kGetAllCompletedQuestIDsRets}; + +} // namespace + +static void RegisterLuaFunctions() { + if (!Turtle::Detected()) + return; + Game::Lua::RegisterGlobalFunction("QueryQuestsCompleted", &Script_QueryQuestsCompleted, + &kQueryQuestsCompleted); + Game::Lua::RegisterGlobalFunction("GetQuestsCompleted", &Script_GetQuestsCompleted, + &kGetQuestsCompleted); + Game::Lua::RegisterTableFunction("C_QuestLog", "IsQuestFlaggedCompleted", + &Script_IsQuestFlaggedCompleted, &kIsQuestFlaggedCompleted); + Game::Lua::RegisterTableFunction("C_QuestLog", "GetAllCompletedQuestIDs", + &Script_GetAllCompletedQuestIDs, &kGetAllCompletedQuestIDs); +} + +static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace Quest::Completed