1er commit

This commit is contained in:
2021-08-21 10:14:47 +02:00
commit a99ecf7c2d
99 changed files with 66605 additions and 0 deletions

105
src/game/server/Server.cpp Normal file
View File

@@ -0,0 +1,105 @@
#include "game/server/Server.h"
#include <iostream>
#include "protocol/PacketFactory.h"
namespace td {
namespace server {
Server::Server(const std::string& worldFilePath){
m_Game.getWorld()->loadMapFromFile(worldFilePath);
}
void Server::lauchGame(){
m_Game.startGame();
}
bool Server::start(std::uint16_t port){
if(!m_Listener.listen(port, 10)){
std::cout << "Failed to bind port " << port << " !\n";
return false;
}
if(!m_Listener.setBlocking(false)){
std::cout << "Failed to block server socket !\n";
return false;
}
std::cout << "Server started at port " << port << " !\n";
m_TickCounter.reset();
return true;
}
void Server::stop(){
protocol::DisconnectPacket packet("Server closed");
broadcastPacket(&packet);
m_Listener.close();
m_Listener.destroy();
m_Connections.clear();
getPlayers().clear();
}
void Server::tick(std::uint64_t delta){
accept();
updateSockets();
m_Lobby.tick();
m_Game.tick(delta);
if(m_TickCounter.update()){
protocol::ServerTpsPacket packet(m_TickCounter.getTPS(), utils::getTime());
broadcastPacket(&packet);
}
}
void Server::accept(){
static std::uint8_t newPlayerID = 0;
network::TCPSocket newSocket;
if (m_Listener.accept(newSocket)){
ServerConnexion con(newSocket, newPlayerID);
m_Connections.insert(std::move(ConnexionMap::value_type{newPlayerID, std::move(con)}));
OnPlayerJoin(newPlayerID);
m_Connections[newPlayerID].setServer(this);
newPlayerID++;
}
}
void Server::updateSockets(){
std::int16_t closedConnexionID = -1;
for (auto& connection : m_Connections){
ServerConnexion& con = connection.second;
if(con.getSocketStatus() != network::Socket::Status::Connected){
closedConnexionID = connection.first;
}else{
con.updateSocket();
}
}
if(closedConnexionID != -1){
removeConnexion(closedConnexionID);
}
}
void Server::broadcastPacket(protocol::Packet* packet){
for (auto& connection : m_Connections){
ServerConnexion& con = connection.second;
con.sendPacket(packet);
}
}
void Server::removeConnexion(std::uint8_t connexionID){
getPlayers().erase(getPlayers().find(connexionID));
m_Connections.erase(connexionID);
m_Lobby.OnPlayerLeave(connexionID);
OnPlayerLeave(connexionID);
}
void Server::OnPlayerJoin(std::uint8_t id){
m_Lobby.OnPlayerJoin(id);
getPlayers().insert({id, game::Player{id}});
}
void Server::OnPlayerLeave(std::uint8_t id){
protocol::PlayerLeavePacket packet(id);
broadcastPacket(&packet);
}
} // namespace server
} // namespace td