#pragma once // GameClient — the channel/game-server side of the connection on top of // NetStream: // connect -> (base KX handshake) -> GC_PHASE(PHASE_LOGIN) // -> send CG_LOGIN2{name, login_key} // -> GC_LOGIN_SUCCESS3{char list} | GC_LOGIN_FAILURE{reason} // -> GC_PHASE(PHASE_SELECT) ... select_character(i) -> CG_CHARACTER_SELECT // -> GC_PHASE(PHASE_LOADING) -> GC_PHASE(PHASE_GAME) // // Game-phase packets (spawn/move/etc) are not decoded yet — on_packet keeps the // connection alive (PING is handled by the base) and records unknown headers so // they can be reversed against a live capture. #include "entity_store.h" #include "net_stream.h" #include #include #include #include #include #include #include namespace mtnet { class GameClient : public NetStream { public: struct CharSlot { int index = -1; uint32_t id = 0; std::string name; int job = 0, level = 0; int32_t x = 0, y = 0; uint32_t guild_id = 0; std::string guild_name; uint32_t play_minutes = 0; int st = 0, ht = 0, dx = 0, iq = 0; int main_part = 0, hair_part = 0; }; static void fill_slot_stats(CharSlot &c, const SimplePlayerInfo &s) { c.play_minutes = s.play_minutes; c.st = s.st; c.ht = s.ht; c.dx = s.dx; c.iq = s.iq; c.main_part = s.main_part; c.hair_part = s.hair_part; } // guild-mark side connection auth (from GC_LOGIN_SUCCESS3/4). struct MarkUpdate { uint32_t guild_id = 0; uint16_t img_idx = 0; }; GameClient(std::string name, uint32_t login_key) : m_name(std::move(name)), m_login_key(login_key) { m_trace = std::getenv("MT_NET_TRACE") != nullptr; } void set_trace(bool on) { m_trace = on; } // hex-dump the first 3 of each of these headers (calibration aid). void dump_header(uint16_t h) { m_dump_mask.insert(h); } // auto-send CG_ENTERGAME when GC_PHASE(PHASE_LOADING) arrives (default on). void set_auto_enter_game(bool on) { m_auto_enter_game = on; } uint8_t phase() const { return m_phase; } bool login_sent() const { return m_login_sent; } bool char_list_ready() const { return m_char_list_ready; } int slot_count() const { return m_slot_count; } const std::vector &chars() const { return m_chars; } bool failed() const { return m_failed; } const std::string &fail_reason() const { return m_fail_reason; } bool in_game() const { return m_phase == PHASE_GAME; } uint16_t last_unknown_header() const { return m_last_unknown; } // guild-mark auth: valid after the char list arrives. uint32_t mark_handle() const { return m_mark_handle; } uint32_t mark_random_key() const { return m_mark_random_key; } // GC_MARK_UPDATE pushes on the main connection (guild mark image changed). std::vector drain_mark_updates() { auto v = std::move(m_mark_updates); m_mark_updates.clear(); return v; } // The networked world. Feed set_now()/tick() from the frame loop; poll // drain_changes()/drain_chat() to mirror into the scene. EntityStore &world() { return m_world; } const EntityStore &world() const { return m_world; } bool select_character(int index) { if (index < 0 || index > 255) { return false; } CGCharacterSelect p{}; p.header = CG_CHARACTER_SELECT; p.length = sizeof(p); p.player_index = static_cast(index); return send_packet(&p, sizeof(p)); } // CG_CHARACTER_CREATE — mirrors CPythonNetworkStream::SendCreateCharacterPacket. // shape = face/hair shape index; con/intel/str/dex = the distributed stat points. bool create_character(int slot, const std::string &name, int job, int shape, int con, int intel, int str, int dex) { if (slot < 0 || slot >= PLAYER_PER_ACCOUNT4) { return false; } CGCreateCharacter p{}; p.header = CG_CHARACTER_CREATE; p.length = sizeof(p); p.index = static_cast(slot); std::strncpy(p.name, name.c_str(), CHARACTER_NAME_MAX_LEN); p.job = static_cast(job); p.shape = static_cast(shape); p.con = static_cast(con); p.intel = static_cast(intel); p.str = static_cast(str); p.dex = static_cast(dex); return send_packet(&p, sizeof(p)); } // CG_CHARACTER_DELETE — mirrors SendDestroyCharacterPacket. private_code is the // account's social-id / delete code (server rejects with WRONG_SOCIAL_ID). bool delete_character(int slot, const std::string &private_code) { if (slot < 0 || slot >= PLAYER_PER_ACCOUNT4) { return false; } CGDeleteCharacter p{}; p.header = CG_CHARACTER_DELETE; p.length = sizeof(p); p.index = static_cast(slot); std::strncpy(p.private_code, private_code.c_str(), PRIVATE_CODE_LENGTH - 1); return send_packet(&p, sizeof(p)); } // CG_CHANGE_NAME — rename a character slot using the server-side rename card. // Reject invalid UTF-8 byte lengths instead of silently truncating the fixed field. bool change_name(int slot, const std::string &name) { if (slot < 0 || slot >= PLAYER_PER_ACCOUNT4 || name.empty() || name.size() > CHARACTER_NAME_MAX_LEN) { return false; } CGChangeName p{}; p.header = CG_CHANGE_NAME; p.length = sizeof(p); p.index = static_cast(slot); std::memcpy(p.name, name.data(), name.size()); return send_packet(&p, sizeof(p)); } struct CharEvent { enum Kind { CreateOk, CreateFail, DeleteOk, DeleteFail } kind; int slot; // valid for CreateOk / DeleteOk int fail_type; // valid for CreateFail }; struct NameEvent { uint32_t pid; std::string name; }; std::vector drain_char_events() { auto v = std::move(m_char_events); m_char_events.clear(); return v; } const std::vector &peek_char_events() const { return m_char_events; } std::vector drain_name_events() { auto v = std::move(m_name_events); m_name_events.clear(); return v; } int drain_guild_make_requests() { int count = m_guild_make_requests; m_guild_make_requests = 0; return count; } // GC_EMPIRE payload (0 = server wants an empire choice before character select). uint8_t empire() const { return m_empire; } bool empire_seen() const { return m_empire_seen; } bool send_empire(uint8_t empire_id) { struct { uint16_t header, length; uint8_t empire; } p{CG_EMPIRE, 5, empire_id}; return send_packet(&p, sizeof(p)); } // CG_ENTERGAME — "map loaded, put me in the world" (drives PHASE_LOADING -> PHASE_GAME). bool send_enter_game() { DynHeader p{CG_ENTERGAME, sizeof(DynHeader)}; return send_packet(&p, sizeof(p)); } // CG_CLIENT_VERSION — auto-sent on GC_MAIN_CHARACTER; the fork uses a fixed // timestamp and any filename. bool send_client_version() { CGClientVersion p{}; p.header = CG_CLIENT_VERSION; p.length = sizeof(p); std::strncpy(p.filename, "metin2.bin", sizeof(p.filename) - 1); std::strncpy(p.timestamp, "1215955205", sizeof(p.timestamp) - 1); return send_packet(&p, sizeof(p)); } // --- outbound game-phase intents (CG_*) --- bool send_move(uint8_t func, uint8_t arg, uint8_t rot, int32_t x, int32_t y, uint32_t time) { CGMove p{}; p.header = CG_MOVE; p.length = sizeof(p); p.func = func; p.arg = arg; p.rot = rot; p.x = x; p.y = y; p.time = time; return send_packet(&p, sizeof(p)); } // CG_CHARACTER_POSITION — update the local character's posture/position enum. bool send_character_position(uint8_t position) { CGCharacterPosition p{CG_CHARACTER_POSITION, sizeof(CGCharacterPosition), position}; return send_packet(&p, sizeof(p)); } // CG_SYNC_POSITION — batch nearby entity positions (the legacy client caps this at 16). bool send_sync_positions(const std::vector &elements) { if (elements.empty() || elements.size() > 16) { return false; } const size_t total = sizeof(CGSyncPosition) + elements.size() * sizeof(CGSyncPositionElement); if (total > 0xffffu) { return false; } std::vector packet(total); CGSyncPosition head{CG_SYNC_POSITION, static_cast(total)}; std::memcpy(packet.data(), &head, sizeof(head)); std::memcpy(packet.data() + sizeof(head), elements.data(), elements.size() * sizeof(CGSyncPositionElement)); return send_packet(packet.data(), packet.size()); } bool send_warp() { CGWarp p{CG_WARP, sizeof(CGWarp)}; return send_packet(&p, sizeof(p)); } bool send_fishing(uint8_t dir) { CGFishing p{CG_FISHING, sizeof(CGFishing), dir}; return send_packet(&p, sizeof(p)); } bool send_dungeon() { CGDungeon p{CG_DUNGEON, sizeof(CGDungeon)}; return send_packet(&p, sizeof(p)); } bool send_attack(uint8_t type, uint32_t victim_vid) { CGAttack p{}; p.header = CG_ATTACK; p.length = sizeof(p); p.type = type; p.victim_vid = victim_vid; return send_packet(&p, sizeof(p)); } bool send_use_skill(uint32_t vnum, uint32_t target_vid) { CGUseSkill p{CG_USE_SKILL, sizeof(CGUseSkill), vnum, target_vid}; return send_packet(&p, sizeof(p)); } bool send_shoot(uint8_t type) { CGShoot p{CG_SHOOT, sizeof(CGShoot), type}; return send_packet(&p, sizeof(p)); } bool send_fly_targeting(uint32_t target_vid, int32_t x, int32_t y) { CGFlyTargeting p{CG_FLY_TARGETING, sizeof(CGFlyTargeting), target_vid, x, y}; return send_packet(&p, sizeof(p)); } bool send_add_fly_targeting(uint32_t target_vid, int32_t x, int32_t y) { CGFlyTargeting p{CG_ADD_FLY_TARGETING, sizeof(CGFlyTargeting), target_vid, x, y}; return send_packet(&p, sizeof(p)); } bool send_quickslot_add(uint8_t pos, uint8_t type, uint8_t ref) { CGQuickSlotAdd p{CG_QUICKSLOT_ADD, sizeof(CGQuickSlotAdd), pos, {type, ref}}; return send_packet(&p, sizeof(p)); } bool send_quickslot_del(uint8_t pos) { CGQuickSlotDel p{CG_QUICKSLOT_DEL, sizeof(CGQuickSlotDel), pos}; return send_packet(&p, sizeof(p)); } bool send_quickslot_swap(uint8_t pos, uint8_t change_pos) { CGQuickSlotSwap p{CG_QUICKSLOT_SWAP, sizeof(CGQuickSlotSwap), pos, change_pos}; return send_packet(&p, sizeof(p)); } bool send_target(uint32_t vid) { CGTarget p{CG_TARGET, sizeof(CGTarget), vid}; return send_packet(&p, sizeof(p)); } // --- item intents (TItemPos = window_type:u8 + cell:u16) --- bool send_item_move(uint8_t from_win, uint16_t from_cell, uint8_t to_win, uint16_t to_cell, uint8_t num) { CGItemMove p{}; p.header = CG_ITEM_MOVE; p.length = sizeof(p); p.pos = {from_win, from_cell}; p.change_pos = {to_win, to_cell}; p.num = num; return send_packet(&p, sizeof(p)); } bool send_item_use(uint8_t win, uint16_t cell) { CGItemUse p{}; p.header = CG_ITEM_USE; p.length = sizeof(p); p.pos = {win, cell}; return send_packet(&p, sizeof(p)); } bool send_item_drop(uint8_t win, uint16_t cell, uint32_t gold) { CGItemDrop p{}; p.header = CG_ITEM_DROP; p.length = sizeof(p); p.pos = {win, cell}; p.gold = gold; return send_packet(&p, sizeof(p)); } bool send_item_drop2(uint8_t win, uint16_t cell, uint32_t gold, uint8_t count) { CGItemDrop2 p{CG_ITEM_DROP2, sizeof(CGItemDrop2), {win, cell}, gold, count}; return send_packet(&p, sizeof(p)); } bool send_item_use_to_item(uint8_t src_win, uint16_t src_cell, uint8_t dst_win, uint16_t dst_cell) { CGItemUseToItem p{CG_ITEM_USE_TO_ITEM, sizeof(CGItemUseToItem), {src_win, src_cell}, {dst_win, dst_cell}}; return send_packet(&p, sizeof(p)); } bool send_give_item(uint32_t target_vid, uint8_t win, uint16_t cell, uint8_t count) { CGGiveItem p{CG_ITEM_GIVE, sizeof(CGGiveItem), target_vid, {win, cell}, count}; return send_packet(&p, sizeof(p)); } bool send_item_pickup(uint32_t vid) { CGItemPickUp p{CG_ITEM_PICKUP, sizeof(CGItemPickUp), vid}; return send_packet(&p, sizeof(p)); } // --- quest / NPC intents --- bool send_on_click(uint32_t vid) { CGOnClick p{CG_ON_CLICK, sizeof(CGOnClick), vid}; return send_packet(&p, sizeof(p)); } bool send_script_answer(uint8_t answer) { CGScriptAnswer p{CG_SCRIPT_ANSWER, sizeof(CGScriptAnswer), answer}; return send_packet(&p, sizeof(p)); } bool send_script_button(uint32_t idx) { CGScriptButton p{CG_SCRIPT_BUTTON, sizeof(CGScriptButton), idx}; return send_packet(&p, sizeof(p)); } bool send_script_select_item(uint32_t selection) { CGScriptSelectItem p{CG_SCRIPT_SELECT_ITEM, sizeof(CGScriptSelectItem), selection}; return send_packet(&p, sizeof(p)); } bool send_quest_input(const std::string &s) { CGQuestInputString p{}; p.header = CG_QUEST_INPUT_STRING; p.length = sizeof(p); std::strncpy(p.str, s.c_str(), sizeof(p.str) - 1); return send_packet(&p, sizeof(p)); } bool send_quest_confirm(bool yes, uint32_t request_pid) { CGQuestConfirm p{CG_QUEST_CONFIRM, sizeof(CGQuestConfirm), (uint8_t)(yes ? 1 : 0), request_pid}; return send_packet(&p, sizeof(p)); } bool send_quest_cancel() { CGQuestCancel p{CG_QUEST_CANCEL, sizeof(CGQuestCancel)}; return send_packet(&p, sizeof(p)); } // --- P8 party intents --- bool send_party_invite(uint32_t vid) { CGPartyInvite p{CG_PARTY_INVITE, sizeof(CGPartyInvite), vid}; return send_packet(&p, sizeof(p)); } bool send_party_invite_answer(uint32_t leader_pid, bool accept) { CGPartyInviteAnswer p{CG_PARTY_INVITE_ANSWER, sizeof(CGPartyInviteAnswer), leader_pid, (uint8_t)(accept ? 1 : 0)}; return send_packet(&p, sizeof(p)); } bool send_party_remove(uint32_t pid) { CGPartyRemove p{CG_PARTY_REMOVE, sizeof(CGPartyRemove), pid}; return send_packet(&p, sizeof(p)); } bool send_party_use_skill(uint8_t skill_index, uint32_t target_vid) { CGPartyUseSkill p{CG_PARTY_USE_SKILL, sizeof(CGPartyUseSkill), skill_index, target_vid}; return send_packet(&p, sizeof(p)); } bool send_party_parameter(uint8_t mode) { CGPartyParameter p{CG_PARTY_PARAMETER, sizeof(CGPartyParameter), mode}; return send_packet(&p, sizeof(p)); } bool send_party_set_state(uint32_t pid, uint8_t role, uint8_t on) { CGPartySetState p{CG_PARTY_SET_STATE, sizeof(CGPartySetState), pid, role, on}; return send_packet(&p, sizeof(p)); } // --- P8 messenger intents (CG_MESSENGER = [head][sub][u8 len][name]) --- bool send_friend_add(const std::string &name) { std::vector buf(sizeof(CGSubHeader) + 1 + name.size()); CGSubHeader head{CG_MESSENGER, (uint16_t)buf.size(), MESSENGER_CG_ADD_BY_NAME}; std::memcpy(buf.data(), &head, sizeof(head)); buf[sizeof(head)] = (uint8_t)name.size(); std::memcpy(buf.data() + sizeof(head) + 1, name.data(), name.size()); return send_packet(buf.data(), buf.size()); } bool send_friend_remove(const std::string &name) { std::vector buf(sizeof(CGSubHeader) + 1 + name.size()); CGSubHeader head{CG_MESSENGER, (uint16_t)buf.size(), MESSENGER_CG_REMOVE}; std::memcpy(buf.data(), &head, sizeof(head)); buf[sizeof(head)] = (uint8_t)name.size(); std::memcpy(buf.data() + sizeof(head) + 1, name.data(), name.size()); return send_packet(buf.data(), buf.size()); } // --- P8 NPC shop intents --- bool send_shop_close() { CGSubHeader p{CG_SHOP, sizeof(CGSubHeader), SHOP_CG_END}; return send_packet(&p, sizeof(p)); } // SHOP_CG_BUY body = [head][u8 count][u8 pos] bool send_shop_buy(uint8_t pos, uint8_t count) { uint8_t buf[sizeof(CGSubHeader) + 2]; CGSubHeader head{CG_SHOP, sizeof(buf), SHOP_CG_BUY}; std::memcpy(buf, &head, sizeof(head)); buf[sizeof(head)] = count; buf[sizeof(head) + 1] = pos; return send_packet(buf, sizeof(buf)); } // SHOP_CG_SELL2 body = [head][u8 inv_cell][u8 count] bool send_shop_sell(uint8_t inv_cell, uint8_t count) { uint8_t buf[sizeof(CGSubHeader) + 2]; CGSubHeader head{CG_SHOP, sizeof(buf), SHOP_CG_SELL2}; std::memcpy(buf, &head, sizeof(head)); buf[sizeof(head)] = inv_cell; buf[sizeof(head) + 1] = count; return send_packet(buf, sizeof(buf)); } // --- P8 exchange intents --- bool send_exchange_start(uint32_t vid) { CGExchange p{}; p.header = CG_EXCHANGE; p.length = sizeof(p); p.subheader = EXCHANGE_SUB_START; p.arg1 = vid; return send_packet(&p, sizeof(p)); } bool send_exchange_item_add(uint8_t inv_win, uint16_t inv_cell, uint8_t display_pos) { CGExchange p{}; p.header = CG_EXCHANGE; p.length = sizeof(p); p.subheader = EXCHANGE_SUB_ITEM_ADD; p.arg2 = display_pos; p.pos = {inv_win, inv_cell}; return send_packet(&p, sizeof(p)); } bool send_exchange_gold(uint32_t gold) { CGExchange p{}; p.header = CG_EXCHANGE; p.length = sizeof(p); p.subheader = EXCHANGE_SUB_ELK_ADD; p.arg1 = gold; return send_packet(&p, sizeof(p)); } bool send_exchange_accept() { CGExchange p{}; p.header = CG_EXCHANGE; p.length = sizeof(p); p.subheader = EXCHANGE_SUB_ACCEPT; return send_packet(&p, sizeof(p)); } bool send_exchange_cancel() { CGExchange p{}; p.header = CG_EXCHANGE; p.length = sizeof(p); p.subheader = EXCHANGE_SUB_CANCEL; return send_packet(&p, sizeof(p)); } // --- P8 safebox intents --- bool send_safebox_checkin(uint8_t safe_pos, uint8_t inv_win, uint16_t inv_cell) { CGSafeboxCheckin p{}; p.header = CG_SAFEBOX_CHECKIN; p.length = sizeof(p); p.safe_pos = safe_pos; p.inv_pos = {inv_win, inv_cell}; return send_packet(&p, sizeof(p)); } bool send_safebox_checkout(uint8_t safe_pos, uint8_t inv_win, uint16_t inv_cell) { CGSafeboxCheckout p{}; p.header = CG_SAFEBOX_CHECKOUT; p.length = sizeof(p); p.safe_pos = safe_pos; p.inv_pos = {inv_win, inv_cell}; return send_packet(&p, sizeof(p)); } bool send_safebox_move(uint16_t from_cell, uint16_t to_cell, uint8_t count) { CGItemMove p{}; p.header = CG_SAFEBOX_ITEM_MOVE; p.length = sizeof(p); p.pos = {WINDOW_INVENTORY, from_cell}; p.change_pos = {WINDOW_INVENTORY, to_cell}; p.num = count; return send_packet(&p, sizeof(p)); } // --- item-mall (창고몰) intent: pull mall slot -> inventory cell --- bool send_mall_checkout(uint8_t mall_pos, uint8_t inv_win, uint16_t inv_cell) { CGMallCheckout p{}; p.header = CG_MALL_CHECKOUT; p.length = sizeof(p); p.mall_pos = mall_pos; p.inv_pos = {inv_win, inv_cell}; return send_packet(&p, sizeof(p)); } // --- private (PC) shop: CG_MYSHOP head + N MyShopItem --- bool send_open_private_shop(const std::string &sign, const std::vector &items) { size_t n = items.size(); if (n > PRIVATE_SHOP_ITEM_MAX_NUM) { n = PRIVATE_SHOP_ITEM_MAX_NUM; } std::vector buf(sizeof(CGMyShopHead) + n * sizeof(MyShopItem)); CGMyShopHead head{}; head.header = CG_MYSHOP; head.length = static_cast(buf.size()); std::strncpy(head.sign, sign.c_str(), SHOP_SIGN_MAX_LEN); head.count = static_cast(n); std::memcpy(buf.data(), &head, sizeof(head)); for (size_t i = 0; i < n; ++i) { std::memcpy(buf.data() + sizeof(head) + i * sizeof(MyShopItem), &items[i], sizeof(MyShopItem)); } return send_packet(buf.data(), buf.size()); } // closing your own private shop reuses SHOP_CG_END. bool send_close_private_shop() { return send_shop_close(); } // --- cube (제작) — server side is GC_CHAT/COMMAND text; client asks via /cube ... --- bool send_cube_make(int result_idx) { return send_chat(CHAT_TYPE_COMMAND, "/cube make " + std::to_string(result_idx)); } bool send_cube_material_info(int start_idx, int count) { return send_chat(CHAT_TYPE_COMMAND, "/cube mInfo " + std::to_string(start_idx) + " " + std::to_string(count)); } bool send_cube_result_list(uint32_t npc_vnum) { return send_chat(CHAT_TYPE_COMMAND, "/cube rList " + std::to_string(npc_vnum)); } // --- guild / refine intents --- bool send_refine(uint8_t pos, uint8_t type) { CGRefine p{CG_REFINE, sizeof(CGRefine), pos, type}; return send_packet(&p, sizeof(p)); } // CG_DRAGON_SOUL_REFINE — sub_type = the mode (DS_SUB_DO_UPGRADE/IMPROVEMENT/REFINE); // grid[0] = the dragon soul, grid[1..] = materials. Unused entries stay {0,0}. bool send_ds_refine(uint8_t sub_type, const ItemPos grid[DS_REFINE_WINDOW_MAX_NUM]) { CGDragonSoulRefine p{}; p.header = CG_DRAGON_SOUL_REFINE; p.length = sizeof(p); p.sub_type = sub_type; std::memcpy(p.grid, grid, sizeof(ItemPos) * DS_REFINE_WINDOW_MAX_NUM); return send_packet(&p, sizeof(p)); } bool send_guild_sub(uint8_t subheader) { // bare sub-header (e.g. request list/info) CGGuild p{CG_GUILD, sizeof(CGGuild), subheader}; return send_packet(&p, sizeof(p)); } bool send_guild_answer_make(const std::string &guild_name) { CGAnswerMakeGuild p{}; p.header = CG_ANSWER_MAKE_GUILD; p.length = sizeof(p); std::strncpy(p.guild_name, guild_name.c_str(), sizeof(p.guild_name) - 1); return send_packet(&p, sizeof(p)); } // CG_GUILD sub-header + a u32 payload (add/remove member by vid, offer amount, ...). bool send_guild_sub_u32(uint8_t subheader, uint32_t arg) { uint8_t buf[sizeof(CGGuild) + 4]; CGGuild head{CG_GUILD, (uint16_t)sizeof(buf), subheader}; std::memcpy(buf, &head, sizeof(head)); std::memcpy(buf + sizeof(head), &arg, 4); return send_packet(buf, sizeof(buf)); } // GUILD_CG_USE_SKILL: sub-header + {u32 skill_vnum, u32 target_vid}. bool send_guild_use_skill(uint32_t skill_vnum, uint32_t target_vid) { uint8_t buf[sizeof(CGGuild) + 8]; CGGuild head{CG_GUILD, (uint16_t)sizeof(buf), GUILD_CG_USE_SKILL}; std::memcpy(buf, &head, sizeof(head)); std::memcpy(buf + sizeof(head), &skill_vnum, 4); std::memcpy(buf + sizeof(head) + 4, &target_vid, 4); return send_packet(buf, sizeof(buf)); } // CG_CHAT is variable: [head][type][utf8 text][NUL] bool send_chat(uint8_t type, const std::string &text) { std::vector buf(sizeof(CGChat) + text.size() + 1); CGChat head{}; head.header = CG_CHAT; head.length = static_cast(buf.size()); head.type = type; std::memcpy(buf.data(), &head, sizeof(head)); std::memcpy(buf.data() + sizeof(head), text.data(), text.size()); buf[buf.size() - 1] = 0; return send_packet(buf.data(), buf.size()); } // CG_WHISPER is variable: [head][name[65]][utf8 text][NUL] bool send_whisper(const std::string &to, const std::string &text) { std::vector buf(sizeof(CGWhisper) + text.size() + 1); CGWhisper head{}; head.header = CG_WHISPER; head.length = static_cast(buf.size()); std::strncpy(head.to_name, to.c_str(), sizeof(head.to_name) - 1); std::memcpy(buf.data(), &head, sizeof(head)); std::memcpy(buf.data() + sizeof(head), text.data(), text.size()); buf[buf.size() - 1] = 0; return send_packet(buf.data(), buf.size()); } protected: void on_phase(uint8_t phase) override { if (m_trace) { std::fprintf(stderr, "[gc] GC_PHASE -> %d\n", (int)phase); } m_phase = phase; if (phase == PHASE_LOADING && m_auto_enter_game && !m_enter_game_sent) { send_enter_game(); m_enter_game_sent = true; } if (phase == PHASE_LOGIN && !m_login_sent) { CGLogin2 p{}; p.header = CG_LOGIN2; p.length = sizeof(p); std::strncpy(p.name, m_name.c_str(), sizeof(p.name) - 1); p.login_key = m_login_key; send_packet(&p, sizeof(p)); m_login_sent = true; } } bool on_packet(uint16_t header, uint16_t len) override { if (m_trace) { std::fprintf(stderr, "[gc] recv header=0x%04X len=%u phase=%d\n", header, len, (int)m_phase); } // calibration: hex-dump the first few of each interesting packet, whole. if (m_dump_mask.count(header) && m_dump_seen[header]++ < 3) { uint8_t buf[512]; uint16_t n = len < sizeof(buf) ? len : (uint16_t)sizeof(buf); if (peek_bytes(buf, n)) { std::fprintf(stderr, "[dump 0x%04X len=%u]", header, len); for (uint16_t i = 0; i < n; ++i) { std::fprintf(stderr, " %02x", buf[i]); } std::fprintf(stderr, "\n"); } } switch (header) { case GC_LOGIN_SUCCESS3: { GCLoginSuccess3 p{}; if (len != sizeof(p) || !recv_bytes(&p, sizeof(p))) { // length mismatch: consume and flag so the layout can be fixed consume(len); m_fail_reason = "LOGIN_SUCCESS3 size " + std::to_string(len) + " != " + std::to_string(sizeof(p)); m_char_list_ready = true; return true; } m_chars.clear(); for (int i = 0; i < PLAYER_PER_ACCOUNT3; ++i) { const SimplePlayerInfo &s = p.players[i]; if (s.id == 0 && s.name[0] == '\0') { continue; // empty slot } CharSlot c; c.index = i; c.id = s.id; c.name.assign(s.name, strnlen(s.name, sizeof(s.name))); c.job = s.job; c.level = s.level; c.x = s.x; c.y = s.y; c.guild_id = p.guild_id[i]; c.guild_name.assign(p.guild_name[i], strnlen(p.guild_name[i], sizeof(p.guild_name[i]))); fill_slot_stats(c, s); m_chars.push_back(std::move(c)); } m_mark_handle = p.handle; m_mark_random_key = p.random_key; m_slot_count = PLAYER_PER_ACCOUNT3; m_char_list_ready = true; return true; } case GC_LOGIN_SUCCESS4: { GCLoginSuccess4 p{}; if (len != sizeof(p) || !recv_bytes(&p, sizeof(p))) { consume(len); m_fail_reason = "LOGIN_SUCCESS4 size " + std::to_string(len) + " != " + std::to_string(sizeof(p)); m_char_list_ready = true; return true; } m_chars.clear(); for (int i = 0; i < PLAYER_PER_ACCOUNT4; ++i) { const SimplePlayerInfo &s = p.players[i]; if (s.id == 0 && s.name[0] == '\0') { continue; } CharSlot c; c.index = i; c.id = s.id; c.name.assign(s.name, strnlen(s.name, sizeof(s.name))); c.job = s.job; c.level = s.level; c.x = s.x; c.y = s.y; c.guild_id = p.guild_id[i]; c.guild_name.assign(p.guild_name[i], strnlen(p.guild_name[i], sizeof(p.guild_name[i]))); fill_slot_stats(c, s); m_chars.push_back(std::move(c)); } m_mark_handle = p.handle; m_mark_random_key = p.random_key; m_slot_count = PLAYER_PER_ACCOUNT4; m_char_list_ready = true; return true; } case GC_EMPIRE: { uint8_t tmp[16]; if (len <= sizeof(tmp) && recv_bytes(tmp, len)) { if (len >= 5) { m_empire = tmp[4]; } m_empire_seen = true; } else { consume(len); } return true; } case GC_CHANGE_NAME: { GCChangeName p{}; if (len == sizeof(p) && recv_bytes(&p, sizeof(p))) { std::string name(p.name, strnlen(p.name, sizeof(p.name))); for (auto &slot : m_chars) { if (slot.id == p.pid) { slot.name = name; } } m_name_events.push_back({p.pid, std::move(name)}); } else { consume(len); } return true; } case GC_REQUEST_MAKE_GUILD: { if (len == sizeof(DynHeader)) { DynHeader p{}; if (recv_bytes(&p, sizeof(p))) { ++m_guild_make_requests; return true; } } consume(len); return true; } case GC_LOGIN_FAILURE: { char buf[128] = {0}; uint16_t body = len > (uint16_t)sizeof(DynHeader) ? len - (uint16_t)sizeof(DynHeader) : 0; uint8_t tmp[256]; if (len <= sizeof(tmp)) { recv_bytes(tmp, len); uint16_t n = body < sizeof(buf) - 1 ? body : (uint16_t)(sizeof(buf) - 1); std::memcpy(buf, tmp + sizeof(DynHeader), n); } else { drop_recv(); } m_failed = true; m_fail_reason = std::string("LOGIN_FAILURE ") + buf; return true; } case GC_MARK_UPDATE: { GCMarkUpdate p{}; if (len == sizeof(p) && recv_bytes(&p, sizeof(p))) { m_mark_updates.push_back({p.guild_id, p.img_idx}); } else { consume(len); } return true; } case GC_PLAYER_CREATE_SUCCESS: { GCPlayerCreateSuccess p{}; if (len == sizeof(p) && recv_bytes(&p, sizeof(p))) { int slot = p.slot; if (slot >= 0 && slot < PLAYER_PER_ACCOUNT4) { // patch the local slot list (server does not re-send it) CharSlot c; c.index = slot; c.id = p.player.id; c.name.assign(p.player.name, strnlen(p.player.name, sizeof(p.player.name))); c.job = p.player.job; c.level = p.player.level; c.x = p.player.x; c.y = p.player.y; fill_slot_stats(c, p.player); replace_slot(std::move(c)); m_char_events.push_back({CharEvent::CreateOk, slot, 0}); } } else { consume(len); } return true; } case GC_PLAYER_CREATE_FAILURE: { GCCreateFailure p{}; if (len == sizeof(p) && recv_bytes(&p, sizeof(p))) { m_char_events.push_back({CharEvent::CreateFail, -1, p.type}); } else { consume(len); } return true; } case GC_PLAYER_DELETE_SUCCESS: { GCDeleteSuccess p{}; if (len == sizeof(p) && recv_bytes(&p, sizeof(p))) { int slot = p.account_index; clear_slot(slot); m_char_events.push_back({CharEvent::DeleteOk, slot, 0}); } else { consume(len); } return true; } case GC_PLAYER_DELETE_WRONG_SOCIAL_ID: { consume(len); m_char_events.push_back({CharEvent::DeleteFail, -1, 0}); return true; } // Game-phase packets -> the networked world model. case GC_MAIN_CHARACTER: case GC_CHARACTER_ADD: case GC_CHARACTER_ADD2: case GC_CHAR_ADD_INFO: case GC_CHARACTER_UPDATE: case GC_CHARACTER_DEL: case GC_MOVE: case GC_CHAT: case GC_WHISPER: case GC_PLAYER_POINTS: case GC_CHARACTER_POSITION: case GC_PLAYER_POINT_CHANGE: case GC_STUN: case GC_DEAD: case GC_CHANGE_SPEED: case GC_WALK_MODE: case GC_MOTION: case GC_DIG_MOTION: case GC_DAMAGE_INFO: case GC_TARGET_INFO: case GC_AFFECT_ADD: case GC_AFFECT_REMOVE: case GC_SPECIAL_EFFECT: case GC_SPECIFIC_EFFECT: case GC_SKILL_LEVEL: case GC_SKILL_LEVEL_NEW: case GC_SKILL_COOLTIME_END: case GC_CHANGE_SKILL_GROUP: case GC_VIEW_EQUIP: case GC_QUICKSLOT_ADD: case GC_QUICKSLOT_DEL: case GC_QUICKSLOT_SWAP: case GC_FLY_TARGETING: case GC_ADD_FLY_TARGETING: case GC_CREATE_FLY: case GC_SYNC_POSITION: case GC_PVP: case GC_DUEL_START: case GC_SCRIPT: case GC_QUEST_CONFIRM: case GC_QUEST_INFO: case GC_ITEM_SET: case GC_ITEM_DEL: case GC_ITEM_UPDATE: case GC_ITEM_USE: case GC_ITEM_GROUND_ADD: case GC_ITEM_GROUND_DEL: case GC_ITEM_OWNERSHIP: case GC_ITEM_GET: case GC_PARTY_INVITE: case GC_PARTY_ADD: case GC_PARTY_UPDATE: case GC_PARTY_REMOVE: case GC_PARTY_LINK: case GC_PARTY_UNLINK: case GC_PARTY_PARAMETER: case GC_MESSENGER: case GC_LOVER_INFO: case GC_LOVE_POINT_UPDATE: case GC_SHOP: case GC_EXCHANGE: case GC_SAFEBOX_SET: case GC_SAFEBOX_DEL: case GC_SAFEBOX_SIZE: case GC_SAFEBOX_MONEY_CHANGE: case GC_SAFEBOX_WRONG_PASSWORD: case GC_MALL_OPEN: case GC_MALL_SET: case GC_MALL_DEL: case GC_GUILD: case GC_REFINE_INFO: case GC_REFINE_INFO_NEW: case GC_DRAGON_SOUL_REFINE: case GC_WARP: case GC_TIME: case GC_CHANNEL: case GC_FISHING: case GC_DUNGEON: case GC_LAND_LIST: case GC_OBSERVER_ADD: case GC_OBSERVER_REMOVE: case GC_OBSERVER_MOVE: case GC_NPC_POSITION: case GC_TARGET_CREATE: case GC_TARGET_UPDATE: case GC_TARGET_DELETE: case GC_MOUNT: { uint8_t tmp[4096]; if (len > sizeof(tmp) || !recv_bytes(tmp, len)) { drop_recv(); return true; } m_world.apply(header, tmp, len); // The server expects a version report right after the main char // arrives; skipping it gets us dropped before PHASE_GAME. if (header == GC_MAIN_CHARACTER && !m_version_sent) { send_client_version(); m_version_sent = true; } return true; } default: m_last_unknown = header; consume(len); return true; } } void on_disconnect() override { m_failed = m_failed || !m_char_list_ready; } private: void consume(uint16_t len) { uint8_t tmp[2048]; if (len <= sizeof(tmp)) { recv_bytes(tmp, len); } else { drop_recv(); } } // Local char-slot list maintenance after create/delete (server patches, not re-sends). void replace_slot(CharSlot &&c) { for (auto &s : m_chars) { if (s.index == c.index) { s = std::move(c); return; } } m_chars.push_back(std::move(c)); } void clear_slot(int slot) { for (auto it = m_chars.begin(); it != m_chars.end(); ++it) { if (it->index == slot) { m_chars.erase(it); return; } } } std::string m_name; uint32_t m_login_key; uint8_t m_phase = 0xFF; bool m_login_sent = false; bool m_char_list_ready = false; int m_slot_count = PLAYER_PER_ACCOUNT4; bool m_failed = false; std::string m_fail_reason; std::vector m_chars; std::vector m_char_events; std::vector m_name_events; int m_guild_make_requests = 0; uint16_t m_last_unknown = 0; bool m_trace = false; std::set m_dump_mask; std::unordered_map m_dump_seen; uint8_t m_empire = 0; bool m_empire_seen = false; bool m_auto_enter_game = true; bool m_enter_game_sent = false; bool m_version_sent = false; uint32_t m_mark_handle = 0; uint32_t m_mark_random_key = 0; std::vector m_mark_updates; EntityStore m_world; }; } // namespace mtnet