Initialize shared Metin2 SDK with rendering optimizations and tests

This commit is contained in:
shen
2026-10-11 17:52:55 -07:00
commit 86759bb726
147 changed files with 27272 additions and 0 deletions
+26
View File
@@ -0,0 +1,26 @@
cmake_minimum_required(VERSION 3.20)
project(network LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_library(network STATIC
src/connection_phase.cpp
src/cipher.cpp
src/packet.cpp
src/network_client.cpp
)
target_include_directories(network PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
add_library(network::network ALIAS network)
option(NETWORK_BUILD_TESTS "Build network SDK tests" ON)
if(NETWORK_BUILD_TESTS)
add_executable(network_test tests/network_test.cpp)
target_link_libraries(network_test PRIVATE network)
add_test(NAME network_test COMMAND network_test)
endif()
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include "types.h"
#include <cstdint>
#include <vector>
#include <array>
#include <span>
namespace metin2::network {
using TeaKey = std::array<uint32_t, 4>;
class TeaCipher {
public:
TeaCipher() = default;
explicit TeaCipher(const TeaKey& key);
void SetKey(const TeaKey& key);
const TeaKey& GetKey() const { return m_key; }
void EncryptBlock(uint32_t& y, uint32_t& z) const;
void DecryptBlock(uint32_t& y, uint32_t& z) const;
std::vector<uint8_t> Encrypt(std::span<const uint8_t> input) const;
std::vector<uint8_t> Decrypt(std::span<const uint8_t> input) const;
private:
TeaKey m_key{0, 0, 0, 0};
};
class RollingXorCipher {
public:
RollingXorCipher() = default;
explicit RollingXorCipher(uint32_t seed_key);
void Reset(uint32_t seed_key);
void Process(uint8_t* data, size_t size);
private:
uint32_t m_key = 0;
uint32_t m_state = 0;
};
class CipherContext {
public:
CipherContext() = default;
void SetEnabled(bool enabled) { m_enabled = enabled; }
bool IsEnabled() const { return m_enabled; }
void InitializeKeys(const TeaKey& tea_key, uint32_t xor_seed);
void EncryptSend(uint8_t* data, size_t size);
void DecryptRecv(uint8_t* data, size_t size);
TeaCipher& GetSendTea() { return m_send_tea; }
TeaCipher& GetRecvTea() { return m_recv_tea; }
private:
bool m_enabled = false;
TeaCipher m_send_tea;
TeaCipher m_recv_tea;
RollingXorCipher m_send_xor;
RollingXorCipher m_recv_xor;
};
} // namespace metin2::network
@@ -0,0 +1,32 @@
#pragma once
#include "types.h"
#include <functional>
namespace metin2::network {
class PhaseStateMachine {
public:
using PhaseChangeCallback = std::function<void(ConnectionPhase old_phase, ConnectionPhase new_phase)>;
PhaseStateMachine();
explicit PhaseStateMachine(ConnectionPhase initial_phase);
ConnectionPhase GetCurrentPhase() const { return m_current_phase; }
const char* GetPhaseName() const { return ToString(m_current_phase); }
bool CanTransitionTo(ConnectionPhase target_phase) const;
bool TransitionTo(ConnectionPhase target_phase);
void ForcePhase(ConnectionPhase phase);
void SetPhaseChangeCallback(PhaseChangeCallback cb) { m_callback = std::move(cb); }
bool IsConnected() const { return m_current_phase != ConnectionPhase::Disconnected; }
bool IsInGame() const { return m_current_phase == ConnectionPhase::InGame; }
private:
ConnectionPhase m_current_phase = ConnectionPhase::Disconnected;
PhaseChangeCallback m_callback;
};
} // namespace metin2::network
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "types.h"
#include "connection_phase.h"
#include "cipher.h"
#include "packet.h"
#include "network_client.h"
+87
View File
@@ -0,0 +1,87 @@
#pragma once
#include "types.h"
#include "connection_phase.h"
#include "cipher.h"
#include "packet.h"
#include <functional>
#include <string>
namespace metin2::network {
class NetworkClient {
public:
using HandshakeCallback = std::function<void(uint32_t server_time)>;
using AuthResultCallback = std::function<void(bool success, uint32_t error_code, const std::string& message)>;
using CharacterListCallback = std::function<void(const std::vector<CharacterSummary>& characters)>;
using GameStartCallback = std::function<void(const PlayerInfo& player)>;
using ChatCallback = std::function<void(uint32_t sender_id, uint8_t chat_type, const std::string& text)>;
using ActorMoveCallback = std::function<void(uint32_t actor_id, float x, float y, float z, float rot, uint32_t move_type)>;
using GenericPacketCallback = std::function<void(const Packet& packet)>;
NetworkClient();
// Transport Interface (zero socket binding)
void PushReceivedData(const uint8_t* data, size_t size);
std::vector<uint8_t> PopSendData();
bool HasPendingSendData() const { return !m_send_buffer.empty(); }
// Phase and State
ConnectionPhase GetPhase() const { return m_phase_fsm.GetCurrentPhase(); }
const char* GetPhaseName() const { return m_phase_fsm.GetPhaseName(); }
bool SetPhase(ConnectionPhase phase) { return m_phase_fsm.TransitionTo(phase); }
void ForcePhase(ConnectionPhase phase) { m_phase_fsm.ForcePhase(phase); }
bool IsConnected() const { return m_phase_fsm.IsConnected(); }
bool IsInGame() const { return m_phase_fsm.IsInGame(); }
// Cipher Control
CipherContext& GetCipher() { return m_cipher; }
void EnableCipher(bool enable) { m_cipher.SetEnabled(enable); }
void SetEncryptionKeys(const TeaKey& tea_key, uint32_t xor_seed) {
m_cipher.InitializeKeys(tea_key, xor_seed);
}
// Packet Registry
PacketRegistry& GetRegistry() { return m_registry; }
// Callback Setup
void SetPhaseCallback(PhaseStateMachine::PhaseChangeCallback cb) { m_phase_fsm.SetPhaseChangeCallback(std::move(cb)); }
void SetOnHandshake(HandshakeCallback cb) { m_on_handshake = std::move(cb); }
void SetOnAuthResult(AuthResultCallback cb) { m_on_auth_result = std::move(cb); }
void SetOnCharacterList(CharacterListCallback cb) { m_on_character_list = std::move(cb); }
void SetOnGameStart(GameStartCallback cb) { m_on_game_start = std::move(cb); }
void SetOnChat(ChatCallback cb) { m_on_chat = std::move(cb); }
void SetOnActorMove(ActorMoveCallback cb) { m_on_actor_move = std::move(cb); }
void SetOnGenericPacket(GenericPacketCallback cb) { m_on_generic_packet = std::move(cb); }
// High-Level Sending Methods
void SendHandshakeAck(uint32_t client_time);
void SendLogin(const std::string& username, const std::string& password);
void SendSelectCharacter(uint8_t slot_index);
void SendEnterGame();
void SendChat(uint8_t chat_type, const std::string& text);
void SendMove(float x, float y, float z, float rotation, uint32_t move_type);
void SendRawPacket(uint8_t header, const void* payload, size_t payload_size);
void SendDynamicPacket(uint8_t header, const void* payload, size_t payload_size);
void Reset();
private:
void ProcessPacket(const Packet& packet);
PhaseStateMachine m_phase_fsm;
CipherContext m_cipher;
PacketRegistry m_registry;
PacketBuffer m_recv_buffer;
std::vector<uint8_t> m_send_buffer;
HandshakeCallback m_on_handshake;
AuthResultCallback m_on_auth_result;
CharacterListCallback m_on_character_list;
GameStartCallback m_on_game_start;
ChatCallback m_on_chat;
ActorMoveCallback m_on_actor_move;
GenericPacketCallback m_on_generic_packet;
};
} // namespace metin2::network
+65
View File
@@ -0,0 +1,65 @@
#pragma once
#include "types.h"
#include <cstdint>
#include <vector>
#include <unordered_map>
#include <optional>
#include <span>
namespace metin2::network {
struct Packet {
uint8_t header = 0;
std::vector<uint8_t> payload;
size_t TotalSize() const { return 1 + payload.size(); }
};
enum class PacketSizeMode {
Fixed, // Fixed payload size (header + payload)
Dynamic // Header (1 byte) + uint16_t size (2 bytes) + payload
};
struct PacketDescriptor {
uint8_t header = 0;
PacketSizeMode mode = PacketSizeMode::Fixed;
size_t fixed_payload_size = 0;
};
class PacketRegistry {
public:
PacketRegistry();
void Register(uint8_t header, size_t fixed_payload_size);
void RegisterDynamic(uint8_t header);
const PacketDescriptor* Find(uint8_t header) const;
bool HasHeader(uint8_t header) const;
private:
void RegisterDefaultPackets();
std::unordered_map<uint8_t, PacketDescriptor> m_descriptors;
};
class PacketBuffer {
public:
PacketBuffer() = default;
void Append(const uint8_t* data, size_t size);
void Append(const std::vector<uint8_t>& data);
// Extracts all full frames available in buffer according to registry
std::vector<Packet> ExtractPackets(const PacketRegistry& registry);
size_t AvailableBytes() const { return m_buffer.size() - m_read_offset; }
void Clear();
private:
std::vector<uint8_t> m_buffer;
size_t m_read_offset = 0;
void Compact();
};
} // namespace metin2::network
+77
View File
@@ -0,0 +1,77 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <array>
#include <functional>
namespace metin2::network {
enum class ConnectionPhase {
Disconnected = 0,
Handshake,
Auth,
CharacterSelect,
GameLoading,
InGame
};
const char* ToString(ConnectionPhase phase);
enum EPacketHeader : uint8_t {
HEADER_NONE = 0,
HEADER_CG_LOGIN = 1,
HEADER_CG_ATTACK = 2,
HEADER_CG_CHAT = 3,
HEADER_CG_CHARACTER_CREATE = 4,
HEADER_CG_CHARACTER_DELETE = 5,
HEADER_CG_CHARACTER_SELECT = 6,
HEADER_CG_MOVE = 7,
HEADER_CG_SYNC_POSITION = 8,
HEADER_CG_ENTERGAME = 10,
HEADER_CG_ITEM_USE = 11,
HEADER_CG_ITEM_MOVE = 12,
HEADER_CG_PONG = 254,
HEADER_CG_HANDSHAKE = 255,
HEADER_GC_AUTH_SUCCESS = 101,
HEADER_GC_AUTH_FAILURE = 102,
HEADER_GC_CHARACTER_INFO = 103,
HEADER_GC_CHARACTER_LIST = 104,
HEADER_GC_GAME_START = 105,
HEADER_GC_CHAT = 106,
HEADER_GC_ACTOR_ADD = 107,
HEADER_GC_ACTOR_REMOVE = 108,
HEADER_GC_ACTOR_MOVE = 109,
HEADER_GC_ACTOR_ATTACK = 110,
HEADER_GC_ITEM_SET = 111,
HEADER_GC_PING = 253,
HEADER_GC_HANDSHAKE = 255
};
struct CharacterSummary {
uint32_t id = 0;
std::string name;
uint8_t job = 0; // Warrior, Assassin, Sura, Shaman
uint8_t level = 1;
uint32_t play_time = 0;
uint16_t body_armor = 0;
uint16_t weapon = 0;
uint16_t hair = 0;
};
struct PlayerInfo {
uint32_t player_id = 0;
std::string name;
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
float rotation = 0.0f;
uint32_t hp = 100;
uint32_t max_hp = 100;
uint32_t sp = 100;
uint32_t max_sp = 100;
};
} // namespace metin2::network
+133
View File
@@ -0,0 +1,133 @@
#include "network/cipher.h"
#include <cstring>
namespace metin2::network {
TeaCipher::TeaCipher(const TeaKey& key)
: m_key(key) {}
void TeaCipher::SetKey(const TeaKey& key) {
m_key = key;
}
void TeaCipher::EncryptBlock(uint32_t& y, uint32_t& z) const {
uint32_t sum = 0;
constexpr uint32_t delta = 0x9e3779b9u;
for (int i = 0; i < 32; ++i) {
y += ((z << 4 ^ z >> 5) + z) ^ (sum + m_key[sum & 3]);
sum += delta;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + m_key[(sum >> 11) & 3]);
}
}
void TeaCipher::DecryptBlock(uint32_t& y, uint32_t& z) const {
uint32_t sum = 0xc6ef3720u; // 32 * 0x9e3779b9
constexpr uint32_t delta = 0x9e3779b9u;
for (int i = 0; i < 32; ++i) {
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + m_key[(sum >> 11) & 3]);
sum -= delta;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + m_key[sum & 3]);
}
}
static uint32_t ReadU32LE(const uint8_t* p) {
return static_cast<uint32_t>(p[0]) |
(static_cast<uint32_t>(p[1]) << 8) |
(static_cast<uint32_t>(p[2]) << 16) |
(static_cast<uint32_t>(p[3]) << 24);
}
static void WriteU32LE(uint8_t* p, uint32_t v) {
p[0] = static_cast<uint8_t>(v & 0xFF);
p[1] = static_cast<uint8_t>((v >> 8) & 0xFF);
p[2] = static_cast<uint8_t>((v >> 16) & 0xFF);
p[3] = static_cast<uint8_t>((v >> 24) & 0xFF);
}
std::vector<uint8_t> TeaCipher::Encrypt(std::span<const uint8_t> input) const {
size_t padded_size = (input.size() + 7) / 8 * 8;
std::vector<uint8_t> out(padded_size, 0);
std::memcpy(out.data(), input.data(), input.size());
for (size_t i = 0; i < padded_size; i += 8) {
uint32_t y = ReadU32LE(out.data() + i);
uint32_t z = ReadU32LE(out.data() + i + 4);
EncryptBlock(y, z);
WriteU32LE(out.data() + i, y);
WriteU32LE(out.data() + i + 4, z);
}
return out;
}
std::vector<uint8_t> TeaCipher::Decrypt(std::span<const uint8_t> input) const {
size_t full_blocks = (input.size() / 8) * 8;
std::vector<uint8_t> out(input.begin(), input.begin() + full_blocks);
for (size_t i = 0; i < full_blocks; i += 8) {
uint32_t y = ReadU32LE(out.data() + i);
uint32_t z = ReadU32LE(out.data() + i + 4);
DecryptBlock(y, z);
WriteU32LE(out.data() + i, y);
WriteU32LE(out.data() + i + 4, z);
}
return out;
}
// RollingXorCipher
RollingXorCipher::RollingXorCipher(uint32_t seed_key) {
Reset(seed_key);
}
void RollingXorCipher::Reset(uint32_t seed_key) {
m_key = seed_key;
m_state = seed_key;
}
void RollingXorCipher::Process(uint8_t* data, size_t size) {
for (size_t i = 0; i < size; ++i) {
// Linear feedback shift rolling key
m_state = (m_state * 1103515245u + 12345u);
uint8_t mask = static_cast<uint8_t>((m_state >> 16) & 0xFF);
data[i] ^= mask;
}
}
// CipherContext
void CipherContext::InitializeKeys(const TeaKey& tea_key, uint32_t xor_seed) {
m_send_tea.SetKey(tea_key);
m_recv_tea.SetKey(tea_key);
m_send_xor.Reset(xor_seed);
m_recv_xor.Reset(xor_seed);
}
void CipherContext::EncryptSend(uint8_t* data, size_t size) {
if (!m_enabled || size == 0) return;
// Fast block TEA if multiple of 8, else rolling XOR
size_t tea_len = (size / 8) * 8;
for (size_t i = 0; i < tea_len; i += 8) {
uint32_t y = ReadU32LE(data + i);
uint32_t z = ReadU32LE(data + i + 4);
m_send_tea.EncryptBlock(y, z);
WriteU32LE(data + i, y);
WriteU32LE(data + i + 4, z);
}
// Apply rolling XOR for streaming confidentiality & anti-replay
m_send_xor.Process(data, size);
}
void CipherContext::DecryptRecv(uint8_t* data, size_t size) {
if (!m_enabled || size == 0) return;
// Reverse rolling XOR first
m_recv_xor.Process(data, size);
// Reverse TEA blocks
size_t tea_len = (size / 8) * 8;
for (size_t i = 0; i < tea_len; i += 8) {
uint32_t y = ReadU32LE(data + i);
uint32_t z = ReadU32LE(data + i + 4);
m_recv_tea.DecryptBlock(y, z);
WriteU32LE(data + i, y);
WriteU32LE(data + i + 4, z);
}
}
} // namespace metin2::network
+76
View File
@@ -0,0 +1,76 @@
#include "network/connection_phase.h"
namespace metin2::network {
const char* ToString(ConnectionPhase phase) {
switch (phase) {
case ConnectionPhase::Disconnected: return "Disconnected";
case ConnectionPhase::Handshake: return "Handshake";
case ConnectionPhase::Auth: return "Auth";
case ConnectionPhase::CharacterSelect: return "CharacterSelect";
case ConnectionPhase::GameLoading: return "GameLoading";
case ConnectionPhase::InGame: return "InGame";
default: return "Unknown";
}
}
PhaseStateMachine::PhaseStateMachine()
: m_current_phase(ConnectionPhase::Disconnected) {}
PhaseStateMachine::PhaseStateMachine(ConnectionPhase initial_phase)
: m_current_phase(initial_phase) {}
bool PhaseStateMachine::CanTransitionTo(ConnectionPhase target_phase) const {
if (m_current_phase == target_phase) {
return true;
}
// Always allowed to disconnect
if (target_phase == ConnectionPhase::Disconnected) {
return true;
}
switch (m_current_phase) {
case ConnectionPhase::Disconnected:
return target_phase == ConnectionPhase::Handshake || target_phase == ConnectionPhase::Auth;
case ConnectionPhase::Handshake:
return target_phase == ConnectionPhase::Auth;
case ConnectionPhase::Auth:
return target_phase == ConnectionPhase::CharacterSelect;
case ConnectionPhase::CharacterSelect:
return target_phase == ConnectionPhase::GameLoading || target_phase == ConnectionPhase::Auth;
case ConnectionPhase::GameLoading:
return target_phase == ConnectionPhase::InGame || target_phase == ConnectionPhase::CharacterSelect;
case ConnectionPhase::InGame:
return target_phase == ConnectionPhase::CharacterSelect || target_phase == ConnectionPhase::GameLoading;
default:
return false;
}
}
bool PhaseStateMachine::TransitionTo(ConnectionPhase target_phase) {
if (!CanTransitionTo(target_phase)) {
return false;
}
if (m_current_phase != target_phase) {
ConnectionPhase old = m_current_phase;
m_current_phase = target_phase;
if (m_callback) {
m_callback(old, target_phase);
}
}
return true;
}
void PhaseStateMachine::ForcePhase(ConnectionPhase phase) {
if (m_current_phase != phase) {
ConnectionPhase old = m_current_phase;
m_current_phase = phase;
if (m_callback) {
m_callback(old, phase);
}
}
}
} // namespace metin2::network
+221
View File
@@ -0,0 +1,221 @@
#include "network/network_client.h"
#include <cstring>
namespace metin2::network {
NetworkClient::NetworkClient()
: m_phase_fsm(ConnectionPhase::Disconnected) {
}
void NetworkClient::Reset() {
m_phase_fsm.ForcePhase(ConnectionPhase::Disconnected);
m_cipher.SetEnabled(false);
m_recv_buffer.Clear();
m_send_buffer.clear();
}
void NetworkClient::PushReceivedData(const uint8_t* data, size_t size) {
if (!data || size == 0) return;
std::vector<uint8_t> decrypted(data, data + size);
if (m_cipher.IsEnabled()) {
m_cipher.DecryptRecv(decrypted.data(), decrypted.size());
}
m_recv_buffer.Append(decrypted);
auto packets = m_recv_buffer.ExtractPackets(m_registry);
for (const auto& pkt : packets) {
ProcessPacket(pkt);
}
}
std::vector<uint8_t> NetworkClient::PopSendData() {
std::vector<uint8_t> result;
if (!m_send_buffer.empty()) {
result = std::move(m_send_buffer);
m_send_buffer.clear();
}
return result;
}
void NetworkClient::SendRawPacket(uint8_t header, const void* payload, size_t payload_size) {
std::vector<uint8_t> raw;
raw.reserve(1 + payload_size);
raw.push_back(header);
if (payload && payload_size > 0) {
const uint8_t* bytes = static_cast<const uint8_t*>(payload);
raw.insert(raw.end(), bytes, bytes + payload_size);
}
if (m_cipher.IsEnabled()) {
m_cipher.EncryptSend(raw.data(), raw.size());
}
m_send_buffer.insert(m_send_buffer.end(), raw.begin(), raw.end());
}
void NetworkClient::SendDynamicPacket(uint8_t header, const void* payload, size_t payload_size) {
std::vector<uint8_t> raw;
raw.reserve(3 + payload_size);
raw.push_back(header);
uint16_t sz = static_cast<uint16_t>(payload_size);
raw.push_back(static_cast<uint8_t>(sz & 0xFF));
raw.push_back(static_cast<uint8_t>((sz >> 8) & 0xFF));
if (payload && payload_size > 0) {
const uint8_t* bytes = static_cast<const uint8_t*>(payload);
raw.insert(raw.end(), bytes, bytes + payload_size);
}
if (m_cipher.IsEnabled()) {
m_cipher.EncryptSend(raw.data(), raw.size());
}
m_send_buffer.insert(m_send_buffer.end(), raw.begin(), raw.end());
}
void NetworkClient::SendHandshakeAck(uint32_t client_time) {
SendRawPacket(HEADER_CG_HANDSHAKE, &client_time, sizeof(client_time));
}
void NetworkClient::SendLogin(const std::string& username, const std::string& password) {
char buf[64];
std::memset(buf, 0, sizeof(buf));
std::strncpy(buf, username.c_str(), 31);
std::strncpy(buf + 32, password.c_str(), 31);
SendRawPacket(HEADER_CG_LOGIN, buf, sizeof(buf));
}
void NetworkClient::SendSelectCharacter(uint8_t slot_index) {
SendRawPacket(HEADER_CG_CHARACTER_SELECT, &slot_index, 1);
}
void NetworkClient::SendEnterGame() {
SendRawPacket(HEADER_CG_ENTERGAME, nullptr, 0);
}
void NetworkClient::SendChat(uint8_t chat_type, const std::string& text) {
std::vector<uint8_t> payload;
payload.reserve(1 + text.size());
payload.push_back(chat_type);
payload.insert(payload.end(), text.begin(), text.end());
SendDynamicPacket(HEADER_CG_CHAT, payload.data(), payload.size());
}
void NetworkClient::SendMove(float x, float y, float z, float rotation, uint32_t move_type) {
struct MovePacketPayload {
float x, y, z, rot;
uint32_t type;
} p{x, y, z, rotation, move_type};
SendRawPacket(HEADER_CG_MOVE, &p, sizeof(p));
}
void NetworkClient::ProcessPacket(const Packet& packet) {
switch (packet.header) {
case HEADER_GC_HANDSHAKE: {
if (packet.payload.size() >= 4) {
uint32_t server_time = *reinterpret_cast<const uint32_t*>(packet.payload.data());
if (m_on_handshake) {
m_on_handshake(server_time);
}
}
break;
}
case HEADER_GC_AUTH_SUCCESS: {
SetPhase(ConnectionPhase::CharacterSelect);
if (m_on_auth_result) {
m_on_auth_result(true, 0, "Authentication successful");
}
break;
}
case HEADER_GC_AUTH_FAILURE: {
uint32_t error_code = 0;
std::string msg;
if (packet.payload.size() >= 4) {
error_code = *reinterpret_cast<const uint32_t*>(packet.payload.data());
}
if (packet.payload.size() > 4) {
const char* str = reinterpret_cast<const char*>(packet.payload.data() + 4);
size_t str_len = strnlen(str, packet.payload.size() - 4);
msg.assign(str, str_len);
}
if (m_on_auth_result) {
m_on_auth_result(false, error_code, msg);
}
break;
}
case HEADER_GC_CHARACTER_LIST: {
// Parse character summary list
// Layout per character: id(4), job(1), level(1), name(24) = 30 bytes
std::vector<CharacterSummary> characters;
size_t offset = 0;
while (offset + 30 <= packet.payload.size()) {
CharacterSummary c;
c.id = *reinterpret_cast<const uint32_t*>(packet.payload.data() + offset);
c.job = packet.payload[offset + 4];
c.level = packet.payload[offset + 5];
const char* name_ptr = reinterpret_cast<const char*>(packet.payload.data() + offset + 6);
size_t nlen = strnlen(name_ptr, 24);
c.name.assign(name_ptr, nlen);
characters.push_back(c);
offset += 30;
}
if (m_on_character_list) {
m_on_character_list(characters);
}
break;
}
case HEADER_GC_GAME_START: {
SetPhase(ConnectionPhase::InGame);
PlayerInfo info;
if (packet.payload.size() >= 4 + 32 + 16) {
info.player_id = *reinterpret_cast<const uint32_t*>(packet.payload.data());
const char* name_ptr = reinterpret_cast<const char*>(packet.payload.data() + 4);
info.name.assign(name_ptr, strnlen(name_ptr, 32));
const float* coords = reinterpret_cast<const float*>(packet.payload.data() + 36);
info.x = coords[0];
info.y = coords[1];
info.z = coords[2];
info.rotation = coords[3];
}
if (m_on_game_start) {
m_on_game_start(info);
}
break;
}
case HEADER_GC_CHAT: {
if (!packet.payload.empty()) {
uint8_t chat_type = packet.payload[0];
std::string msg;
if (packet.payload.size() > 1) {
msg.assign(reinterpret_cast<const char*>(packet.payload.data() + 1), packet.payload.size() - 1);
}
if (m_on_chat) {
m_on_chat(0, chat_type, msg);
}
}
break;
}
case HEADER_GC_ACTOR_MOVE: {
if (packet.payload.size() >= 4 + 16 + 1) {
uint32_t vid = *reinterpret_cast<const uint32_t*>(packet.payload.data());
const float* coords = reinterpret_cast<const float*>(packet.payload.data() + 4);
uint8_t move_type = packet.payload[20];
if (m_on_actor_move) {
m_on_actor_move(vid, coords[0], coords[1], coords[2], coords[3], move_type);
}
}
break;
}
default:
break;
}
if (m_on_generic_packet) {
m_on_generic_packet(packet);
}
}
} // namespace metin2::network
+149
View File
@@ -0,0 +1,149 @@
#include "network/packet.h"
#include <cstring>
#include <algorithm>
namespace metin2::network {
PacketRegistry::PacketRegistry() {
RegisterDefaultPackets();
}
void PacketRegistry::Register(uint8_t header, size_t fixed_payload_size) {
PacketDescriptor desc;
desc.header = header;
desc.mode = PacketSizeMode::Fixed;
desc.fixed_payload_size = fixed_payload_size;
m_descriptors[header] = desc;
}
void PacketRegistry::RegisterDynamic(uint8_t header) {
PacketDescriptor desc;
desc.header = header;
desc.mode = PacketSizeMode::Dynamic;
desc.fixed_payload_size = 0;
m_descriptors[header] = desc;
}
const PacketDescriptor* PacketRegistry::Find(uint8_t header) const {
auto it = m_descriptors.find(header);
if (it != m_descriptors.end()) {
return &it->second;
}
return nullptr;
}
bool PacketRegistry::HasHeader(uint8_t header) const {
return m_descriptors.find(header) != m_descriptors.end();
}
void PacketRegistry::RegisterDefaultPackets() {
// Client -> Server default headers
Register(HEADER_CG_HANDSHAKE, 4); // uint32_t handshake_time
Register(HEADER_CG_PONG, 4); // uint32_t ping_id
Register(HEADER_CG_LOGIN, 32 + 32); // username (32) + password (32)
Register(HEADER_CG_CHARACTER_SELECT, 1); // slot_index (1)
Register(HEADER_CG_CHARACTER_DELETE, 1); // slot_index (1)
Register(HEADER_CG_ENTERGAME, 0); // empty payload
Register(HEADER_CG_MOVE, 4 * 4 + 1); // x, y, z, rot, type
Register(HEADER_CG_ATTACK, 4 + 1); // target_vid, type
RegisterDynamic(HEADER_CG_CHAT); // dynamic chat message
// Server -> Client default headers
Register(HEADER_GC_HANDSHAKE, 8); // server_time (4) + delta (4)
Register(HEADER_GC_PING, 4); // ping_id (4)
Register(HEADER_GC_AUTH_SUCCESS, 4); // account_id (4)
Register(HEADER_GC_AUTH_FAILURE, 4 + 64); // error_code (4) + error_msg (64)
Register(HEADER_GC_GAME_START, 4 + 32 + 4 * 4); // vid + name + x, y, z, rot
Register(HEADER_GC_ACTOR_MOVE, 4 + 4 * 4 + 1); // vid + x, y, z, rot + type
Register(HEADER_GC_ACTOR_REMOVE, 4); // vid
RegisterDynamic(HEADER_GC_CHARACTER_LIST); // dynamic list
RegisterDynamic(HEADER_GC_CHAT); // dynamic chat
}
// PacketBuffer
void PacketBuffer::Append(const uint8_t* data, size_t size) {
if (data && size > 0) {
m_buffer.insert(m_buffer.end(), data, data + size);
}
}
void PacketBuffer::Append(const std::vector<uint8_t>& data) {
Append(data.data(), data.size());
}
void PacketBuffer::Clear() {
m_buffer.clear();
m_read_offset = 0;
}
void PacketBuffer::Compact() {
if (m_read_offset > 0) {
if (m_read_offset < m_buffer.size()) {
m_buffer.erase(m_buffer.begin(), m_buffer.begin() + m_read_offset);
} else {
m_buffer.clear();
}
m_read_offset = 0;
}
}
std::vector<Packet> PacketBuffer::ExtractPackets(const PacketRegistry& registry) {
std::vector<Packet> packets;
while (m_read_offset < m_buffer.size()) {
uint8_t header = m_buffer[m_read_offset];
const PacketDescriptor* desc = registry.Find(header);
if (!desc) {
// Unknown packet header: skip 1 byte to attempt re-synchronization
m_read_offset++;
continue;
}
if (desc->mode == PacketSizeMode::Fixed) {
size_t total_packet_size = 1 + desc->fixed_payload_size;
if (m_buffer.size() - m_read_offset < total_packet_size) {
// Incomplete frame, wait for more data
break;
}
Packet pkt;
pkt.header = header;
if (desc->fixed_payload_size > 0) {
pkt.payload.resize(desc->fixed_payload_size);
std::memcpy(pkt.payload.data(), m_buffer.data() + m_read_offset + 1, desc->fixed_payload_size);
}
packets.push_back(std::move(pkt));
m_read_offset += total_packet_size;
} else {
// Dynamic packet: Header (1) + Size (2 bytes LE) + Payload
if (m_buffer.size() - m_read_offset < 3) {
// Incomplete header, wait for more data
break;
}
uint16_t payload_len = static_cast<uint16_t>(m_buffer[m_read_offset + 1]) |
(static_cast<uint16_t>(m_buffer[m_read_offset + 2]) << 8);
size_t total_packet_size = 3 + payload_len;
if (m_buffer.size() - m_read_offset < total_packet_size) {
// Incomplete body, wait for more data
break;
}
Packet pkt;
pkt.header = header;
if (payload_len > 0) {
pkt.payload.resize(payload_len);
std::memcpy(pkt.payload.data(), m_buffer.data() + m_read_offset + 3, payload_len);
}
packets.push_back(std::move(pkt));
m_read_offset += total_packet_size;
}
}
Compact();
return packets;
}
} // namespace metin2::network
+202
View File
@@ -0,0 +1,202 @@
#include "network/network.h"
#include <iostream>
#include <cassert>
#include <cstring>
using namespace metin2::network;
void TestPhaseStateMachine() {
std::cout << "[Test] Phase State Machine...\n";
PhaseStateMachine fsm;
assert(fsm.GetCurrentPhase() == ConnectionPhase::Disconnected);
assert(!fsm.IsConnected());
// Invalid transition
assert(!fsm.CanTransitionTo(ConnectionPhase::InGame));
// Valid flow: Disconnected -> Handshake -> Auth -> CharacterSelect -> GameLoading -> InGame
assert(fsm.TransitionTo(ConnectionPhase::Handshake));
assert(fsm.GetCurrentPhase() == ConnectionPhase::Handshake);
assert(fsm.IsConnected());
assert(fsm.TransitionTo(ConnectionPhase::Auth));
assert(fsm.TransitionTo(ConnectionPhase::CharacterSelect));
assert(fsm.TransitionTo(ConnectionPhase::GameLoading));
assert(fsm.TransitionTo(ConnectionPhase::InGame));
assert(fsm.IsInGame());
// Disconnect from anywhere
assert(fsm.TransitionTo(ConnectionPhase::Disconnected));
assert(!fsm.IsConnected());
std::cout << " -> Phase transitions passed!\n";
}
void TestCipher() {
std::cout << "[Test] TEA & Rolling XOR Cipher...\n";
TeaKey key = { 0x12345678, 0x9ABCDEF0, 0x0FEDCBA9, 0x87654321 };
TeaCipher tea(key);
std::string text = "Metin2 cross-platform network packet payload encryption!";
std::vector<uint8_t> plain(text.begin(), text.end());
auto encrypted = tea.Encrypt(plain);
assert(encrypted.size() >= plain.size());
assert(encrypted.size() % 8 == 0);
auto decrypted = tea.Decrypt(encrypted);
assert(std::memcmp(plain.data(), decrypted.data(), plain.size()) == 0);
// Rolling XOR
RollingXorCipher xor_cipher1(0xA5A55A5A);
RollingXorCipher xor_cipher2(0xA5A55A5A);
std::vector<uint8_t> xor_buf(plain.begin(), plain.end());
xor_cipher1.Process(xor_buf.data(), xor_buf.size());
assert(std::memcmp(plain.data(), xor_buf.data(), plain.size()) != 0);
xor_cipher2.Process(xor_buf.data(), xor_buf.size());
assert(std::memcmp(plain.data(), xor_buf.data(), plain.size()) == 0);
std::cout << " -> Cipher encryption and decryption passed!\n";
}
void TestPacketSegmentationAndReassembly() {
std::cout << "[Test] Packet Buffer Fragmentation & Reassembly...\n";
PacketRegistry registry;
PacketBuffer buffer;
// 1. Pack multiple packets into one stream (Sticky packets / 粘包)
// Packet A: HEADER_GC_PING (header=253, 4 bytes payload)
// Packet B: HEADER_CG_CHARACTER_SELECT (header=6, 1 byte payload)
uint32_t ping_id = 9999;
uint8_t char_slot = 2;
std::vector<uint8_t> sticky_stream;
sticky_stream.push_back(HEADER_GC_PING);
const uint8_t* p_ping = reinterpret_cast<const uint8_t*>(&ping_id);
sticky_stream.insert(sticky_stream.end(), p_ping, p_ping + 4);
sticky_stream.push_back(HEADER_CG_CHARACTER_SELECT);
sticky_stream.push_back(char_slot);
buffer.Append(sticky_stream);
auto packets = buffer.ExtractPackets(registry);
assert(packets.size() == 2);
assert(packets[0].header == HEADER_GC_PING);
assert(packets[0].payload.size() == 4);
assert(*reinterpret_cast<const uint32_t*>(packets[0].payload.data()) == 9999);
assert(packets[1].header == HEADER_CG_CHARACTER_SELECT);
assert(packets[1].payload[0] == 2);
// 2. Partial packets (半包)
// Send 1st half of a packet
std::vector<uint8_t> half1;
half1.push_back(HEADER_GC_PING);
half1.push_back(0x11);
half1.push_back(0x22);
buffer.Append(half1);
auto partial = buffer.ExtractPackets(registry);
assert(partial.empty()); // Not complete yet
// Send 2nd half
std::vector<uint8_t> half2;
half2.push_back(0x33);
half2.push_back(0x44);
buffer.Append(half2);
auto completed = buffer.ExtractPackets(registry);
assert(completed.size() == 1);
assert(completed[0].header == HEADER_GC_PING);
assert(completed[0].payload[0] == 0x11 && completed[0].payload[3] == 0x44);
std::cout << " -> Packet segmentation and reassembly passed!\n";
}
void TestNetworkClientEndToEnd() {
std::cout << "[Test] NetworkClient Full Protocol Pipeline...\n";
NetworkClient client;
bool handshake_called = false;
bool auth_called = false;
std::string received_chat;
client.SetOnHandshake([&](uint32_t s_time) {
handshake_called = true;
assert(s_time == 12345678);
});
client.SetOnAuthResult([&](bool success, uint32_t err, const std::string& msg) {
auth_called = true;
assert(success);
});
client.SetOnChat([&](uint32_t sender, uint8_t type, const std::string& msg) {
received_chat = msg;
});
// Client connects -> Handshake phase
client.SetPhase(ConnectionPhase::Handshake);
assert(client.GetPhase() == ConnectionPhase::Handshake);
// Server sends GC_HANDSHAKE (header 255, 8 bytes: time=12345678, delta=0)
std::vector<uint8_t> server_handshake;
server_handshake.push_back(HEADER_GC_HANDSHAKE);
uint32_t s_time = 12345678;
uint32_t delta = 0;
const uint8_t* p_st = reinterpret_cast<const uint8_t*>(&s_time);
const uint8_t* p_dt = reinterpret_cast<const uint8_t*>(&delta);
server_handshake.insert(server_handshake.end(), p_st, p_st + 4);
server_handshake.insert(server_handshake.end(), p_dt, p_dt + 4);
client.PushReceivedData(server_handshake.data(), server_handshake.size());
assert(handshake_called);
// Client responds with Handshake Ack
client.SendHandshakeAck(87654321);
assert(client.HasPendingSendData());
auto out_data = client.PopSendData();
assert(!out_data.empty());
assert(out_data[0] == HEADER_CG_HANDSHAKE);
// Move to Auth phase & authenticate
client.SetPhase(ConnectionPhase::Auth);
client.SendLogin("player_tester", "secret_pass");
auto login_send = client.PopSendData();
assert(login_send[0] == HEADER_CG_LOGIN);
// Server sends Auth success (HEADER_GC_AUTH_SUCCESS: header 101, account_id 42)
std::vector<uint8_t> auth_resp;
auth_resp.push_back(HEADER_GC_AUTH_SUCCESS);
uint32_t account_id = 42;
const uint8_t* p_acc = reinterpret_cast<const uint8_t*>(&account_id);
auth_resp.insert(auth_resp.end(), p_acc, p_acc + 4);
client.PushReceivedData(auth_resp.data(), auth_resp.size());
assert(auth_called);
assert(client.GetPhase() == ConnectionPhase::CharacterSelect);
// Server sends Chat dynamic packet
std::string test_msg = "Welcome to Metin2 World!";
std::vector<uint8_t> chat_pkt;
chat_pkt.push_back(HEADER_GC_CHAT);
uint16_t chat_len = static_cast<uint16_t>(1 + test_msg.size());
chat_pkt.push_back(chat_len & 0xFF);
chat_pkt.push_back((chat_len >> 8) & 0xFF);
chat_pkt.push_back(1); // chat type
chat_pkt.insert(chat_pkt.end(), test_msg.begin(), test_msg.end());
client.PushReceivedData(chat_pkt.data(), chat_pkt.size());
assert(received_chat == test_msg);
std::cout << " -> NetworkClient pipeline passed!\n";
}
int main() {
std::cout << "=== Running Metin2 Network SDK Tests ===\n";
TestPhaseStateMachine();
TestCipher();
TestPacketSegmentationAndReassembly();
TestNetworkClientEndToEnd();
std::cout << "All Network SDK Tests PASSED!\n";
return 0;
}