diff --git a/server/server.cpp b/server/server.cpp index a8c978e..e13d653 100644 --- a/server/server.cpp +++ b/server/server.cpp @@ -7,14 +7,30 @@ #include #include #include +#include +#include #include #define _USE_MATH_DEFINES #include #include "../src/network/ClientState.h" #include #include +#include +#include + +namespace beast = boost::beast; +namespace http = beast::http; +namespace websocket = beast::websocket; +namespace net = boost::asio; +using tcp = net::ip::tcp; + +struct DeathInfo { + int targetId = -1; + uint64_t serverTime = 0; + Eigen::Vector3f position = Eigen::Vector3f::Zero(); + int killerId = -1; +}; -// Вспомогательный split std::vector split(const std::string& s, char delimiter) { std::vector tokens; std::string token; @@ -25,127 +41,98 @@ std::vector split(const std::string& s, char delimiter) { return tokens; } -namespace beast = boost::beast; -namespace http = beast::http; -namespace websocket = beast::websocket; -namespace net = boost::asio; -using tcp = net::ip::tcp; - -class Session; - struct ServerBox { Eigen::Vector3f position; Eigen::Matrix3f rotation; float collisionRadius = 2.0f; }; +struct Projectile { + int shooterId = -1; + uint64_t spawnMs = 0; + Eigen::Vector3f pos; + Eigen::Vector3f vel; + float lifeMs = 5000.0f; +}; + std::vector g_serverBoxes; std::mutex g_boxes_mutex; - -std::vector> g_sessions; +std::vector> g_sessions; std::mutex g_sessions_mutex; +std::vector g_projectiles; +std::mutex g_projectiles_mutex; + +std::unordered_set g_dead_players; +std::mutex g_dead_mutex; + +class Session; + +void broadcastToAll(const std::string& message); + class Session : public std::enable_shared_from_this { websocket::stream ws_; beast::flat_buffer buffer_; int id_; bool is_writing_ = false; + std::queue> writeQueue_; + std::mutex writeMutex_; +public: ClientStateInterval timedClientStates; - void process_message(const std::string& msg) { - auto now_server = std::chrono::system_clock::now(); - auto parts = split(msg, ':'); + explicit Session(tcp::socket&& socket, int id) + : ws_(std::move(socket)), id_(id) { + } - if (parts.empty()) { - std::cerr << "Empty message received\n"; - return; + int get_id() const { return id_; } + + bool fetchStateAtTime(std::chrono::system_clock::time_point targetTime, ClientState& outState) const { + if (timedClientStates.canFetchClientStateAtTime(targetTime)) { + outState = timedClientStates.fetchClientStateAtTime(targetTime); + return true; } + return false; + } - std::string type = parts[0]; - - if (type == "UPD") { - if (parts.size() < 16) { - std::cerr << "Invalid UPD message: too few parts (" << parts.size() << ")\n"; - return; - } - uint64_t clientTimestamp = std::stoull(parts[1]); - ClientState receivedState; - receivedState.id = id_; - std::chrono::system_clock::time_point uptime_timepoint{ - std::chrono::milliseconds(clientTimestamp) - }; - receivedState.lastUpdateServerTime = uptime_timepoint; - receivedState.handle_full_sync(parts, 2); - retranslateMessage(msg); - timedClientStates.add_state(receivedState); + void send_message(const std::string& msg) { + auto ss = std::make_shared(msg); + { + std::lock_guard lock(writeMutex_); + writeQueue_.push(ss); } - else if (parts[0] == "FIRE") { - if (parts.size() < 10) { - std::cerr << "Invalid FIRE: too few parts\n"; - return; - } - - uint64_t clientTime = std::stoull(parts[1]); - Eigen::Vector3f pos{ - std::stof(parts[2]), std::stof(parts[3]), std::stof(parts[4]) - }; - Eigen::Quaternion dir{ - std::stof(parts[5]), std::stof(parts[6]), std::stof(parts[7]), std::stof(parts[8]) - }; - - float velocity = std::stof(parts[9]); - - int shotCount = 2; - if (parts.size() >= 11) { - try { - shotCount = std::stoi(parts[10]); - } - catch (...) { - shotCount = 2; - } - } - - std::string broadcast = "PROJECTILE:" + - std::to_string(id_) + ":" + - std::to_string(clientTime) + ":" + - std::to_string(pos.x()) + ":" + - std::to_string(pos.y()) + ":" + - std::to_string(pos.z()) + ":" + - std::to_string(dir.w()) + ":" + - std::to_string(dir.x()) + ":" + - std::to_string(dir.y()) + ":" + - std::to_string(dir.z()) + ":" + - std::to_string(velocity) + ":" + - std::to_string(shotCount); + doWrite(); + } + void run() { + { std::lock_guard lock(g_sessions_mutex); - std::cout << "Player " << id_ << " fired " << shotCount << " shots → broadcasting\n"; + g_sessions.push_back(shared_from_this()); + } - for (auto& session : g_sessions) { - if (session->get_id() != id_) { - session->send_message(broadcast); - } - } - } - else { - std::cerr << "Unknown message type: " << type << "\n"; - } + ws_.async_accept([self = shared_from_this()](beast::error_code ec) { + if (ec) return; + std::cout << "Client " << self->id_ << " connected\n"; + self->init(); + }); } - void retranslateMessage(const std::string& msg) - { - std::string event_msg = "EVENT:" + std::to_string(id_) + ":" + msg; +private: + /* + void init() { + sendBoxesToClient(); - std::lock_guard lock(g_sessions_mutex); - for (auto& session : g_sessions) { - if (session->get_id() != id_) { // Не шлем отправителю - session->send_message(event_msg); + auto timer = std::make_shared(ws_.get_executor()); + timer->expires_after(std::chrono::milliseconds(100)); + timer->async_wait([self = shared_from_this(), timer](const boost::system::error_code& ec) { + if (!ec) { + self->send_message("ID:" + std::to_string(self->id_)); + self->do_read(); } - } + }); } - + */ void sendBoxesToClient() { std::lock_guard lock(g_boxes_mutex); @@ -162,18 +149,17 @@ class Session : public std::enable_shared_from_this { std::to_string(q.z()) + "|"; } - if (!boxMsg.empty() && boxMsg.back() == '|') { - boxMsg.pop_back(); - } + if (!boxMsg.empty() && boxMsg.back() == '|') boxMsg.pop_back(); send_message(boxMsg); } public: + /* explicit Session(tcp::socket&& socket, int id) : ws_(std::move(socket)), id_(id) { - } + }*/ void init() { @@ -188,7 +174,7 @@ public: } }); } - + /* void run() { { @@ -203,16 +189,16 @@ public: // self->send_message("ID:" + std::to_string(self->id_)); // self->do_read(); }); - } + }*/ /*void send_message(std::string msg) { auto ss = std::make_shared(std::move(msg)); ws_.async_write(net::buffer(*ss), [ss](beast::error_code, std::size_t) {}); - }*/ + } int get_id() const { return id_; - } + }*/ ClientState get_latest_state(std::chrono::system_clock::time_point now) { if (timedClientStates.timedStates.empty()) { @@ -229,7 +215,7 @@ public: return latest; } - + /* void send_message(std::string msg) { auto ss = std::make_shared(std::move(msg)); @@ -252,18 +238,42 @@ public: } }); } - } + }*/ + void doWrite() { + std::lock_guard lock(writeMutex_); + if (is_writing_ || writeQueue_.empty()) { + return; + } + + is_writing_ = true; + auto message = writeQueue_.front(); + + ws_.async_write(net::buffer(*message), + [self = shared_from_this(), message](beast::error_code ec, std::size_t) { + if (ec) { + std::cerr << "Write error: " << ec.message() << std::endl; + return; + } + { + std::lock_guard lock(self->writeMutex_); + self->writeQueue_.pop(); + self->is_writing_ = false; + } + self->doWrite(); + }); + } private: + void do_read() { ws_.async_read(buffer_, [self = shared_from_this()](beast::error_code ec, std::size_t) { - if (ec) - { + if (ec) { std::lock_guard lock(g_sessions_mutex); g_sessions.erase(std::remove_if(g_sessions.begin(), g_sessions.end(), [self](const std::shared_ptr& session) { return session.get() == self.get(); }), g_sessions.end()); + std::cout << "Client " << self->id_ << " disconnected\n"; return; } @@ -274,9 +284,139 @@ private: self->do_read(); }); } + + void process_message(const std::string& msg) { + auto parts = split(msg, ':'); + + if (parts.empty()) return; + + std::string type = parts[0]; + + if (type == "UPD") { + { + std::lock_guard gd(g_dead_mutex); + if (g_dead_players.find(id_) != g_dead_players.end()) { + std::cout << "Server: Ignoring UPD from dead player " << id_ << std::endl; + return; + } + } + + if (parts.size() < 16) return; + uint64_t clientTimestamp = std::stoull(parts[1]); + ClientState receivedState; + receivedState.id = id_; + std::chrono::system_clock::time_point uptime_timepoint{ + std::chrono::milliseconds(clientTimestamp) + }; + receivedState.lastUpdateServerTime = uptime_timepoint; + receivedState.handle_full_sync(parts, 2); + timedClientStates.add_state(receivedState); + + retranslateMessage(msg); + } + else if (parts[0] == "RESPAWN") { + { + std::lock_guard gd(g_dead_mutex); + g_dead_players.erase(id_); + } + + std::string respawnMsg = "RESPAWN_ACK:" + std::to_string(id_); + broadcastToAll(respawnMsg); + + std::cout << "Server: Player " << id_ << " respawned\n"; + } + else if (parts[0] == "FIRE") { + if (parts.size() < 10) return; + + uint64_t clientTime = std::stoull(parts[1]); + Eigen::Vector3f pos{ + std::stof(parts[2]), std::stof(parts[3]), std::stof(parts[4]) + }; + Eigen::Quaternionf dir( + std::stof(parts[5]), std::stof(parts[6]), std::stof(parts[7]), std::stof(parts[8]) + ); + float velocity = std::stof(parts[9]); + + int shotCount = 2; + if (parts.size() >= 11) { + try { shotCount = std::stoi(parts[10]); } + catch (...) { shotCount = 2; } + } + + std::string broadcast = "PROJECTILE:" + + std::to_string(id_) + ":" + + std::to_string(clientTime) + ":" + + std::to_string(pos.x()) + ":" + + std::to_string(pos.y()) + ":" + + std::to_string(pos.z()) + ":" + + std::to_string(dir.w()) + ":" + + std::to_string(dir.x()) + ":" + + std::to_string(dir.y()) + ":" + + std::to_string(dir.z()) + ":" + + std::to_string(velocity); + + { + std::lock_guard lock(g_sessions_mutex); + for (auto& session : g_sessions) { + if (session->get_id() != id_) { + session->send_message(broadcast); + } + } + } + + { + const std::vector localOffsets = { + Eigen::Vector3f(-1.5f, 0.9f, 5.0f), + Eigen::Vector3f(1.5f, 0.9f, 5.0f) + }; + + uint64_t now_ms = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + + std::lock_guard pl(g_projectiles_mutex); + for (int i = 0; i < std::min(shotCount, (int)localOffsets.size()); ++i) { + Projectile pr; + pr.shooterId = id_; + pr.spawnMs = now_ms; + Eigen::Vector3f shotPos = pos + dir.toRotationMatrix() * localOffsets[i]; + pr.pos = shotPos; + Eigen::Vector3f localForward(0.0f, 0.0f, -1.0f); + Eigen::Vector3f worldForward = dir.toRotationMatrix() * localForward; + float len = worldForward.norm(); + if (len > 1e-6f) worldForward /= len; + pr.vel = worldForward * velocity; + pr.lifeMs = 5000.0f; + g_projectiles.push_back(pr); + + std::cout << "Server: Created projectile from player " << id_ + << " at pos (" << shotPos.x() << ", " << shotPos.y() << ", " << shotPos.z() + << ") vel (" << pr.vel.x() << ", " << pr.vel.y() << ", " << pr.vel.z() << ")" << std::endl; + } + } + } + } + + void retranslateMessage(const std::string& msg) { + std::string event_msg = "EVENT:" + std::to_string(id_) + ":" + msg; + + std::lock_guard lock(g_sessions_mutex); + for (auto& session : g_sessions) { + if (session->get_id() != id_) { + session->send_message(event_msg); + } + } + } }; +void broadcastToAll(const std::string& message) { + std::lock_guard lock(g_sessions_mutex); + for (const auto& session : g_sessions) { + session->send_message(message); + } +} + void update_world(net::steady_timer& timer, net::io_context& ioc) { + static auto last_snapshot_time = std::chrono::steady_clock::now(); auto now = std::chrono::steady_clock::now(); @@ -305,9 +445,105 @@ void update_world(net::steady_timer& timer, net::io_context& ioc) { } }*/ - timer.expires_after(std::chrono::milliseconds(50)); + const std::chrono::milliseconds interval(50); + timer.expires_after(interval); + timer.async_wait([&](const boost::system::error_code& ec) { - if (!ec) update_world(timer, ioc); + if (ec) return; + + auto now = std::chrono::system_clock::now(); + uint64_t now_ms = static_cast(std::chrono::duration_cast(now.time_since_epoch()).count()); + + std::vector deathEvents; + + { + std::lock_guard pl(g_projectiles_mutex); + std::vector indicesToRemove; + + float dt = 50.0f / 1000.0f; + + for (size_t i = 0; i < g_projectiles.size(); ++i) { + auto& pr = g_projectiles[i]; + + pr.pos += pr.vel * dt; + + if (now_ms > pr.spawnMs + static_cast(pr.lifeMs)) { + indicesToRemove.push_back(static_cast(i)); + continue; + } + + bool hitDetected = false; + + { + std::lock_guard lm(g_sessions_mutex); + std::lock_guard gd(g_dead_mutex); + + for (auto& session : g_sessions) { + int targetId = session->get_id(); + + if (targetId == pr.shooterId) continue; + if (g_dead_players.find(targetId) != g_dead_players.end()) continue; + + ClientState targetState; + if (!session->fetchStateAtTime(now, targetState)) continue; + + Eigen::Vector3f diff = pr.pos - targetState.position; + const float shipRadius = 15.0f; + const float projectileRadius = 1.5f; + float combinedRadius = shipRadius + projectileRadius; + + if (diff.squaredNorm() <= combinedRadius * combinedRadius) { + DeathInfo death; + death.targetId = targetId; + death.serverTime = now_ms; + death.position = pr.pos; + death.killerId = pr.shooterId; + + deathEvents.push_back(death); + g_dead_players.insert(targetId); + indicesToRemove.push_back(static_cast(i)); + hitDetected = true; + + std::cout << "Server: *** HIT DETECTED! ***" << std::endl; + std::cout << "Server: Projectile at (" + << pr.pos.x() << ", " << pr.pos.y() << ", " << pr.pos.z() + << ") hit player " << targetId << std::endl; + break; + } + } + } + + if (hitDetected) continue; + } + + if (!indicesToRemove.empty()) { + std::sort(indicesToRemove.rbegin(), indicesToRemove.rend()); + for (int idx : indicesToRemove) { + if (idx >= 0 && idx < (int)g_projectiles.size()) { + g_projectiles.erase(g_projectiles.begin() + idx); + } + } + } + } + + if (!deathEvents.empty()) { + for (const auto& death : deathEvents) { + std::string deadMsg = "DEAD:" + + std::to_string(death.serverTime) + ":" + + std::to_string(death.targetId) + ":" + + std::to_string(death.position.x()) + ":" + + std::to_string(death.position.y()) + ":" + + std::to_string(death.position.z()) + ":" + + std::to_string(death.killerId); + + broadcastToAll(deadMsg); + + std::cout << "Server: Sent DEAD event - Player " << death.targetId + << " killed by " << death.killerId << std::endl; + } + } + + update_world(timer, ioc); }); } @@ -360,7 +596,6 @@ std::vector generateServerBoxes(int count) { return boxes; } - int main() { try { { @@ -383,7 +618,6 @@ int main() { }); }; - net::steady_timer timer(ioc); update_world(timer, ioc); diff --git a/src/Game.cpp b/src/Game.cpp index 4848277..dc864e2 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -1039,11 +1039,16 @@ namespace ZL if (!uiGameOverShown) { if (uiManager.pushMenuFromFile("resources/config/game_over.json", this->renderer, CONST_ZIP_FILE)) { uiManager.setButtonCallback("restartButton", [this](const std::string& name) { + + std::string respawnMsg = "RESPAWN:" + std::to_string(networkClient->GetClientId()); + networkClient->Send(respawnMsg); + this->shipAlive = true; this->gameOver = false; this->uiGameOverShown = false; this->showExplosion = false; this->explosionEmitter.setEmissionPoints(std::vector()); + this->deadRemotePlayers.clear(); Environment::shipState.position = Vector3f{ 0, 0, 45000.f }; Environment::shipState.velocity = 0.0f; @@ -1434,6 +1439,80 @@ namespace ZL } }*/ } + // Обработка событий смерти, присланных сервером + auto deaths = networkClient->getPendingDeaths(); + if (!deaths.empty()) { + int localId = networkClient->GetClientId(); + std::cout << "Client: Received " << deaths.size() << " death events" << std::endl; + + for (const auto& d : deaths) { + std::cout << "Client: Processing death - target=" << d.targetId + << ", killer=" << d.killerId << ", pos=(" + << d.position.x() << ", " << d.position.y() << ", " << d.position.z() << ")" << std::endl; + + showExplosion = true; + explosionEmitter.setUseWorldSpace(true); + explosionEmitter.setEmissionPoints(std::vector{ d.position }); + explosionEmitter.emit(); + lastExplosionTime = SDL_GetTicks64(); + std::cout << "Client: Explosion emitted at (" << d.position.x() << ", " + << d.position.y() << ", " << d.position.z() << ")" << std::endl; + + if (d.targetId == localId) { + std::cout << "Client: Local ship destroyed!" << std::endl; + shipAlive = false; + gameOver = true; + Environment::shipState.velocity = 0.0f; + + if (!uiGameOverShown) { + if (uiManager.pushMenuFromFile("resources/config/game_over.json", + this->renderer, CONST_ZIP_FILE)) { + uiManager.setButtonCallback("restartButton", [this](const std::string& name) { + std::cout << "Client: Restart button clicked, sending RESPAWN" << std::endl; + + std::string respawnMsg = "RESPAWN:" + std::to_string(networkClient->GetClientId()); + networkClient->Send(respawnMsg); + + this->shipAlive = true; + this->gameOver = false; + this->uiGameOverShown = false; + this->showExplosion = false; + this->explosionEmitter.setEmissionPoints(std::vector()); + this->deadRemotePlayers.clear(); + + Environment::shipState.position = Vector3f{ 0, 0, 45000.f }; + Environment::shipState.velocity = 0.0f; + Environment::shipState.rotation = Eigen::Matrix3f::Identity(); + Environment::inverseShipMatrix = Eigen::Matrix3f::Identity(); + Environment::zoom = DEFAULT_ZOOM; + Environment::tapDownHold = false; + + uiManager.popMenu(); + std::cerr << "Game restarted\n"; + }); + + uiManager.setButtonCallback("gameOverExitButton", [this](const std::string& name) { + Environment::exitGameLoop = true; + }); + + uiGameOverShown = true; + } + } + } + else { + deadRemotePlayers.insert(d.targetId); + std::cout << "Marked remote player " << d.targetId << " as dead" << std::endl; + } + } + } + + auto respawns = networkClient->getPendingRespawns(); + if (!respawns.empty()) { + for (const auto& respawnId : respawns) { + deadRemotePlayers.erase(respawnId); + std::cout << "Client: Remote player " << respawnId << " respawned, removed from dead list" << std::endl; + } + } } } diff --git a/src/Game.h b/src/Game.h index b8b2ce6..273eaf4 100644 --- a/src/Game.h +++ b/src/Game.h @@ -15,6 +15,8 @@ #include #include +#include + namespace ZL { @@ -118,6 +120,7 @@ namespace ZL { const uint64_t explosionDurationMs = 500; bool serverBoxesApplied = false; + static constexpr float MAX_DIST_SQ = 10000.f * 10000.f; static constexpr float FADE_START = 6000.f; static constexpr float FADE_RANGE = 4000.f; @@ -125,6 +128,9 @@ namespace ZL { static constexpr float PERSPECTIVE_K = 0.05f; // Tune static constexpr float MIN_SCALE = 0.4f; static constexpr float MAX_SCALE = 1.5f; + + std::unordered_set deadRemotePlayers; + }; diff --git a/src/network/LocalClient.h b/src/network/LocalClient.h index c45c0c8..8d72353 100644 --- a/src/network/LocalClient.h +++ b/src/network/LocalClient.h @@ -1,6 +1,5 @@ #pragma once -// WebSocketClient.h #include "NetworkInterface.h" #include @@ -16,8 +15,8 @@ namespace ZL { void Send(const std::string& message) override; bool IsConnected() const override { return true; } - int GetClientId() const { return 1; } - std::vector getPendingProjectiles(); + int GetClientId() const override { return 1; } + std::vector getPendingProjectiles() override; std::unordered_map getRemotePlayers() override { return std::unordered_map(); @@ -26,5 +25,13 @@ namespace ZL { std::vector> getServerBoxes() override { return {}; } + + std::vector getPendingDeaths() override { + return {}; + } + + std::vector getPendingRespawns() override { + return {}; + } }; } \ No newline at end of file diff --git a/src/network/NetworkInterface.h b/src/network/NetworkInterface.h index fc03c53..063b666 100644 --- a/src/network/NetworkInterface.h +++ b/src/network/NetworkInterface.h @@ -7,26 +7,37 @@ // NetworkInterface.h - »нтерфейс дл¤ разных типов соединений namespace ZL { - struct ProjectileInfo { - int shooterId = -1; - uint64_t clientTime = 0; - Eigen::Vector3f position = Eigen::Vector3f::Zero(); - //Eigen::Vector3f direction = Eigen::Vector3f::Zero(); - Eigen::Matrix3f rotation = Eigen::Matrix3f::Identity(); - float velocity = 0; - }; + struct ProjectileInfo { + int shooterId = -1; + uint64_t clientTime = 0; + Eigen::Vector3f position = Eigen::Vector3f::Zero(); + //Eigen::Vector3f direction = Eigen::Vector3f::Zero(); + Eigen::Matrix3f rotation = Eigen::Matrix3f::Identity(); + float velocity = 0; + }; - class INetworkClient { - public: - virtual ~INetworkClient() = default; - virtual void Connect(const std::string& host, uint16_t port) = 0; - virtual void Send(const std::string& message) = 0; - virtual bool IsConnected() const = 0; - virtual void Poll() = 0; // ƒл¤ обработки вход¤щих пакетов - virtual std::unordered_map getRemotePlayers() = 0; + struct DeathInfo { + int targetId = -1; + uint64_t serverTime = 0; + Eigen::Vector3f position = Eigen::Vector3f::Zero(); + int killerId = -1; + }; - virtual std::vector> getServerBoxes() = 0; + class INetworkClient { + public: + virtual ~INetworkClient() = default; + virtual void Connect(const std::string& host, uint16_t port) = 0; + virtual void Send(const std::string& message) = 0; + virtual bool IsConnected() const = 0; + virtual void Poll() = 0; // ƒл¤ обработки вход¤щих пакетов + virtual std::unordered_map getRemotePlayers() = 0; - virtual std::vector getPendingProjectiles() = 0; - }; + virtual std::vector> getServerBoxes() = 0; + + virtual std::vector getPendingProjectiles() = 0; + + virtual std::vector getPendingDeaths() = 0; + virtual std::vector getPendingRespawns() = 0; + virtual int GetClientId() const { return -1; } + }; } diff --git a/src/network/WebSocketClient.cpp b/src/network/WebSocketClient.cpp index 91db004..c28496b 100644 --- a/src/network/WebSocketClient.cpp +++ b/src/network/WebSocketClient.cpp @@ -71,6 +71,20 @@ namespace ZL { return copy; } + std::vector WebSocketClient::getPendingDeaths() { + std::lock_guard lock(deathsMutex_); + auto copy = pendingDeaths_; + pendingDeaths_.clear(); + return copy; + } + + std::vector WebSocketClient::getPendingRespawns() { + std::lock_guard lock(respawnMutex_); + auto copy = pendingRespawns_; + pendingRespawns_.clear(); + return copy; + } + void WebSocketClient::Poll() { std::lock_guard lock(queueMutex); @@ -125,6 +139,25 @@ namespace ZL { } continue; } + if (msg.rfind("RESPAWN_ACK:", 0) == 0) { + auto parts = split(msg, ':'); + if (parts.size() >= 2) { + try { + int respawnedPlayerId = std::stoi(parts[1]); + { + std::lock_guard rLock(respawnMutex_); + pendingRespawns_.push_back(respawnedPlayerId); + } + { + std::lock_guard pLock(playersMutex); + remotePlayers.erase(respawnedPlayerId); + } + std::cout << "Client: Received RESPAWN_ACK for player " << respawnedPlayerId << std::endl; + } + catch (...) {} + } + continue; + } if (msg.rfind("PROJECTILE:", 0) == 0) { auto parts = split(msg, ':'); @@ -150,8 +183,29 @@ namespace ZL { std::lock_guard pl(projMutex_); pendingProjectiles_.push_back(pi); } - catch (...) { + catch (...) {} + } + continue; + } + + if (msg.rfind("DEAD:", 0) == 0) { + auto parts = split(msg, ':'); + if (parts.size() >= 7) { + try { + DeathInfo di; + di.serverTime = std::stoull(parts[1]); + di.targetId = std::stoi(parts[2]); + di.position = Eigen::Vector3f( + std::stof(parts[3]), + std::stof(parts[4]), + std::stof(parts[5]) + ); + di.killerId = std::stoi(parts[6]); + + std::lock_guard dl(deathsMutex_); + pendingDeaths_.push_back(di); } + catch (...) {} } continue; } diff --git a/src/network/WebSocketClient.h b/src/network/WebSocketClient.h index 093e008..451f25c 100644 --- a/src/network/WebSocketClient.h +++ b/src/network/WebSocketClient.h @@ -2,7 +2,6 @@ #ifdef NETWORK -// WebSocketClient.h #include "NetworkInterface.h" #include #include @@ -12,62 +11,70 @@ namespace ZL { - class WebSocketClient : public INetworkClient { - private: - // Переиспользуем io_context из TaskManager - boost::asio::io_context& ioc_; + class WebSocketClient : public INetworkClient { + private: + // Переиспользуем io_context из TaskManager + boost::asio::io_context& ioc_; - // Объекты переехали в члены класса - std::unique_ptr> ws_; - boost::beast::flat_buffer buffer_; + // Объекты переехали в члены класса + std::unique_ptr> ws_; + boost::beast::flat_buffer buffer_; - std::queue messageQueue; - std::mutex queueMutex; // Защита для messageQueue + std::queue messageQueue; + std::mutex queueMutex; // Защита для messageQueue - std::queue> writeQueue_; - bool isWriting_ = false; - std::mutex writeMutex_; // Отдельный мьютекс для очереди записи + std::queue> writeQueue_; + bool isWriting_ = false; + std::mutex writeMutex_; // Отдельный мьютекс для очереди записи - bool connected = false; - int clientId = -1; + bool connected = false; + int clientId = -1; - std::unordered_map remotePlayers; - std::mutex playersMutex; + std::unordered_map remotePlayers; + std::mutex playersMutex; - // Серверные коробки - std::vector> serverBoxes_; - std::mutex boxesMutex; + // Серверные коробки + std::vector> serverBoxes_; + std::mutex boxesMutex; - std::vector pendingProjectiles_; - std::mutex projMutex_; + std::vector pendingProjectiles_; + std::mutex projMutex_; - void startAsyncRead(); - void processIncomingMessage(const std::string& msg); + std::vector pendingDeaths_; + std::mutex deathsMutex_; - public: - explicit WebSocketClient(boost::asio::io_context& ioc) : ioc_(ioc) {} + std::vector pendingRespawns_; + std::mutex respawnMutex_; - void Connect(const std::string& host, uint16_t port) override; + void startAsyncRead(); + void processIncomingMessage(const std::string& msg); - void Poll() override; + public: + explicit WebSocketClient(boost::asio::io_context& ioc) : ioc_(ioc) {} - void Send(const std::string& message) override; - void doWrite(); + void Connect(const std::string& host, uint16_t port) override; - bool IsConnected() const override { return connected; } - int GetClientId() const { return clientId; } + void Poll() override; - std::unordered_map getRemotePlayers() override { - std::lock_guard lock(playersMutex); - return remotePlayers; - } + void Send(const std::string& message) override; + void doWrite(); - std::vector> getServerBoxes() override { - std::lock_guard lock(boxesMutex); - return serverBoxes_; - } + bool IsConnected() const override { return connected; } + int GetClientId() const override { return clientId; } - std::vector getPendingProjectiles() override; - }; + std::unordered_map getRemotePlayers() override { + std::lock_guard lock(playersMutex); + return remotePlayers; + } + + std::vector> getServerBoxes() override { + std::lock_guard lock(boxesMutex); + return serverBoxes_; + } + + std::vector getPendingProjectiles() override; + std::vector getPendingDeaths() override; + std::vector getPendingRespawns() override; + }; } #endif