Fixing bug, implementing delays, remove WORLD_UPDATE
This commit is contained in:
1 parent
3c55b59c8d
commit
64385ba15c
7 files changed
+398
-136
No files matched your search
@@ -13,6 +13,9 @@ constexpr float ANGULAR_ACCEL = 0.005f * 1000.0f;
|
||||
constexpr float SHIP_ACCEL = 1.0f * 1000.0f;
|
||||
constexpr float ROTATION_SENSITIVITY = 0.002f;
|
||||
|
||||
constexpr long long SERVER_DELAY = 0; //ms
|
||||
constexpr long long CLIENT_DELAY = 1500; //ms
|
||||
constexpr long long CUTOFF_TIME = 5000; //ms
|
||||
struct ClientState {
|
||||
int id = 0;
|
||||
Eigen::Vector3f position = { 0, 0, 45000.0f };
|
||||
@@ -27,13 +30,6 @@ struct ClientState {
|
||||
std::chrono::system_clock::time_point lastUpdateServerTime;
|
||||
|
||||
void simulate_physics(size_t delta) {
|
||||
// Константы из Game.cpp, приведенные к секундам (умножаем на 1000)
|
||||
//const float ANGULAR_ACCEL = 0.005f * 1000.0f;
|
||||
//const float ROTATION_SENSITIVITY = 0.002f;
|
||||
//const float SHIP_ACCEL = 1.0f * 1000.0f; // CONST_ACCELERATION
|
||||
|
||||
// 1. Вычисляем targetAngularVelocity на лету из дискретных значений
|
||||
|
||||
if (discreteMag > 0.01f)
|
||||
{
|
||||
float rad = static_cast<float>(discreteAngle) * static_cast<float>(M_PI) / 180.0f;
|
||||
@@ -93,52 +89,6 @@ struct ClientState {
|
||||
//std::cout << "NOT Rotating ship. speedScale=" << speedScale << " discreteMag=" << discreteMag << "\n";
|
||||
}
|
||||
|
||||
/*
|
||||
Eigen::Vector3f targetAngularVelocity = Eigen::Vector3f::Zero();
|
||||
|
||||
if (discreteMag > 0.001f) {
|
||||
float rad = static_cast<float>(discreteAngle) * static_cast<float>(M_PI) / 180.0f;
|
||||
// Направление из угла (как в твоем обновленном клиентском коде)
|
||||
Eigen::Vector3f targetDir(sinf(rad), cosf(rad), 0.0f);
|
||||
targetAngularVelocity = targetDir * discreteMag;
|
||||
}
|
||||
|
||||
// 2. Линейное изменение текущей угловой скорости к вычисленной цели
|
||||
Eigen::Vector3f diffVel = targetAngularVelocity - currentAngularVelocity;
|
||||
float diffLen = diffVel.norm();
|
||||
|
||||
if (diffLen > 0.0001f) {
|
||||
float maxChange = ANGULAR_ACCEL * dt_s;
|
||||
if (diffLen <= maxChange) {
|
||||
currentAngularVelocity = targetAngularVelocity;
|
||||
}
|
||||
else {
|
||||
currentAngularVelocity += (diffVel / diffLen) * maxChange;
|
||||
}
|
||||
}
|
||||
else if (discreteMag < 0.001f && currentAngularVelocity.norm() > 0.0001f) {
|
||||
// Если джойстик отпущен, используем ту же логику торможения (или ANGULAR_ACCEL)
|
||||
float currentSpeed = currentAngularVelocity.norm();
|
||||
float drop = ANGULAR_ACCEL * dt_s;
|
||||
if (currentSpeed <= drop) {
|
||||
currentAngularVelocity = Eigen::Vector3f::Zero();
|
||||
}
|
||||
else {
|
||||
currentAngularVelocity -= (currentAngularVelocity / currentSpeed) * drop;
|
||||
}
|
||||
}*/
|
||||
|
||||
/*
|
||||
// 3. Применение вращения к матрице (Интеграция)
|
||||
float speedScale = currentAngularVelocity.norm();
|
||||
if (speedScale > 0.0001f) {
|
||||
float deltaAlpha = speedScale * dt_s * ROTATION_SENSITIVITY;
|
||||
Eigen::Vector3f axis = currentAngularVelocity.normalized();
|
||||
|
||||
Eigen::Quaternionf rotateQuat(Eigen::AngleAxisf(deltaAlpha, axis));
|
||||
rotation = rotation * rotateQuat.toRotationMatrix();
|
||||
}*/
|
||||
|
||||
// 4. Линейное изменение линейной скорости
|
||||
float shipDesiredVelocity = selectedVelocity * 100.f;
|
||||
|
||||
@@ -177,7 +127,7 @@ struct ClientState {
|
||||
|
||||
// 3. Защита от слишком больших скачков (Clamp)
|
||||
// Если лаг более 500мс, ограничиваем его, чтобы избежать резких рывков
|
||||
long long final_lag_ms = min(deltaMs, 500ll);
|
||||
long long final_lag_ms = deltaMs;//min(deltaMs, 500ll);
|
||||
|
||||
if (final_lag_ms > 0) {
|
||||
// Доматываем симуляцию на величину задержки
|
||||
@@ -186,7 +136,7 @@ struct ClientState {
|
||||
}
|
||||
}
|
||||
|
||||
std::string get_state_string(int id) {
|
||||
std::string get_state_string() {
|
||||
// Используем кватернион для передачи вращения (4 числа вместо 9)
|
||||
Eigen::Quaternionf q(rotation);
|
||||
|
||||
|
||||
@@ -1,10 +1,70 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include "ClientState.h"
|
||||
|
||||
// NetworkInterface.h - Èíòåðôåéñ äëÿ ðàçíûõ òèïîâ ñîåäèíåíèé
|
||||
namespace ZL {
|
||||
|
||||
struct RemotePlayer
|
||||
{
|
||||
std::vector<ClientState> timedRemoteStates;
|
||||
|
||||
bool canFetchClientStateAtTime(std::chrono::system_clock::time_point targetTime) const
|
||||
{
|
||||
if (timedRemoteStates.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (timedRemoteStates[0].lastUpdateServerTime > targetTime)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
ClientState fetchClientStateAtTime(std::chrono::system_clock::time_point targetTime) const {
|
||||
|
||||
ClientState closestState;
|
||||
|
||||
if (timedRemoteStates.empty())
|
||||
{
|
||||
throw std::runtime_error("No timed client states available");
|
||||
return closestState;
|
||||
}
|
||||
if (timedRemoteStates[0].lastUpdateServerTime > targetTime)
|
||||
{
|
||||
throw std::runtime_error("Found time but it is in future");
|
||||
return closestState;
|
||||
}
|
||||
if (timedRemoteStates.size() == 1)
|
||||
{
|
||||
closestState = timedRemoteStates[0];
|
||||
closestState.apply_lag_compensation(targetTime);
|
||||
return closestState;
|
||||
}
|
||||
|
||||
|
||||
for (size_t i = 0; i < timedRemoteStates.size() - 1; ++i)
|
||||
{
|
||||
const auto& earlierState = timedRemoteStates[i];
|
||||
const auto& laterState = timedRemoteStates[i + 1];
|
||||
if (earlierState.lastUpdateServerTime <= targetTime && laterState.lastUpdateServerTime >= targetTime)
|
||||
{
|
||||
closestState = earlierState;
|
||||
closestState.apply_lag_compensation(targetTime);
|
||||
return closestState;
|
||||
}
|
||||
}
|
||||
|
||||
closestState = timedRemoteStates[timedRemoteStates.size() - 1];
|
||||
closestState.apply_lag_compensation(targetTime);
|
||||
return closestState;
|
||||
}
|
||||
};
|
||||
|
||||
class INetworkClient {
|
||||
public:
|
||||
virtual ~INetworkClient() = default;
|
||||
@@ -12,7 +72,6 @@ namespace ZL {
|
||||
virtual void Send(const std::string& message) = 0;
|
||||
virtual bool IsConnected() const = 0;
|
||||
virtual void Poll() = 0; // Äëÿ îáðàáîòêè âõîäÿùèõ ïàêåòîâ
|
||||
virtual std::unordered_map<int, ClientState> getRemotePlayers() = 0;
|
||||
virtual void updateRemotePlayers(const std::unordered_map<int, ClientState>& newRemotePlayers) = 0;
|
||||
virtual std::unordered_map<int, RemotePlayer> getRemotePlayers() = 0;
|
||||
};
|
||||
}
|
||||
+120
-33
@@ -73,10 +73,15 @@ namespace ZL {
|
||||
|
||||
auto nowTime = std::chrono::system_clock::now();
|
||||
|
||||
//Apply server delay:
|
||||
nowTime -= std::chrono::milliseconds(CLIENT_DELAY);
|
||||
|
||||
auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
nowTime.time_since_epoch()
|
||||
).count();
|
||||
|
||||
|
||||
|
||||
std::string msg = messageQueue.front();
|
||||
messageQueue.pop();
|
||||
|
||||
@@ -88,6 +93,95 @@ namespace ZL {
|
||||
std::string subType = parts[2];
|
||||
uint64_t sentTime = std::stoull(parts[3]);
|
||||
|
||||
ClientState remoteState;
|
||||
remoteState.id = remoteId;
|
||||
|
||||
std::chrono::system_clock::time_point uptime_timepoint{ std::chrono::duration_cast<std::chrono::system_clock::time_point::duration>(std::chrono::milliseconds(sentTime)) };
|
||||
remoteState.lastUpdateServerTime = uptime_timepoint;
|
||||
|
||||
if (subType == "VEL") {
|
||||
remoteState.selectedVelocity = std::stoi(parts[4]);
|
||||
int startFrom = 5;
|
||||
remoteState.position = { std::stof(parts[startFrom]), std::stof(parts[startFrom + 1]), std::stof(parts[startFrom + 2]) };
|
||||
Eigen::Quaternionf q(
|
||||
std::stof(parts[startFrom + 3]),
|
||||
std::stof(parts[startFrom + 4]),
|
||||
std::stof(parts[startFrom + 5]),
|
||||
std::stof(parts[startFrom + 6]));
|
||||
remoteState.rotation = q.toRotationMatrix();
|
||||
|
||||
remoteState.currentAngularVelocity = Eigen::Vector3f{
|
||||
std::stof(parts[startFrom + 7]),
|
||||
std::stof(parts[startFrom + 8]),
|
||||
std::stof(parts[startFrom + 9]) };
|
||||
remoteState.velocity = std::stof(parts[startFrom + 10]);
|
||||
remoteState.selectedVelocity = std::stoi(parts[startFrom + 11]);
|
||||
remoteState.discreteMag = std::stof(parts[startFrom + 12]);
|
||||
remoteState.discreteAngle = std::stoi(parts[startFrom + 13]);
|
||||
|
||||
}
|
||||
else if (subType == "ROT") {
|
||||
remoteState.discreteAngle = std::stoi(parts[4]);
|
||||
remoteState.discreteMag = std::stof(parts[5]);
|
||||
int startFrom = 6;
|
||||
remoteState.position = { std::stof(parts[startFrom]), std::stof(parts[startFrom + 1]), std::stof(parts[startFrom + 2]) };
|
||||
Eigen::Quaternionf q(
|
||||
std::stof(parts[startFrom + 3]),
|
||||
std::stof(parts[startFrom + 4]),
|
||||
std::stof(parts[startFrom + 5]),
|
||||
std::stof(parts[startFrom + 6]));
|
||||
remoteState.rotation = q.toRotationMatrix();
|
||||
|
||||
remoteState.currentAngularVelocity = Eigen::Vector3f{
|
||||
std::stof(parts[startFrom + 7]),
|
||||
std::stof(parts[startFrom + 8]),
|
||||
std::stof(parts[startFrom + 9]) };
|
||||
remoteState.velocity = std::stof(parts[startFrom + 10]);
|
||||
remoteState.selectedVelocity = std::stoi(parts[startFrom + 11]);
|
||||
remoteState.discreteMag = std::stof(parts[startFrom + 12]);
|
||||
remoteState.discreteAngle = std::stoi(parts[startFrom + 13]);
|
||||
}
|
||||
else if (subType == "PING") {
|
||||
//remoteState.discreteAngle = std::stoi(parts[4]);
|
||||
//remoteState.discreteMag = std::stof(parts[5]);
|
||||
int startFrom = 4;
|
||||
remoteState.position = { std::stof(parts[startFrom]), std::stof(parts[startFrom + 1]), std::stof(parts[startFrom + 2]) };
|
||||
Eigen::Quaternionf q(
|
||||
std::stof(parts[startFrom + 3]),
|
||||
std::stof(parts[startFrom + 4]),
|
||||
std::stof(parts[startFrom + 5]),
|
||||
std::stof(parts[startFrom + 6]));
|
||||
remoteState.rotation = q.toRotationMatrix();
|
||||
|
||||
remoteState.currentAngularVelocity = Eigen::Vector3f{
|
||||
std::stof(parts[startFrom + 7]),
|
||||
std::stof(parts[startFrom + 8]),
|
||||
std::stof(parts[startFrom + 9]) };
|
||||
remoteState.velocity = std::stof(parts[startFrom + 10]);
|
||||
remoteState.selectedVelocity = std::stoi(parts[startFrom + 11]);
|
||||
remoteState.discreteMag = std::stof(parts[startFrom + 12]);
|
||||
remoteState.discreteAngle = std::stoi(parts[startFrom + 13]);
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> pLock(playersMutex);
|
||||
auto& rp = remotePlayers[remoteId];
|
||||
rp.timedRemoteStates.push_back(remoteState);
|
||||
|
||||
auto cutoff_time = nowTime - std::chrono::milliseconds(CUTOFF_TIME);
|
||||
|
||||
while (rp.timedRemoteStates.size() > 0 && rp.timedRemoteStates[0].lastUpdateServerTime < cutoff_time)
|
||||
{
|
||||
rp.timedRemoteStates.erase(rp.timedRemoteStates.begin());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
std::lock_guard<std::mutex> pLock(playersMutex);
|
||||
if (remotePlayers.count(remoteId)) {
|
||||
auto& rp = remotePlayers[remoteId];
|
||||
@@ -111,26 +205,6 @@ namespace ZL {
|
||||
rp.selectedVelocity = std::stoi(parts[startFrom + 11]);
|
||||
rp.discreteMag = std::stof(parts[startFrom + 12]);
|
||||
rp.discreteAngle = std::stoi(parts[startFrom + 13]);
|
||||
/*position = { std::stof(parts[startFrom]), std::stof(parts[startFrom+1]), std::stof(parts[startFrom+2]) };
|
||||
|
||||
// Äëÿ âðàùåíèÿ êëèåíò äîëæåí ïðèñëàòü ëèáî êâàòåðíèîí, ëèáî óãëû Ýéëåðà.
|
||||
// Ïðåäïîëîæèì, ìû ïåðåäàåì 4 çíà÷åíèÿ êâàòåðíèîíà äëÿ ýêîíîìèè:
|
||||
Eigen::Quaternionf q(
|
||||
std::stof(parts[startFrom+3]),
|
||||
std::stof(parts[startFrom+4]),
|
||||
std::stof(parts[startFrom+5]),
|
||||
std::stof(parts[startFrom+6]));
|
||||
rotation = q.toRotationMatrix();
|
||||
|
||||
currentAngularVelocity = Eigen::Vector3f{
|
||||
std::stof(parts[startFrom+7]),
|
||||
std::stof(parts[startFrom+8]),
|
||||
std::stof(parts[startFrom+9]) };
|
||||
velocity = std::stof(parts[startFrom+10]);
|
||||
selectedVelocity = std::stoi(parts[startFrom+11]);
|
||||
discreteMag = std::stof(parts[startFrom+12]);
|
||||
discreteAngle = std::stoi(parts[15]);
|
||||
*/
|
||||
|
||||
}
|
||||
else if (subType == "ROT") {
|
||||
@@ -174,7 +248,7 @@ namespace ZL {
|
||||
// Îáíîâëÿåì ìåòêó âðåìåíè, ÷òîáû îáû÷íàÿ ýêñòðàïîëÿöèÿ â Game.cpp
|
||||
// çíàëà, ÷òî ñîñòîÿíèå óæå àêòóàëüíî íà ìîìåíò now_ms
|
||||
rp.lastUpdateServerTime = nowTime;
|
||||
}
|
||||
}*/
|
||||
}
|
||||
else if (msg.rfind("WORLD_UPDATE|", 0) == 0) {
|
||||
parseWorldUpdate(msg, nowTime);
|
||||
@@ -208,24 +282,37 @@ namespace ZL {
|
||||
|
||||
void WebSocketClient::updateRemotePlayer(int id, const std::vector<std::string>& vals, uint64_t serverTime, std::chrono::system_clock::time_point now_ms) {
|
||||
|
||||
auto& rp = remotePlayers[id];
|
||||
rp.id = id;
|
||||
//auto& rp = remotePlayers[id];
|
||||
|
||||
rp.position = { std::stof(vals[1]), std::stof(vals[2]), std::stof(vals[3]) };
|
||||
rp.rotation = Eigen::Quaternionf(std::stof(vals[4]), std::stof(vals[5]), std::stof(vals[6]), std::stof(vals[7]));
|
||||
ClientState remoteState;
|
||||
|
||||
remoteState.id = id;
|
||||
|
||||
remoteState.position = { std::stof(vals[1]), std::stof(vals[2]), std::stof(vals[3]) };
|
||||
remoteState.rotation = Eigen::Quaternionf(std::stof(vals[4]), std::stof(vals[5]), std::stof(vals[6]), std::stof(vals[7]));
|
||||
|
||||
// 3. Ñîõðàíÿåì îñòàëüíûå ôèçè÷åñêèå ïàðàìåòðû (äëÿ ýêñòðàïîëÿöèè èëè îòëàäêè)
|
||||
rp.velocity = std::stof(vals[8]);
|
||||
rp.currentAngularVelocity = { std::stof(vals[9]), std::stof(vals[10]), std::stof(vals[11]) };
|
||||
rp.selectedVelocity = std::stoi(vals[12]);
|
||||
rp.discreteMag = std::stof(vals[13]);
|
||||
rp.discreteAngle = std::stoi(vals[14]);
|
||||
remoteState.velocity = std::stof(vals[8]);
|
||||
remoteState.currentAngularVelocity = { std::stof(vals[9]), std::stof(vals[10]), std::stof(vals[11]) };
|
||||
remoteState.selectedVelocity = std::stoi(vals[12]);
|
||||
remoteState.discreteMag = std::stof(vals[13]);
|
||||
remoteState.discreteAngle = std::stoi(vals[14]);
|
||||
std::chrono::system_clock::time_point uptime_timepoint{ std::chrono::duration_cast<std::chrono::system_clock::time_point::duration>(std::chrono::milliseconds(serverTime)) };
|
||||
|
||||
std::cout << "PING Received discreteMag=" << rp.discreteMag << std::endl;
|
||||
//std::cout << "PING Received discreteMag=" << rp.discreteMag << std::endl;
|
||||
|
||||
rp.lastUpdateServerTime = uptime_timepoint;
|
||||
rp.apply_lag_compensation(now_ms);
|
||||
remoteState.lastUpdateServerTime = uptime_timepoint;
|
||||
|
||||
auto& rp = remotePlayers[id];
|
||||
rp.timedRemoteStates.push_back(remoteState);
|
||||
|
||||
auto cutoff_time = now_ms - std::chrono::milliseconds(CUTOFF_TIME);
|
||||
|
||||
while (rp.timedRemoteStates.size() > 0 && rp.timedRemoteStates[0].lastUpdateServerTime < cutoff_time)
|
||||
{
|
||||
rp.timedRemoteStates.erase(rp.timedRemoteStates.begin());
|
||||
}
|
||||
//rp.apply_lag_compensation(now_ms);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
|
||||
namespace ZL {
|
||||
|
||||
class WebSocketClient : public INetworkClient {
|
||||
private:
|
||||
// Ïåðåèñïîëüçóåì io_context èç TaskManager
|
||||
@@ -28,7 +29,7 @@ namespace ZL {
|
||||
bool connected = false;
|
||||
int clientId = -1;
|
||||
|
||||
std::unordered_map<int, ClientState> remotePlayers;
|
||||
std::unordered_map<int, RemotePlayer> remotePlayers;
|
||||
std::mutex playersMutex;
|
||||
|
||||
void startAsyncRead();
|
||||
@@ -49,18 +50,9 @@ namespace ZL {
|
||||
bool IsConnected() const override { return connected; }
|
||||
int GetClientId() const { return clientId; }
|
||||
|
||||
std::unordered_map<int, ClientState> getRemotePlayers() override {
|
||||
std::unordered_map<int, RemotePlayer> getRemotePlayers() override {
|
||||
std::lock_guard<std::mutex> lock(playersMutex);
|
||||
return remotePlayers;
|
||||
}
|
||||
|
||||
void updateRemotePlayers(const std::unordered_map<int, ClientState>& newRemotePlayers) override {
|
||||
std::lock_guard<std::mutex> lock(playersMutex);
|
||||
|
||||
for (const auto& [id, newPlayer] : newRemotePlayers) {
|
||||
remotePlayers[id] = newPlayer;
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user