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
+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