Clean up server
This commit is contained in:
parent
c35e093cc5
commit
8528b4dc90
@ -26,6 +26,7 @@ add_subdirectory("${BOOST_SRC_DIR}/libs/predef" boost-predef-build EXCLUDE_FROM_
|
|||||||
|
|
||||||
# Исполняемый файл сервера
|
# Исполняемый файл сервера
|
||||||
add_executable(Server
|
add_executable(Server
|
||||||
|
server.h
|
||||||
server.cpp
|
server.cpp
|
||||||
../src/network/ClientState.h
|
../src/network/ClientState.h
|
||||||
../src/network/ClientState.cpp
|
../src/network/ClientState.cpp
|
||||||
|
|||||||
@ -1,44 +1,11 @@
|
|||||||
#include <boost/beast/core.hpp>
|
#include "server.h"
|
||||||
#include <boost/beast/websocket.hpp>
|
#include <boost/beast/websocket.hpp>
|
||||||
#include <boost/asio/ip/tcp.hpp>
|
#include <boost/asio/ip/tcp.hpp>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <string>
|
|
||||||
#include <memory>
|
|
||||||
#include <vector>
|
|
||||||
#include <mutex>
|
|
||||||
#include <map>
|
|
||||||
#include <queue>
|
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <Eigen/Dense>
|
|
||||||
#define _USE_MATH_DEFINES
|
|
||||||
#include <math.h>
|
|
||||||
#include "../src/network/ClientState.h"
|
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <unordered_set>
|
|
||||||
|
|
||||||
namespace beast = boost::beast;
|
|
||||||
namespace http = beast::http;
|
|
||||||
namespace websocket = beast::websocket;
|
|
||||||
namespace net = boost::asio;
|
|
||||||
using tcp = net::ip::tcp;
|
|
||||||
static constexpr float kWorldZOffset = 45000.0f;
|
|
||||||
static const Eigen::Vector3f kWorldOffset(0.0f, 0.0f, kWorldZOffset);
|
|
||||||
|
|
||||||
static constexpr float kShipRadius = 15.0f;
|
|
||||||
static constexpr float kSpawnShipMargin = 25.0f;
|
|
||||||
static constexpr float kSpawnBoxMargin = 15.0f;
|
|
||||||
static constexpr float kSpawnZJitter = 60.0f;
|
|
||||||
|
|
||||||
Eigen::Vector3f PickSafeSpawnPos(int forPlayerId);
|
|
||||||
|
|
||||||
struct DeathInfo {
|
|
||||||
int targetId = -1;
|
|
||||||
uint64_t serverTime = 0;
|
|
||||||
Eigen::Vector3f position = Eigen::Vector3f::Zero();
|
|
||||||
int killerId = -1;
|
|
||||||
};
|
|
||||||
|
|
||||||
std::vector<std::string> split(const std::string& s, char delimiter) {
|
std::vector<std::string> split(const std::string& s, char delimiter) {
|
||||||
std::vector<std::string> tokens;
|
std::vector<std::string> tokens;
|
||||||
@ -50,75 +17,18 @@ std::vector<std::string> split(const std::string& s, char delimiter) {
|
|||||||
return tokens;
|
return tokens;
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ServerBox {
|
Session::Session(Server& server, tcp::socket&& socket, int id)
|
||||||
Eigen::Vector3f position;
|
: server_(server)
|
||||||
Eigen::Matrix3f rotation;
|
, ws_(std::move(socket))
|
||||||
float collisionRadius = 2.0f;
|
, id_(id) {
|
||||||
bool destroyed = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct Projectile {
|
|
||||||
int shooterId = -1;
|
|
||||||
uint64_t spawnMs = 0;
|
|
||||||
Eigen::Vector3f pos;
|
|
||||||
Eigen::Vector3f vel;
|
|
||||||
float lifeMs = PROJECTILE_LIFE;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct BoxDestroyedInfo {
|
|
||||||
int boxIndex = -1;
|
|
||||||
uint64_t serverTime = 0;
|
|
||||||
Eigen::Vector3f position = Eigen::Vector3f::Zero();
|
|
||||||
int destroyedBy = -1;
|
|
||||||
};
|
|
||||||
|
|
||||||
std::vector<BoxDestroyedInfo> g_boxDestructions;
|
|
||||||
std::mutex g_boxDestructions_mutex;
|
|
||||||
|
|
||||||
std::vector<ServerBox> g_serverBoxes;
|
|
||||||
std::mutex g_boxes_mutex;
|
|
||||||
|
|
||||||
std::vector<std::shared_ptr<class Session>> g_sessions;
|
|
||||||
std::mutex g_sessions_mutex;
|
|
||||||
|
|
||||||
std::vector<Projectile> g_projectiles;
|
|
||||||
std::mutex g_projectiles_mutex;
|
|
||||||
|
|
||||||
std::unordered_set<int> g_dead_players;
|
|
||||||
std::mutex g_dead_mutex;
|
|
||||||
|
|
||||||
class Session;
|
|
||||||
|
|
||||||
void broadcastToAll(const std::string& message);
|
|
||||||
|
|
||||||
class Session : public std::enable_shared_from_this<Session> {
|
|
||||||
websocket::stream<beast::tcp_stream> ws_;
|
|
||||||
beast::flat_buffer buffer_;
|
|
||||||
int id_;
|
|
||||||
bool is_writing_ = false;
|
|
||||||
std::queue<std::shared_ptr<std::string>> writeQueue_;
|
|
||||||
std::mutex writeMutex_;
|
|
||||||
|
|
||||||
public:
|
|
||||||
ClientStateInterval timedClientStates;
|
|
||||||
bool joined_ = false;
|
|
||||||
|
|
||||||
bool hasReservedSpawn_ = false;
|
|
||||||
Eigen::Vector3f reservedSpawn_ = Eigen::Vector3f(0.0f, 0.0f, kWorldZOffset);
|
|
||||||
|
|
||||||
std::string nickname = "Player";
|
|
||||||
int shipType = 0;
|
|
||||||
|
|
||||||
explicit Session(tcp::socket&& socket, int id)
|
|
||||||
: ws_(std::move(socket)), id_(id) {
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int get_id() const { return id_; }
|
int Session::get_id() const { return id_; }
|
||||||
|
|
||||||
bool hasSpawnReserved() const { return hasReservedSpawn_; }
|
bool Session::hasSpawnReserved() const { return hasReservedSpawn_; }
|
||||||
const Eigen::Vector3f& reservedSpawn() const { return reservedSpawn_; }
|
const Eigen::Vector3f& Session::reservedSpawn() const { return reservedSpawn_; }
|
||||||
|
|
||||||
bool fetchStateAtTime(std::chrono::system_clock::time_point targetTime, ClientState& outState) const {
|
bool Session::fetchStateAtTime(std::chrono::system_clock::time_point targetTime, ClientState& outState) const {
|
||||||
if (timedClientStates.canFetchClientStateAtTime(targetTime)) {
|
if (timedClientStates.canFetchClientStateAtTime(targetTime)) {
|
||||||
outState = timedClientStates.fetchClientStateAtTime(targetTime);
|
outState = timedClientStates.fetchClientStateAtTime(targetTime);
|
||||||
return true;
|
return true;
|
||||||
@ -126,7 +36,7 @@ public:
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
void send_message(const std::string& msg) {
|
void Session::send_message(const std::string& msg) {
|
||||||
auto ss = std::make_shared<std::string>(msg);
|
auto ss = std::make_shared<std::string>(msg);
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(writeMutex_);
|
std::lock_guard<std::mutex> lock(writeMutex_);
|
||||||
@ -135,10 +45,10 @@ public:
|
|||||||
doWrite();
|
doWrite();
|
||||||
}
|
}
|
||||||
|
|
||||||
void run() {
|
void Session::run() {
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
std::lock_guard<std::mutex> lock(server_.g_sessions_mutex);
|
||||||
g_sessions.push_back(shared_from_this());
|
server_.g_sessions.push_back(shared_from_this());
|
||||||
}
|
}
|
||||||
|
|
||||||
ws_.async_accept([self = shared_from_this()](beast::error_code ec) {
|
ws_.async_accept([self = shared_from_this()](beast::error_code ec) {
|
||||||
@ -148,7 +58,7 @@ public:
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
bool IsMessageValid(const std::string& fullMessage) {
|
bool Session::IsMessageValid(const std::string& fullMessage) {
|
||||||
#ifdef ENABLE_NETWORK_CHECKSUM
|
#ifdef ENABLE_NETWORK_CHECKSUM
|
||||||
size_t hashPos = fullMessage.find("#hash:");
|
size_t hashPos = fullMessage.find("#hash:");
|
||||||
if (hashPos == std::string::npos) {
|
if (hashPos == std::string::npos) {
|
||||||
@ -170,16 +80,14 @@ public:
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
private:
|
void Session::sendBoxesToClient() {
|
||||||
|
std::lock_guard<std::mutex> lock(server_.g_boxes_mutex);
|
||||||
void sendBoxesToClient() {
|
|
||||||
std::lock_guard<std::mutex> lock(g_boxes_mutex);
|
|
||||||
|
|
||||||
std::string boxMsg = "BOXES:";
|
std::string boxMsg = "BOXES:";
|
||||||
bool first = true;
|
bool first = true;
|
||||||
|
|
||||||
for (size_t i = 0; i < g_serverBoxes.size(); ++i) {
|
for (size_t i = 0; i < server_.g_serverBoxes.size(); ++i) {
|
||||||
const auto& box = g_serverBoxes[i];
|
const auto& box = server_.g_serverBoxes[i];
|
||||||
|
|
||||||
if (box.destroyed) continue;
|
if (box.destroyed) continue;
|
||||||
|
|
||||||
@ -199,14 +107,11 @@ private:
|
|||||||
"0";
|
"0";
|
||||||
}
|
}
|
||||||
|
|
||||||
// Если все коробки уничтожены — отправится просто "BOXES:" (это нормально)
|
|
||||||
send_message(boxMsg);
|
send_message(boxMsg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public:
|
void Session::init()
|
||||||
|
|
||||||
void init()
|
|
||||||
{
|
{
|
||||||
sendBoxesToClient();
|
sendBoxesToClient();
|
||||||
|
|
||||||
@ -224,23 +129,17 @@ public:
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
ClientState get_latest_state(std::chrono::system_clock::time_point now) {
|
ClientState Session::get_latest_state(std::chrono::system_clock::time_point now) {
|
||||||
if (timedClientStates.timedStates.empty()) {
|
if (timedClientStates.timedStates.empty()) {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. Берем самое последнее известное состояние
|
|
||||||
ClientState latest = timedClientStates.timedStates.back();
|
ClientState latest = timedClientStates.timedStates.back();
|
||||||
|
|
||||||
// 3. Применяем компенсацию лага (экстраполяцию).
|
|
||||||
// Функция внутри использует simulate_physics, чтобы переместить объект
|
|
||||||
// из точки lastUpdateServerTime в точку now.
|
|
||||||
latest.apply_lag_compensation(now);
|
latest.apply_lag_compensation(now);
|
||||||
|
|
||||||
return latest;
|
return latest;
|
||||||
}
|
}
|
||||||
|
|
||||||
void doWrite() {
|
void Session::doWrite() {
|
||||||
std::lock_guard<std::mutex> lock(writeMutex_);
|
std::lock_guard<std::mutex> lock(writeMutex_);
|
||||||
if (is_writing_ || writeQueue_.empty()) {
|
if (is_writing_ || writeQueue_.empty()) {
|
||||||
return;
|
return;
|
||||||
@ -263,16 +162,15 @@ public:
|
|||||||
self->doWrite();
|
self->doWrite();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
private:
|
|
||||||
|
|
||||||
void do_read() {
|
void Session::do_read() {
|
||||||
ws_.async_read(buffer_, [self = shared_from_this()](beast::error_code ec, std::size_t) {
|
ws_.async_read(buffer_, [self = shared_from_this()](beast::error_code ec, std::size_t) {
|
||||||
if (ec) {
|
if (ec) {
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
std::lock_guard<std::mutex> lock(self->server_.g_sessions_mutex);
|
||||||
g_sessions.erase(std::remove_if(g_sessions.begin(), g_sessions.end(),
|
self->server_.g_sessions.erase(std::remove_if(self->server_.g_sessions.begin(), self->server_.g_sessions.end(),
|
||||||
[self](const std::shared_ptr<Session>& session) {
|
[self](const std::shared_ptr<Session>& session) {
|
||||||
return session.get() == self.get();
|
return session.get() == self.get();
|
||||||
}), g_sessions.end());
|
}), self->server_.g_sessions.end());
|
||||||
std::cout << "Client " << self->id_ << " disconnected\n";
|
std::cout << "Client " << self->id_ << " disconnected\n";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -285,7 +183,7 @@ private:
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void process_message(const std::string& msg) {
|
void Session::process_message(const std::string& msg) {
|
||||||
if (!IsMessageValid(msg)) {
|
if (!IsMessageValid(msg)) {
|
||||||
std::cout << "[Security] Invalid packet hash. Dropping message: " << msg << std::endl;
|
std::cout << "[Security] Invalid packet hash. Dropping message: " << msg << std::endl;
|
||||||
return;
|
return;
|
||||||
@ -316,7 +214,7 @@ private:
|
|||||||
uint64_t now_ms = static_cast<uint64_t>(
|
uint64_t now_ms = static_cast<uint64_t>(
|
||||||
std::chrono::duration_cast<std::chrono::milliseconds>(now_tp.time_since_epoch()).count());
|
std::chrono::duration_cast<std::chrono::milliseconds>(now_tp.time_since_epoch()).count());
|
||||||
|
|
||||||
Eigen::Vector3f spawnPos = PickSafeSpawnPos(id_);
|
Eigen::Vector3f spawnPos = server_.PickSafeSpawnPos(id_);
|
||||||
this->hasReservedSpawn_ = true;
|
this->hasReservedSpawn_ = true;
|
||||||
this->reservedSpawn_ = spawnPos;
|
this->reservedSpawn_ = spawnPos;
|
||||||
|
|
||||||
@ -342,27 +240,16 @@ private:
|
|||||||
std::string eventMsg =
|
std::string eventMsg =
|
||||||
"EVENT:" + std::to_string(id_) + ":UPD:" + std::to_string(now_ms) + ":" + st.formPingMessageContent();
|
"EVENT:" + std::to_string(id_) + ":UPD:" + std::to_string(now_ms) + ":" + st.formPingMessageContent();
|
||||||
|
|
||||||
{
|
server_.broadcastToAllExceptId(eventMsg, id_);
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
|
||||||
for (auto& session : g_sessions) {
|
|
||||||
if (session->get_id() == id_) continue;
|
|
||||||
session->send_message(eventMsg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
std::cout << "Server: Player " << id_ << " joined as [" << nick << "] shipType=" << sType << std::endl;
|
std::cout << "Server: Player " << id_ << " joined as [" << nick << "] shipType=" << sType << std::endl;
|
||||||
|
|
||||||
std::string info = "PLAYERINFO:" + std::to_string(id_) + ":" + nick + ":" + std::to_string(sType);
|
std::string info = "PLAYERINFO:" + std::to_string(id_) + ":" + nick + ":" + std::to_string(sType);
|
||||||
|
server_.broadcastToAllExceptId(info, id_);
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
std::lock_guard<std::mutex> lock(server_.g_sessions_mutex);
|
||||||
for (auto& session : g_sessions) {
|
for (auto& session : server_.g_sessions) {
|
||||||
if (session->get_id() == this->id_) continue;
|
|
||||||
session->send_message(info);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
|
||||||
for (auto& session : g_sessions) {
|
|
||||||
if (session->get_id() == this->id_) continue;
|
if (session->get_id() == this->id_) continue;
|
||||||
std::string otherInfo = "PLAYERINFO:" + std::to_string(session->get_id()) + ":" + session->nickname + ":" + std::to_string(session->shipType);
|
std::string otherInfo = "PLAYERINFO:" + std::to_string(session->get_id()) + ":" + session->nickname + ":" + std::to_string(session->shipType);
|
||||||
|
|
||||||
@ -376,8 +263,8 @@ private:
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> gd(g_dead_mutex);
|
std::lock_guard<std::mutex> gd(server_.g_dead_mutex);
|
||||||
if (g_dead_players.find(id_) != g_dead_players.end()) {
|
if (server_.g_dead_players.find(id_) != server_.g_dead_players.end()) {
|
||||||
std::cout << "Server: Ignoring UPD from dead player " << id_ << std::endl;
|
std::cout << "Server: Ignoring UPD from dead player " << id_ << std::endl;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -399,8 +286,8 @@ private:
|
|||||||
}
|
}
|
||||||
else if (type == "RESPAWN") {
|
else if (type == "RESPAWN") {
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> gd(g_dead_mutex);
|
std::lock_guard<std::mutex> gd(server_.g_dead_mutex);
|
||||||
g_dead_players.erase(id_);
|
server_.g_dead_players.erase(id_);
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
@ -410,7 +297,7 @@ private:
|
|||||||
ClientState st;
|
ClientState st;
|
||||||
st.id = id_;
|
st.id = id_;
|
||||||
|
|
||||||
Eigen::Vector3f spawnPos = PickSafeSpawnPos(id_);
|
Eigen::Vector3f spawnPos = server_.PickSafeSpawnPos(id_);
|
||||||
st.position = spawnPos;
|
st.position = spawnPos;
|
||||||
|
|
||||||
this->hasReservedSpawn_ = true;
|
this->hasReservedSpawn_ = true;
|
||||||
@ -431,13 +318,13 @@ private:
|
|||||||
"SPAWN:" + std::to_string(id_) + ":" + std::to_string(now_ms) + ":" + st.formPingMessageContent()
|
"SPAWN:" + std::to_string(id_) + ":" + std::to_string(now_ms) + ":" + st.formPingMessageContent()
|
||||||
);
|
);
|
||||||
std::string respawnMsg = "RESPAWN_ACK:" + std::to_string(id_);
|
std::string respawnMsg = "RESPAWN_ACK:" + std::to_string(id_);
|
||||||
broadcastToAll(respawnMsg);
|
server_.broadcastToAll(respawnMsg);
|
||||||
|
|
||||||
std::string playerInfo = "PLAYERINFO:" + std::to_string(id_) + ":" + st.nickname + ":" + std::to_string(st.shipType);
|
std::string playerInfo = "PLAYERINFO:" + std::to_string(id_) + ":" + st.nickname + ":" + std::to_string(st.shipType);
|
||||||
broadcastToAll(playerInfo);
|
server_.broadcastToAll(playerInfo);
|
||||||
|
|
||||||
std::string eventMsg = "EVENT:" + std::to_string(id_) + ":UPD:" + std::to_string(now_ms) + ":" + st.formPingMessageContent();
|
std::string eventMsg = "EVENT:" + std::to_string(id_) + ":UPD:" + std::to_string(now_ms) + ":" + st.formPingMessageContent();
|
||||||
broadcastToAll(eventMsg);
|
server_.broadcastToAll(eventMsg);
|
||||||
|
|
||||||
std::cout << "Server: Player " << id_ << " respawned, broadcasted RESPAWN_ACK, PLAYERINFO and initial UPD\n";
|
std::cout << "Server: Player " << id_ << " respawned, broadcasted RESPAWN_ACK, PLAYERINFO and initial UPD\n";
|
||||||
}
|
}
|
||||||
@ -454,12 +341,6 @@ private:
|
|||||||
);
|
);
|
||||||
float velocity = std::stof(parts[9]);
|
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::string broadcast = "PROJECTILE:" +
|
||||||
std::to_string(id_) + ":" +
|
std::to_string(id_) + ":" +
|
||||||
std::to_string(clientTime) + ":" +
|
std::to_string(clientTime) + ":" +
|
||||||
@ -472,50 +353,14 @@ private:
|
|||||||
std::to_string(dir.z()) + ":" +
|
std::to_string(dir.z()) + ":" +
|
||||||
std::to_string(velocity);
|
std::to_string(velocity);
|
||||||
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
server_.broadcastToAllExceptId(broadcast, id_);
|
||||||
for (auto& session : g_sessions) {
|
|
||||||
if (session->get_id() != id_) {
|
server_.createProjectile(id_, pos, dir, velocity);
|
||||||
session->send_message(broadcast);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
Eigen::Vector3f Server::PickSafeSpawnPos(int forPlayerId)
|
||||||
const std::vector<Eigen::Vector3f> localOffsets = {
|
|
||||||
Eigen::Vector3f(-1.5f, 0.9f - 6.f, 5.0f),
|
|
||||||
Eigen::Vector3f(1.5f, 0.9f - 6.f, 5.0f)
|
|
||||||
};
|
|
||||||
|
|
||||||
uint64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>((
|
|
||||||
std::chrono::system_clock::now().time_since_epoch())).count();
|
|
||||||
|
|
||||||
std::lock_guard<std::mutex> 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 = 15000.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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
Eigen::Vector3f PickSafeSpawnPos(int forPlayerId)
|
|
||||||
{
|
{
|
||||||
static thread_local std::mt19937 rng{ std::random_device{}() };
|
static thread_local std::mt19937 rng{ std::random_device{}() };
|
||||||
|
|
||||||
@ -580,14 +425,54 @@ Eigen::Vector3f PickSafeSpawnPos(int forPlayerId)
|
|||||||
return Eigen::Vector3f(600.0f + a * 100.0f, -600.0f + b * 100.0f, kWorldZOffset);
|
return Eigen::Vector3f(600.0f + a * 100.0f, -600.0f + b * 100.0f, kWorldZOffset);
|
||||||
}
|
}
|
||||||
|
|
||||||
void broadcastToAll(const std::string& message) {
|
void Server::broadcastToAll(const std::string& message) {
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
for (const auto& session : g_sessions) {
|
for (const auto& session : g_sessions) {
|
||||||
session->send_message(message);
|
session->send_message(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void update_world(net::steady_timer& timer, net::io_context& ioc) {
|
void Server::broadcastToAllExceptId(const std::string& message, int id)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
|
for (auto& session : g_sessions) {
|
||||||
|
if (session->get_id() == id) continue;
|
||||||
|
session->send_message(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Server::createProjectile(int id, Eigen::Vector3f pos, Eigen::Quaternionf dir, float velocity)
|
||||||
|
{
|
||||||
|
const std::vector<Eigen::Vector3f> localOffsets = {
|
||||||
|
Eigen::Vector3f(-1.5f, 0.9f - 6.f, 5.0f),
|
||||||
|
Eigen::Vector3f(1.5f, 0.9f - 6.f, 5.0f)
|
||||||
|
};
|
||||||
|
|
||||||
|
uint64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>((
|
||||||
|
std::chrono::system_clock::now().time_since_epoch())).count();
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> pl(g_projectiles_mutex);
|
||||||
|
for (int i = 0; i < 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 = 15000.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 Server::update_world() {
|
||||||
|
|
||||||
static auto last_snapshot_time = std::chrono::system_clock::now();
|
static auto last_snapshot_time = std::chrono::system_clock::now();
|
||||||
|
|
||||||
@ -595,26 +480,6 @@ void update_world(net::steady_timer& timer, net::io_context& ioc) {
|
|||||||
uint64_t now_ms = static_cast<uint64_t>(
|
uint64_t now_ms = static_cast<uint64_t>(
|
||||||
std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
|
std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
|
||||||
|
|
||||||
// --- Snapshot every 500ms ---
|
|
||||||
/*if (std::chrono::duration_cast<std::chrono::milliseconds>(now - last_snapshot_time).count() >= 500) {
|
|
||||||
last_snapshot_time = now;
|
|
||||||
|
|
||||||
std::string snapshot_msg = "SNAPSHOT:" + std::to_string(now_ms);
|
|
||||||
|
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
|
||||||
for (auto& session : g_sessions) {
|
|
||||||
ClientState st = session->get_latest_state(now);
|
|
||||||
snapshot_msg += "|" + std::to_string(session->get_id()) + ":" + st.formPingMessageContent();
|
|
||||||
}
|
|
||||||
for (auto& session : g_sessions) {
|
|
||||||
session->send_message(snapshot_msg);
|
|
||||||
}
|
|
||||||
}*/
|
|
||||||
|
|
||||||
// --- Tick: broadcast each player's latest state to all others (20Hz) ---
|
|
||||||
// Send the raw last-known state with its original timestamp, NOT an extrapolated one.
|
|
||||||
// Extrapolating here causes snap-back: if a player stops rotating, the server would
|
|
||||||
// keep sending over-rotated positions until the new state arrives, then B snaps back.
|
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
for (auto& sender : g_sessions) {
|
for (auto& sender : g_sessions) {
|
||||||
@ -834,13 +699,13 @@ void update_world(net::steady_timer& timer, net::io_context& ioc) {
|
|||||||
|
|
||||||
// --- Schedule next tick in 50ms ---
|
// --- Schedule next tick in 50ms ---
|
||||||
timer.expires_after(std::chrono::milliseconds(50));
|
timer.expires_after(std::chrono::milliseconds(50));
|
||||||
timer.async_wait([&timer, &ioc](const boost::system::error_code& ec) {
|
timer.async_wait([this](const boost::system::error_code& ec) {
|
||||||
if (ec) return;
|
if (ec) return;
|
||||||
update_world(timer, ioc);
|
update_world();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<ServerBox> generateServerBoxes(int count) {
|
std::vector<ServerBox> Server::generateServerBoxes(int count) {
|
||||||
std::vector<ServerBox> boxes;
|
std::vector<ServerBox> boxes;
|
||||||
std::random_device rd;
|
std::random_device rd;
|
||||||
std::mt19937 gen(rd());
|
std::mt19937 gen(rd());
|
||||||
@ -889,34 +754,42 @@ std::vector<ServerBox> generateServerBoxes(int count) {
|
|||||||
return boxes;
|
return boxes;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main() {
|
Server::Server(tcp::acceptor& acceptor, net::io_context& ioc)
|
||||||
try {
|
: acceptor_(acceptor)
|
||||||
|
, ioc_(ioc)
|
||||||
|
, timer(ioc_)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
void Server::init()
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(g_boxes_mutex);
|
std::lock_guard<std::mutex> lock(g_boxes_mutex);
|
||||||
g_serverBoxes = generateServerBoxes(50);
|
g_serverBoxes = generateServerBoxes(50);
|
||||||
//g_serverBoxes = generateServerBoxes(1);
|
|
||||||
std::cout << "Generated " << g_serverBoxes.size() << " boxes on server\n";
|
std::cout << "Generated " << g_serverBoxes.size() << " boxes on server\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void Server::accept()
|
||||||
|
{
|
||||||
|
acceptor_.async_accept([&](beast::error_code ec, tcp::socket socket) {
|
||||||
|
if (!ec) {
|
||||||
|
std::make_shared<Session>(*this, std::move(socket), next_id++)->run();
|
||||||
|
}
|
||||||
|
accept();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
try {
|
||||||
net::io_context ioc;
|
net::io_context ioc;
|
||||||
tcp::acceptor acceptor{ ioc, {tcp::v4(), 8081} };
|
tcp::acceptor acceptor{ ioc, {tcp::v4(), 8081} };
|
||||||
|
|
||||||
int next_id = 1000;
|
Server server(acceptor, ioc);
|
||||||
|
|
||||||
|
server.accept();
|
||||||
|
|
||||||
std::cout << "Server started on port 8081...\n";
|
std::cout << "Server started on port 8081...\n";
|
||||||
|
|
||||||
auto do_accept = [&](auto& self_fn) -> void {
|
server.update_world();
|
||||||
acceptor.async_accept([&, self_fn](beast::error_code ec, tcp::socket socket) {
|
|
||||||
if (!ec) {
|
|
||||||
std::make_shared<Session>(std::move(socket), next_id++)->run();
|
|
||||||
}
|
|
||||||
self_fn(self_fn);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
net::steady_timer timer(ioc);
|
|
||||||
update_world(timer, ioc);
|
|
||||||
|
|
||||||
do_accept(do_accept);
|
|
||||||
ioc.run();
|
ioc.run();
|
||||||
}
|
}
|
||||||
catch (std::exception const& e) {
|
catch (std::exception const& e) {
|
||||||
|
|||||||
137
server/server.h
Normal file
137
server/server.h
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <boost/beast/core.hpp>
|
||||||
|
#include <boost/beast/websocket.hpp>
|
||||||
|
#include <string>
|
||||||
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
#include <mutex>
|
||||||
|
#include <queue>
|
||||||
|
#include <unordered_set>
|
||||||
|
#include <Eigen/Dense>
|
||||||
|
#include "../src/network/ClientState.h"
|
||||||
|
#define _USE_MATH_DEFINES
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
|
namespace beast = boost::beast;
|
||||||
|
namespace http = beast::http;
|
||||||
|
namespace websocket = beast::websocket;
|
||||||
|
namespace net = boost::asio;
|
||||||
|
using tcp = net::ip::tcp;
|
||||||
|
static constexpr float kWorldZOffset = 45000.0f;
|
||||||
|
static const Eigen::Vector3f kWorldOffset(0.0f, 0.0f, kWorldZOffset);
|
||||||
|
|
||||||
|
static constexpr float kShipRadius = 15.0f;
|
||||||
|
static constexpr float kSpawnShipMargin = 25.0f;
|
||||||
|
static constexpr float kSpawnBoxMargin = 15.0f;
|
||||||
|
static constexpr float kSpawnZJitter = 60.0f;
|
||||||
|
|
||||||
|
std::vector<std::string> split(const std::string& s, char delimiter);
|
||||||
|
|
||||||
|
struct DeathInfo {
|
||||||
|
int targetId = -1;
|
||||||
|
uint64_t serverTime = 0;
|
||||||
|
Eigen::Vector3f position = Eigen::Vector3f::Zero();
|
||||||
|
int killerId = -1;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
struct ServerBox {
|
||||||
|
Eigen::Vector3f position;
|
||||||
|
Eigen::Matrix3f rotation;
|
||||||
|
float collisionRadius = 2.0f;
|
||||||
|
bool destroyed = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Projectile {
|
||||||
|
int shooterId = -1;
|
||||||
|
uint64_t spawnMs = 0;
|
||||||
|
Eigen::Vector3f pos;
|
||||||
|
Eigen::Vector3f vel;
|
||||||
|
float lifeMs = PROJECTILE_LIFE;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct BoxDestroyedInfo {
|
||||||
|
int boxIndex = -1;
|
||||||
|
uint64_t serverTime = 0;
|
||||||
|
Eigen::Vector3f position = Eigen::Vector3f::Zero();
|
||||||
|
int destroyedBy = -1;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Server;
|
||||||
|
|
||||||
|
class Session : public std::enable_shared_from_this<Session> {
|
||||||
|
Server& server_;
|
||||||
|
websocket::stream<beast::tcp_stream> ws_;
|
||||||
|
beast::flat_buffer buffer_;
|
||||||
|
int id_;
|
||||||
|
bool is_writing_ = false;
|
||||||
|
std::queue<std::shared_ptr<std::string>> writeQueue_;
|
||||||
|
std::mutex writeMutex_;
|
||||||
|
|
||||||
|
|
||||||
|
public:
|
||||||
|
ClientStateInterval timedClientStates;
|
||||||
|
bool joined_ = false;
|
||||||
|
|
||||||
|
bool hasReservedSpawn_ = false;
|
||||||
|
Eigen::Vector3f reservedSpawn_ = Eigen::Vector3f(0.0f, 0.0f, kWorldZOffset);
|
||||||
|
|
||||||
|
std::string nickname = "Player";
|
||||||
|
int shipType = 0;
|
||||||
|
|
||||||
|
Session(Server& server, tcp::socket&& socket, int id);
|
||||||
|
int get_id() const;
|
||||||
|
bool hasSpawnReserved() const;
|
||||||
|
const Eigen::Vector3f& reservedSpawn() const;
|
||||||
|
bool fetchStateAtTime(std::chrono::system_clock::time_point targetTime, ClientState& outState) const;
|
||||||
|
void send_message(const std::string& msg);
|
||||||
|
void run();
|
||||||
|
bool IsMessageValid(const std::string& fullMessage);
|
||||||
|
|
||||||
|
private:
|
||||||
|
void sendBoxesToClient();
|
||||||
|
public:
|
||||||
|
void init();
|
||||||
|
ClientState get_latest_state(std::chrono::system_clock::time_point now);
|
||||||
|
void doWrite();
|
||||||
|
private:
|
||||||
|
|
||||||
|
void do_read();
|
||||||
|
void process_message(const std::string& msg);
|
||||||
|
};
|
||||||
|
|
||||||
|
class Server
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
tcp::acceptor& acceptor_;
|
||||||
|
net::io_context& ioc_;
|
||||||
|
net::steady_timer timer;
|
||||||
|
std::vector<BoxDestroyedInfo> g_boxDestructions;
|
||||||
|
std::mutex g_boxDestructions_mutex;
|
||||||
|
|
||||||
|
std::vector<ServerBox> g_serverBoxes;
|
||||||
|
std::mutex g_boxes_mutex;
|
||||||
|
|
||||||
|
std::vector<std::shared_ptr<Session>> g_sessions;
|
||||||
|
std::mutex g_sessions_mutex;
|
||||||
|
|
||||||
|
std::vector<Projectile> g_projectiles;
|
||||||
|
std::mutex g_projectiles_mutex;
|
||||||
|
|
||||||
|
std::unordered_set<int> g_dead_players;
|
||||||
|
std::mutex g_dead_mutex;
|
||||||
|
|
||||||
|
int next_id = 1000;
|
||||||
|
|
||||||
|
std::vector<ServerBox> generateServerBoxes(int count);
|
||||||
|
public:
|
||||||
|
Server(tcp::acceptor& acceptor, net::io_context& ioc);
|
||||||
|
|
||||||
|
void broadcastToAll(const std::string& message);
|
||||||
|
void broadcastToAllExceptId(const std::string& message, int id);
|
||||||
|
void createProjectile(int id, Eigen::Vector3f pos, Eigen::Quaternionf dir, float velocity);
|
||||||
|
void update_world();
|
||||||
|
Eigen::Vector3f PickSafeSpawnPos(int forPlayerId);
|
||||||
|
void init();
|
||||||
|
void accept();
|
||||||
|
};
|
||||||
Loading…
Reference in New Issue
Block a user