Merge with main
This commit is contained in:
commit
8a374a4231
9 files changed
+794
-241
No files matched your search
+169
-30
@@ -349,6 +349,7 @@ namespace ZL
|
||||
uint64_t now = SDL_GetTicks64();
|
||||
if (now - lastProjectileFireTime >= static_cast<uint64_t>(projectileCooldownMs)) {
|
||||
lastProjectileFireTime = now;
|
||||
const float projectileSpeed = 60.0f;
|
||||
|
||||
this->fireProjectiles();
|
||||
|
||||
@@ -358,15 +359,21 @@ namespace ZL
|
||||
Eigen::Vector3f centerPos = Environment::shipState.position +
|
||||
Environment::shipState.rotation * Vector3f{ 0, 0.9f, 5.0f };
|
||||
|
||||
Eigen::Quaternionf q(Environment::shipState.rotation);
|
||||
float speedToSend = projectileSpeed + Environment::shipState.velocity;
|
||||
int shotCount = 2;
|
||||
|
||||
std::string fireMsg = "FIRE:" +
|
||||
std::to_string(now) + ":" +
|
||||
std::to_string(centerPos.x()) + ":" +
|
||||
std::to_string(centerPos.y()) + ":" +
|
||||
std::to_string(centerPos.z()) + ":" +
|
||||
std::to_string(worldForward.x()) + ":" +
|
||||
std::to_string(worldForward.y()) + ":" +
|
||||
std::to_string(worldForward.z()) + ":" +
|
||||
"2";
|
||||
std::to_string(q.w()) + ":" +
|
||||
std::to_string(q.x()) + ":" +
|
||||
std::to_string(q.y()) + ":" +
|
||||
std::to_string(q.z()) + ":" +
|
||||
std::to_string(speedToSend) + ":" +
|
||||
std::to_string(shotCount);
|
||||
|
||||
networkClient->Send(fireMsg);
|
||||
}
|
||||
@@ -734,13 +741,13 @@ namespace ZL
|
||||
// Биндим текстуру корабля один раз для всех удаленных игроков (оптимизация батчинга)
|
||||
glBindTexture(GL_TEXTURE_2D, spaceshipTexture->getTexID());
|
||||
|
||||
auto now = std::chrono::system_clock::now();
|
||||
/*auto now = std::chrono::system_clock::now();
|
||||
|
||||
//Apply server delay:
|
||||
now -= std::chrono::milliseconds(CLIENT_DELAY);
|
||||
|
||||
latestRemotePlayers = networkClient->getRemotePlayers();
|
||||
|
||||
*/
|
||||
// Если сервер прислал коробки, применяем их однократно вместо локальной генерации
|
||||
if (!serverBoxesApplied && networkClient) {
|
||||
auto sboxes = networkClient->getServerBoxes();
|
||||
@@ -763,15 +770,9 @@ namespace ZL
|
||||
}
|
||||
|
||||
// Итерируемся по актуальным данным из extrapolateRemotePlayers
|
||||
for (auto const& [id, remotePlayer] : latestRemotePlayers) {
|
||||
|
||||
if (!remotePlayer.canFetchClientStateAtTime(now))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ClientState playerState = remotePlayer.fetchClientStateAtTime(now);
|
||||
for (auto const& [id, remotePlayer] : remotePlayerStates) {
|
||||
|
||||
const ClientState& playerState = remotePlayer;
|
||||
|
||||
renderer.PushMatrix();
|
||||
renderer.LoadIdentity();
|
||||
@@ -811,18 +812,15 @@ namespace ZL
|
||||
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
||||
|
||||
// Берем удаленных игроков
|
||||
latestRemotePlayers = networkClient->getRemotePlayers();
|
||||
//latestRemotePlayers = networkClient->getRemotePlayers();
|
||||
|
||||
auto now = std::chrono::system_clock::now();
|
||||
now -= std::chrono::milliseconds(CLIENT_DELAY);
|
||||
|
||||
for (auto const& [id, remotePlayer] : latestRemotePlayers)
|
||||
for (auto const& [id, remotePlayer] : remotePlayerStates)
|
||||
{
|
||||
if (!remotePlayer.canFetchClientStateAtTime(now))
|
||||
continue;
|
||||
|
||||
ClientState st = remotePlayer.fetchClientStateAtTime(now);
|
||||
|
||||
|
||||
const ClientState& st = remotePlayer;
|
||||
// Позиция корабля в мире
|
||||
Vector3f shipWorld = st.position;
|
||||
|
||||
@@ -872,6 +870,9 @@ namespace ZL
|
||||
lastTickCount = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch()
|
||||
).count();
|
||||
|
||||
lastTickCount = (lastTickCount / 50)*50;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -880,6 +881,8 @@ namespace ZL
|
||||
std::chrono::system_clock::now().time_since_epoch()
|
||||
).count();
|
||||
|
||||
newTickCount = (newTickCount / 50) * 50;
|
||||
|
||||
if (newTickCount - lastTickCount > CONST_TIMER_INTERVAL) {
|
||||
|
||||
size_t delta = newTickCount - lastTickCount;
|
||||
@@ -893,15 +896,7 @@ namespace ZL
|
||||
sparkEmitter.update(static_cast<float>(delta));
|
||||
planetObject.update(static_cast<float>(delta));
|
||||
|
||||
static float pingTimer = 0.0f;
|
||||
pingTimer += delta;
|
||||
if (pingTimer >= 1000.0f) {
|
||||
std::string pingMsg = "UPD:" + std::to_string(now_ms) + ":" + Environment::shipState.formPingMessageContent();
|
||||
|
||||
networkClient->Send(pingMsg);
|
||||
std::cout << "Sending: " << pingMsg << std::endl;
|
||||
pingTimer = 0.0f;
|
||||
}
|
||||
|
||||
//Handle input:
|
||||
|
||||
@@ -957,9 +952,44 @@ namespace ZL
|
||||
std::cout << "Sending: " << msg << std::endl;
|
||||
}
|
||||
|
||||
Environment::shipState.simulate_physics(delta);
|
||||
long long leftoverDelta = delta;
|
||||
while (leftoverDelta > 0)
|
||||
{
|
||||
long long miniDelta = 50;
|
||||
Environment::shipState.simulate_physics(miniDelta);
|
||||
leftoverDelta -= miniDelta;
|
||||
}
|
||||
Environment::inverseShipMatrix = Environment::shipState.rotation.inverse();
|
||||
|
||||
static float pingTimer = 0.0f;
|
||||
pingTimer += delta;
|
||||
if (pingTimer >= 1000.0f) {
|
||||
std::string pingMsg = "UPD:" + std::to_string(now_ms) + ":" + Environment::shipState.formPingMessageContent();
|
||||
|
||||
networkClient->Send(pingMsg);
|
||||
std::cout << "Sending: " << pingMsg << std::endl;
|
||||
pingTimer = 0.0f;
|
||||
}
|
||||
|
||||
|
||||
auto latestRemotePlayers = networkClient->getRemotePlayers();
|
||||
|
||||
std::chrono::system_clock::time_point nowRounded{ std::chrono::milliseconds(newTickCount) };
|
||||
|
||||
|
||||
for (auto const& [id, remotePlayer] : latestRemotePlayers) {
|
||||
|
||||
if (!remotePlayer.canFetchClientStateAtTime(nowRounded))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ClientState playerState = remotePlayer.fetchClientStateAtTime(nowRounded);
|
||||
|
||||
remotePlayerStates[id] = playerState;
|
||||
|
||||
}
|
||||
|
||||
for (auto& p : projectiles) {
|
||||
if (p && p->isActive()) {
|
||||
p->update(static_cast<float>(delta), renderer);
|
||||
@@ -1027,11 +1057,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<Vector3f>());
|
||||
this->deadRemotePlayers.clear();
|
||||
|
||||
Environment::shipState.position = Vector3f{ 0, 0, 45000.f };
|
||||
Environment::shipState.velocity = 0.0f;
|
||||
@@ -1358,7 +1393,37 @@ namespace ZL
|
||||
const float projectileSpeed = 60.0f;
|
||||
const float lifeMs = 5000.0f;
|
||||
const float size = 0.5f;
|
||||
for (const auto& pi : pending) {
|
||||
const std::vector<Vector3f> localOffsets = {
|
||||
Vector3f{ -1.5f, 0.9f, 5.0f },
|
||||
Vector3f{ 1.5f, 0.9f, 5.0f }
|
||||
//Vector3f{},
|
||||
//Vector3f{}
|
||||
};
|
||||
|
||||
Vector3f localForward = { 0, 0, -1 };
|
||||
Vector3f worldForward = pi.rotation * localForward;
|
||||
|
||||
float len = worldForward.norm();
|
||||
if (len <= 1e-6f) {
|
||||
continue;
|
||||
}
|
||||
worldForward /= len;
|
||||
|
||||
Vector3f baseVel = worldForward * pi.velocity;
|
||||
|
||||
for (const auto& off : localOffsets) {
|
||||
Vector3f shotPos = pi.position + (pi.rotation * off);
|
||||
|
||||
for (auto& p : projectiles) {
|
||||
if (!p->isActive()) {
|
||||
p->init(shotPos, baseVel, lifeMs, size, projectileTexture, renderer);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
auto remotePlayersSnapshot = networkClient->getRemotePlayers();
|
||||
for (const auto& pi : pending) {
|
||||
Eigen::Vector3f dir = pi.direction;
|
||||
@@ -1399,6 +1464,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<Vector3f>{ 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<Vector3f>());
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-2
@@ -15,6 +15,8 @@
|
||||
#include <memory>
|
||||
#include <render/TextRenderer.h>
|
||||
|
||||
#include <unordered_set>
|
||||
|
||||
namespace ZL {
|
||||
|
||||
|
||||
@@ -73,7 +75,8 @@ namespace ZL {
|
||||
std::vector<std::string> boxLabels;
|
||||
std::unique_ptr<TextRenderer> textRenderer;
|
||||
|
||||
std::unordered_map<int, ClientStateInterval> latestRemotePlayers;
|
||||
//std::unordered_map<int, ClientStateInterval> latestRemotePlayers;
|
||||
std::unordered_map<int, ClientState> remotePlayerStates;
|
||||
|
||||
float newShipVelocity = 0;
|
||||
|
||||
@@ -116,6 +119,9 @@ namespace ZL {
|
||||
uint64_t lastExplosionTime = 0;
|
||||
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;
|
||||
@@ -124,7 +130,10 @@ namespace ZL {
|
||||
static constexpr float MIN_SCALE = 0.4f;
|
||||
static constexpr float MAX_SCALE = 0.8f;
|
||||
static constexpr float CLOSE_DIST = 600.0f;
|
||||
bool serverBoxesApplied = false;
|
||||
|
||||
std::unordered_set<int> deadRemotePlayers;
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -157,6 +157,16 @@ void ClientState::apply_lag_compensation(std::chrono::system_clock::time_point n
|
||||
deltaMs = std::chrono::duration_cast<std::chrono::milliseconds>(nowTime - lastUpdateServerTime).count();
|
||||
}
|
||||
|
||||
long long deltaMsLeftover = deltaMs;
|
||||
|
||||
while (deltaMsLeftover > 0)
|
||||
{
|
||||
long long miniDelta = 50;
|
||||
simulate_physics(miniDelta);
|
||||
deltaMsLeftover -= miniDelta;
|
||||
}
|
||||
|
||||
/*
|
||||
// 3. Защита от слишком больших скачков (Clamp)
|
||||
// Если лаг более 500мс, ограничиваем его, чтобы избежать резких рывков
|
||||
long long final_lag_ms = deltaMs;//min(deltaMs, 500ll);
|
||||
@@ -165,7 +175,7 @@ void ClientState::apply_lag_compensation(std::chrono::system_clock::time_point n
|
||||
// Доматываем симуляцию на величину задержки
|
||||
// Мы предполагаем, что за это время параметры управления не менялись
|
||||
simulate_physics(final_lag_ms);
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
void ClientState::handle_full_sync(const std::vector<std::string>& parts, int startFrom) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
// WebSocketClient.h
|
||||
#include "NetworkInterface.h"
|
||||
#include <queue>
|
||||
|
||||
@@ -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<ProjectileInfo> getPendingProjectiles();
|
||||
int GetClientId() const override { return 1; }
|
||||
std::vector<ProjectileInfo> getPendingProjectiles() override;
|
||||
|
||||
std::unordered_map<int, ClientStateInterval> getRemotePlayers() override {
|
||||
return std::unordered_map<int, ClientStateInterval>();
|
||||
@@ -26,5 +25,13 @@ namespace ZL {
|
||||
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() override {
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<DeathInfo> getPendingDeaths() override {
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<int> getPendingRespawns() override {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -7,24 +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();
|
||||
};
|
||||
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<int, ClientStateInterval> getRemotePlayers() = 0;
|
||||
struct DeathInfo {
|
||||
int targetId = -1;
|
||||
uint64_t serverTime = 0;
|
||||
Eigen::Vector3f position = Eigen::Vector3f::Zero();
|
||||
int killerId = -1;
|
||||
};
|
||||
|
||||
virtual std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> 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<int, ClientStateInterval> getRemotePlayers() = 0;
|
||||
|
||||
virtual std::vector<ProjectileInfo> getPendingProjectiles() = 0;
|
||||
};
|
||||
virtual std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() = 0;
|
||||
|
||||
virtual std::vector<ProjectileInfo> getPendingProjectiles() = 0;
|
||||
|
||||
virtual std::vector<DeathInfo> getPendingDeaths() = 0;
|
||||
virtual std::vector<int> getPendingRespawns() = 0;
|
||||
virtual int GetClientId() const { return -1; }
|
||||
};
|
||||
}
|
||||
@@ -71,6 +71,20 @@ namespace ZL {
|
||||
return copy;
|
||||
}
|
||||
|
||||
std::vector<DeathInfo> WebSocketClient::getPendingDeaths() {
|
||||
std::lock_guard<std::mutex> lock(deathsMutex_);
|
||||
auto copy = pendingDeaths_;
|
||||
pendingDeaths_.clear();
|
||||
return copy;
|
||||
}
|
||||
|
||||
std::vector<int> WebSocketClient::getPendingRespawns() {
|
||||
std::lock_guard<std::mutex> lock(respawnMutex_);
|
||||
auto copy = pendingRespawns_;
|
||||
pendingRespawns_.clear();
|
||||
return copy;
|
||||
}
|
||||
|
||||
void WebSocketClient::Poll() {
|
||||
std::lock_guard<std::mutex> lock(queueMutex);
|
||||
|
||||
@@ -125,10 +139,29 @@ 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<std::mutex> rLock(respawnMutex_);
|
||||
pendingRespawns_.push_back(respawnedPlayerId);
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> 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, ':');
|
||||
if (parts.size() >= 9) {
|
||||
if (parts.size() >= 10) {
|
||||
try {
|
||||
ProjectileInfo pi;
|
||||
pi.shooterId = std::stoi(parts[1]);
|
||||
@@ -138,16 +171,41 @@ namespace ZL {
|
||||
std::stof(parts[4]),
|
||||
std::stof(parts[5])
|
||||
);
|
||||
pi.direction = Eigen::Vector3f(
|
||||
Eigen::Quaternionf q(
|
||||
std::stof(parts[6]),
|
||||
std::stof(parts[7]),
|
||||
std::stof(parts[8])
|
||||
std::stof(parts[8]),
|
||||
std::stof(parts[9])
|
||||
);
|
||||
pi.rotation = q.toRotationMatrix();
|
||||
|
||||
pi.velocity = std::stof(parts[10]);
|
||||
std::lock_guard<std::mutex> 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<std::mutex> dl(deathsMutex_);
|
||||
pendingDeaths_.push_back(di);
|
||||
}
|
||||
catch (...) {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -198,6 +256,35 @@ namespace ZL {
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.rfind("SNAPSHOT:", 0) == 0) {
|
||||
auto mainParts = split(msg.substr(9), '|'); // Отсекаем "SNAPSHOT:" и делим по игрокам
|
||||
if (mainParts.empty()) continue;
|
||||
|
||||
uint64_t serverTimestamp = std::stoull(mainParts[0]);
|
||||
std::chrono::system_clock::time_point serverTime{ std::chrono::milliseconds(serverTimestamp) };
|
||||
|
||||
for (size_t i = 1; i < mainParts.size(); ++i) {
|
||||
auto playerParts = split(mainParts[i], ':');
|
||||
if (playerParts.size() < 15) continue; // ID + 14 полей ClientState
|
||||
|
||||
int rId = std::stoi(playerParts[0]);
|
||||
if (rId == clientId) continue; // Свое состояние игрок знает лучше всех (Client Side Prediction)
|
||||
|
||||
ClientState remoteState;
|
||||
remoteState.id = rId;
|
||||
remoteState.lastUpdateServerTime = serverTime;
|
||||
|
||||
// Используем твой handle_full_sync, начиная со 2-го индекса (пропускаем ID в playerParts)
|
||||
remoteState.handle_full_sync(playerParts, 1);
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> pLock(playersMutex);
|
||||
remotePlayers[rId].add_state(remoteState);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
void WebSocketClient::Send(const std::string& message) {
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
#ifdef NETWORK
|
||||
|
||||
// WebSocketClient.h
|
||||
#include "NetworkInterface.h"
|
||||
#include <queue>
|
||||
#include <boost/beast/core.hpp>
|
||||
@@ -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<boost::beast::websocket::stream<boost::beast::tcp_stream>> ws_;
|
||||
boost::beast::flat_buffer buffer_;
|
||||
// Объекты переехали в члены класса
|
||||
std::unique_ptr<boost::beast::websocket::stream<boost::beast::tcp_stream>> ws_;
|
||||
boost::beast::flat_buffer buffer_;
|
||||
|
||||
std::queue<std::string> messageQueue;
|
||||
std::mutex queueMutex; // Защита для messageQueue
|
||||
std::queue<std::string> messageQueue;
|
||||
std::mutex queueMutex; // Защита для messageQueue
|
||||
|
||||
std::queue<std::shared_ptr<std::string>> writeQueue_;
|
||||
bool isWriting_ = false;
|
||||
std::mutex writeMutex_; // Отдельный мьютекс для очереди записи
|
||||
std::queue<std::shared_ptr<std::string>> writeQueue_;
|
||||
bool isWriting_ = false;
|
||||
std::mutex writeMutex_; // Отдельный мьютекс для очереди записи
|
||||
|
||||
bool connected = false;
|
||||
int clientId = -1;
|
||||
bool connected = false;
|
||||
int clientId = -1;
|
||||
|
||||
std::unordered_map<int, ClientStateInterval> remotePlayers;
|
||||
std::mutex playersMutex;
|
||||
std::unordered_map<int, ClientStateInterval> remotePlayers;
|
||||
std::mutex playersMutex;
|
||||
|
||||
// Серверные коробки
|
||||
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> serverBoxes_;
|
||||
std::mutex boxesMutex;
|
||||
// Серверные коробки
|
||||
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> serverBoxes_;
|
||||
std::mutex boxesMutex;
|
||||
|
||||
std::vector<ProjectileInfo> pendingProjectiles_;
|
||||
std::mutex projMutex_;
|
||||
std::vector<ProjectileInfo> pendingProjectiles_;
|
||||
std::mutex projMutex_;
|
||||
|
||||
void startAsyncRead();
|
||||
void processIncomingMessage(const std::string& msg);
|
||||
std::vector<DeathInfo> pendingDeaths_;
|
||||
std::mutex deathsMutex_;
|
||||
|
||||
public:
|
||||
explicit WebSocketClient(boost::asio::io_context& ioc) : ioc_(ioc) {}
|
||||
std::vector<int> 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<int, ClientStateInterval> getRemotePlayers() override {
|
||||
std::lock_guard<std::mutex> lock(playersMutex);
|
||||
return remotePlayers;
|
||||
}
|
||||
void Send(const std::string& message) override;
|
||||
void doWrite();
|
||||
|
||||
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() override {
|
||||
std::lock_guard<std::mutex> lock(boxesMutex);
|
||||
return serverBoxes_;
|
||||
}
|
||||
bool IsConnected() const override { return connected; }
|
||||
int GetClientId() const override { return clientId; }
|
||||
|
||||
std::vector<ProjectileInfo> getPendingProjectiles() override;
|
||||
};
|
||||
std::unordered_map<int, ClientStateInterval> getRemotePlayers() override {
|
||||
std::lock_guard<std::mutex> lock(playersMutex);
|
||||
return remotePlayers;
|
||||
}
|
||||
|
||||
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() override {
|
||||
std::lock_guard<std::mutex> lock(boxesMutex);
|
||||
return serverBoxes_;
|
||||
}
|
||||
|
||||
std::vector<ProjectileInfo> getPendingProjectiles() override;
|
||||
std::vector<DeathInfo> getPendingDeaths() override;
|
||||
std::vector<int> getPendingRespawns() override;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
Reference in new issue
Block a user