migrate codebase to new network

marked non-implemented stuff with an exception
This commit is contained in:
Lion Kortlepel 2024-01-19 17:34:36 +01:00
parent e0fe6693e0
commit b06991aaca
No known key found for this signature in database
GPG Key ID: 4322FF2B4C71259B
10 changed files with 148 additions and 153 deletions

View File

@ -14,7 +14,7 @@ namespace MP {
std::tuple<int, int, int> GetServerVersion(); std::tuple<int, int, int> GetServerVersion();
std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data); std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data); std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); } inline size_t GetPlayerCount() { return Engine->Network()->authenticated_client_count(); }
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason); std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message); std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID); std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include "Cryptography.h" #include "Cryptography.h"
#include "TScopedTimer.h"
#include "commandline.h" #include "commandline.h"
#include <atomic> #include <atomic>
#include <fstream> #include <fstream>
@ -69,4 +70,5 @@ private:
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE"; const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
std::ofstream mLogFileStream; std::ofstream mLogFileStream;
std::mutex mLogFileStreamMtx; std::mutex mLogFileStreamMtx;
TScopedTimer mUptimeTimer{};
}; };

View File

@ -2,10 +2,11 @@
#include "Common.h" #include "Common.h"
#include "IThreaded.h" #include "IThreaded.h"
#include "Network.h"
class THeartbeatThread : public IThreaded { class THeartbeatThread : public IThreaded {
public: public:
THeartbeatThread(TResourceManager& ResourceManager, TServer& Server); THeartbeatThread(std::shared_ptr<Network> network);
//~THeartbeatThread(); //~THeartbeatThread();
void operator()() override; void operator()() override;
@ -13,6 +14,5 @@ private:
std::string GenerateCall(); std::string GenerateCall();
std::string GetPlayers(); std::string GetPlayers();
TResourceManager& mResourceManager; std::shared_ptr<Network> m_network;
TServer& mServer;
}; };

View File

@ -1,7 +1,10 @@
#pragma once #pragma once
#include "Common.h"
#include "IThreaded.h"
#include "Network.h" #include "Network.h"
#include <any> #include <any>
#include <boost/thread/scoped_thread.hpp>
#include <condition_variable> #include <condition_variable>
#include <filesystem> #include <filesystem>
#include <initializer_list> #include <initializer_list>
@ -67,7 +70,7 @@ struct TLuaChunk {
std::string PluginPath; std::string PluginPath;
}; };
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine>, IThreaded { class TLuaEngine : public std::enable_shared_from_this<TLuaEngine> {
public: public:
enum CallStrategy : int { enum CallStrategy : int {
BestEffort, BestEffort,
@ -86,13 +89,11 @@ public:
beammp_debug("Lua Engine terminated"); beammp_debug("Lua Engine terminated");
} }
void operator()() override; void Start();
TNetwork& Network() { return *mNetwork; } std::shared_ptr<::Network> Network() { return mNetwork; }
TServer& Server() { return *mServer; }
void SetNetwork(TNetwork* Network) { mNetwork = Network; } void SetNetwork(const std::shared_ptr<::Network>& network) { mNetwork = network; }
void SetServer(TServer* Server) { mServer = Server; }
size_t GetResultsToCheckSize() { size_t GetResultsToCheckSize() {
std::unique_lock Lock(mResultsToCheckMutex); std::unique_lock Lock(mResultsToCheckMutex);
@ -200,7 +201,7 @@ private:
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config); void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
size_t CalculateMemoryUsage(); size_t CalculateMemoryUsage();
class StateThreadData : IThreaded { class StateThreadData {
public: public:
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine); StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
StateThreadData(const StateThreadData&) = delete; StateThreadData(const StateThreadData&) = delete;
@ -210,7 +211,7 @@ private:
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
void RegisterEvent(const std::string& EventName, const std::string& FunctionName); void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
void AddPath(const fs::path& Path); // to be added to path and cpath void AddPath(const fs::path& Path); // to be added to path and cpath
void operator()() override; void Start();
sol::state_view State() { return sol::state_view(mState); } sol::state_view State() { return sol::state_view(mState); }
std::vector<std::string> GetStateGlobalKeys(); std::vector<std::string> GetStateGlobalKeys();
@ -229,7 +230,7 @@ private:
sol::table Lua_GetPlayers(); sol::table Lua_GetPlayers();
std::string Lua_GetPlayerName(int ID); std::string Lua_GetPlayerName(int ID);
sol::table Lua_GetPlayerVehicles(int ID); sol::table Lua_GetPlayerVehicles(int ID);
std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID); std::pair<sol::table, std::string> Lua_GetVehicleStatus(int VID);
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port); sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
int Lua_GetPlayerIDByName(const std::string& Name); int Lua_GetPlayerIDByName(const std::string& Name);
sol::table Lua_FS_ListFiles(const std::string& Path); sol::table Lua_FS_ListFiles(const std::string& Path);
@ -238,7 +239,6 @@ private:
std::string mName; std::string mName;
TLuaStateId mStateId; TLuaStateId mStateId;
lua_State* mState; lua_State* mState;
std::thread mThread;
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue; std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
std::recursive_mutex mStateExecuteQueueMutex; std::recursive_mutex mStateExecuteQueueMutex;
std::vector<QueuedFunction> mStateFunctionQueue; std::vector<QueuedFunction> mStateFunctionQueue;
@ -250,6 +250,7 @@ private:
std::recursive_mutex mPathsMutex; std::recursive_mutex mPathsMutex;
std::mt19937 mMersenneTwister; std::mt19937 mMersenneTwister;
std::uniform_real_distribution<double> mUniformRealDistribution01; std::uniform_real_distribution<double> mUniformRealDistribution01;
boost::scoped_thread<> mThread;
}; };
struct TimedEvent { struct TimedEvent {
@ -262,8 +263,7 @@ private:
void Reset(); void Reset();
}; };
TNetwork* mNetwork; std::shared_ptr<::Network> mNetwork;
TServer* mServer;
const fs::path mResourceServerPath; const fs::path mResourceServerPath;
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins; std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates; std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
@ -275,6 +275,7 @@ private:
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck; std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
std::mutex mResultsToCheckMutex; std::mutex mResultsToCheckMutex;
std::condition_variable mResultsToCheckCond; std::condition_variable mResultsToCheckCond;
boost::scoped_thread<> mThread;
}; };
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait); // std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);

View File

@ -113,6 +113,8 @@ TEST_CASE("LuaAPI::MP::GetServerVersion") {
} }
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) { static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
std::string Packet = "E:" + EventName + ":" + Data; std::string Packet = "E:" + EventName + ":" + Data;
if (PlayerID == -1) { if (PlayerID == -1) {
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true); LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
@ -130,7 +132,7 @@ static inline std::pair<bool, std::string> InternalTriggerClientEvent(int Player
return { false, "Respond failed, dropping client" }; return { false, "Respond failed, dropping client" };
} }
return { true, "" }; return { true, "" };
} }*/
} }
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) { std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
@ -139,6 +141,8 @@ std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const
} }
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) { std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (!MaybeClient) { if (!MaybeClient) {
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID); beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
@ -147,9 +151,12 @@ std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::s
auto c = MaybeClient.value(); auto c = MaybeClient.value();
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason")); LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
return { true, "" }; return { true, "" };
*/
} }
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) { std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
std::pair<bool, std::string> Result; std::pair<bool, std::string> Result;
std::string Packet = "C:Server: " + Message; std::string Packet = "C:Server: " + Message;
if (ID == -1) { if (ID == -1) {
@ -180,9 +187,12 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
return Result; return Result;
} }
return Result; return Result;
*/
} }
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) { std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
std::pair<bool, std::string> Result; std::pair<bool, std::string> Result;
auto MaybeClient = GetClient(Engine->Server(), PID); auto MaybeClient = GetClient(Engine->Server(), PID);
if (!MaybeClient) { if (!MaybeClient) {
@ -202,6 +212,7 @@ std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
Result.second = "Vehicle does not exist"; Result.second = "Vehicle does not exist";
} }
return Result; return Result;
*/
} }
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) { void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
@ -273,21 +284,26 @@ void LuaAPI::MP::Sleep(size_t Ms) {
} }
bool LuaAPI::MP::IsPlayerConnected(int ID) { bool LuaAPI::MP::IsPlayerConnected(int ID) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient) { if (MaybeClient) {
return MaybeClient.value()->IsConnected.get(); return MaybeClient.value()->IsConnected.get();
} else { } else {
return false; return false;
} }*/
} }
bool LuaAPI::MP::IsPlayerGuest(int ID) { bool LuaAPI::MP::IsPlayerGuest(int ID) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient) { if (MaybeClient) {
return MaybeClient.value()->IsGuest.get(); return MaybeClient.value()->IsGuest.get();
} else { } else {
return false; return false;
} }
*/
} }
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) { void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {

View File

@ -265,14 +265,15 @@ void TConsole::Command_Kick(const std::string&, const std::vector<std::string>&
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); }); std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1); return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
}; };
mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool { throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
if (NameCompare(Client->Name.get(), Name)) { if (NameCompare(Client->Name.get(), Name)) {
mLuaEngine->Network().ClientKick(*Client, Reason); mLuaEngine->Network().ClientKick(*Client, Reason);
Kicked = true; Kicked = true;
return false; return false;
} }
return true; return true;
}); });*/
if (!Kicked) { if (!Kicked) {
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found."); Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
} else { } else {
@ -355,6 +356,9 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
if (!EnsureArgsCount(args, 0)) { if (!EnsureArgsCount(args, 0)) {
return; return;
} }
// Implement once running
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
if (mLuaEngine->Server().ClientCount() == 0) { if (mLuaEngine->Server().ClientCount() == 0) {
Application::Console().WriteRaw("No players online."); Application::Console().WriteRaw("No players online.");
} else { } else {
@ -369,6 +373,7 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
auto Str = ss.str(); auto Str = ss.str();
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1)); Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
} }
*/
} }
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) { void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
@ -377,26 +382,6 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
} }
std::stringstream Status; std::stringstream Status;
size_t CarCount = 0;
size_t ConnectedCount = 0;
size_t GuestCount = 0;
size_t SyncedCount = 0;
size_t SyncingCount = 0;
size_t MissedPacketQueueSum = 0;
int LargestSecondsSinceLastPing = 0;
mLuaEngine->Server().ForEachClient([&](std::shared_ptr<TClient> Client) -> bool {
CarCount += size_t(Client->GetCarCount());
ConnectedCount += Client->IsConnected ? 1 : 0;
GuestCount += Client->IsGuest ? 1 : 0;
SyncedCount += Client->IsSynced ? 1 : 0;
SyncingCount += Client->IsSyncing ? 1 : 0;
MissedPacketQueueSum += Client->MissedPacketsQueue->size();
if (Client->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
LargestSecondsSinceLastPing = Client->SecondsSinceLastPing();
}
return true;
});
size_t SystemsStarting = 0; size_t SystemsStarting = 0;
size_t SystemsGood = 0; size_t SystemsGood = 0;
size_t SystemsBad = 0; size_t SystemsBad = 0;
@ -441,15 +426,21 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2); SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2); SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
auto ElapsedTime = mLuaEngine->Server().UptimeTimer.GetElapsedTime(); auto ElapsedTime = mUptimeTimer.GetElapsedTime();
auto network = mLuaEngine->Network();
auto clients = network->all_clients();
Status << "BeamMP-Server Status:\n" Status << "BeamMP-Server Status:\n"
<< "\tTotal Players: " << mLuaEngine->Server().ClientCount() << "\n" << "\tTotal Players: " << clients.size() << "\n"
<< "\tSyncing Players: " << SyncingCount << "\n" << "\tPlayers identifying: " << network->clients_in_state_count(bmp::State::Identification) << "\n"
<< "\tSynced Players: " << SyncedCount << "\n" << "\tPlayers authenticating: " << network->clients_in_state_count(bmp::State::Authentication) << "\n"
<< "\tConnected Players: " << ConnectedCount << "\n" << "\tPlayers downloading mods: " << network->clients_in_state_count(bmp::State::ModDownload) << "\n"
<< "\tGuests: " << GuestCount << "\n" << "\tPlayers spawning in: " << network->clients_in_state_count(bmp::State::SessionSetup) << "\n"
<< "\tCars: " << CarCount << "\n" << "\tPlayers playing: " << network->clients_in_state_count(bmp::State::Playing) << "\n"
<< "\tPlayers leaving: " << network->clients_in_state_count(bmp::State::Leaving) << "\n"
<< "\tGuests: " << network->guest_count() << "\n"
<< "\tVehicles: " << network->vehicle_count() << "\n"
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n" << "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n"
<< "\tLua:\n" << "\tLua:\n"
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n" << "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"

View File

@ -1,7 +1,7 @@
#include "THeartbeatThread.h" #include "THeartbeatThread.h"
#include "Http.h" #include "Http.h"
//#include "SocketIO.h" // #include "SocketIO.h"
#include <rapidjson/document.h> #include <rapidjson/document.h>
#include <rapidjson/rapidjson.h> #include <rapidjson/rapidjson.h>
#include <sstream> #include <sstream>
@ -120,7 +120,7 @@ std::string THeartbeatThread::GenerateCall() {
std::stringstream Ret; std::stringstream Ret;
Ret << "uuid=" << Application::Settings.Key Ret << "uuid=" << Application::Settings.Key
<< "&players=" << mServer.ClientCount() << "&players=" << m_network->authenticated_client_count()
<< "&maxplayers=" << Application::Settings.MaxPlayers << "&maxplayers=" << Application::Settings.MaxPlayers
<< "&port=" << Application::Settings.Port << "&port=" << Application::Settings.Port
<< "&map=" << Application::Settings.MapName << "&map=" << Application::Settings.MapName
@ -129,17 +129,16 @@ std::string THeartbeatThread::GenerateCall() {
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf. << "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
<< "&name=" << Application::Settings.ServerName << "&name=" << Application::Settings.ServerName
<< "&tags=" << Application::Settings.ServerTags << "&tags=" << Application::Settings.ServerTags
<< "&modlist=" << mResourceManager.TrimmedList() << "&modlist=" << "-"//mResourceManager.TrimmedList()
<< "&modstotalsize=" << mResourceManager.MaxModSize() << "&modstotalsize=" << 0 //mResourceManager.MaxModSize()
<< "&modstotal=" << mResourceManager.ModsLoaded() << "&modstotal=" << 0 // mResourceManager.ModsLoaded()
<< "&playerslist=" << GetPlayers() << "&playerslist=" << GetPlayers()
<< "&desc=" << Application::Settings.ServerDesc << "&desc=" << Application::Settings.ServerDesc
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true"); << "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
return Ret.str(); return Ret.str();
} }
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server) THeartbeatThread::THeartbeatThread(std::shared_ptr<Network> network)
: mResourceManager(ResourceManager) : m_network(std::move(network)) {
, mServer(Server) {
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting); Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
Application::RegisterShutdownHandler([&] { Application::RegisterShutdownHandler([&] {
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown); Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
@ -151,12 +150,10 @@ THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& S
Start(); Start();
} }
std::string THeartbeatThread::GetPlayers() { std::string THeartbeatThread::GetPlayers() {
std::string Return; std::string players;
mServer.ForEachClient([&](const std::shared_ptr<TClient>& ClientPtr) -> bool { for (const auto& [id, client] : m_network->authenticated_clients()) {
Return += ClientPtr->Name.get() + ";"; players += client->name.get() + ";";
return true; }
}); return players;
return Return;
} }
/*THeartbeatThread::~THeartbeatThread() {
}*/

View File

@ -31,7 +31,7 @@ TLuaEngine::TLuaEngine()
} }
Application::SetSubsystemStatus("LuaEngine", Application::Status::Shutdown); Application::SetSubsystemStatus("LuaEngine", Application::Status::Shutdown);
}); });
IThreaded::Start(); mThread = boost::scoped_thread<>(&TLuaEngine::Start, this);
} }
TEST_CASE("TLuaEngine ctor & dtor") { TEST_CASE("TLuaEngine ctor & dtor") {
@ -40,7 +40,7 @@ TEST_CASE("TLuaEngine ctor & dtor") {
Application::GracefullyShutdown(); Application::GracefullyShutdown();
} }
void TLuaEngine::operator()() { void TLuaEngine::Start() {
RegisterThread("LuaEngine"); RegisterThread("LuaEngine");
Application::SetSubsystemStatus("LuaEngine", Application::Status::Good); Application::SetSubsystemStatus("LuaEngine", Application::Status::Good);
// lua engine main thread // lua engine main thread
@ -478,9 +478,9 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string&
} }
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto MaybeClient = mEngine->Network()->get_client(ClientID(ID), bmp::State::Authentication);
if (MaybeClient) { if (MaybeClient) {
auto IDs = MaybeClient.value()->Identifiers.synchronize(); auto IDs = MaybeClient.value()->identifiers.synchronize();
if (IDs->empty()) { if (IDs->empty()) {
return sol::lua_nil; return sol::lua_nil;
} }
@ -495,24 +495,22 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
} }
sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() { sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
sol::table Result = mStateView.create_table(); sol::table result = mStateView.create_table();
mEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool { auto clients = mEngine->Network()->authenticated_clients();
Result[Client->ID.get()] = Client->Name.get(); for (const auto& [id, client] : clients) {
return true; result[client->id] = client->name.get();
}); }
return Result; return result;
} }
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) { int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
int Id = -1; auto clients = mEngine->Network()->authenticated_clients();
mEngine->mServer->ForEachClient([&Id, &Name](const std::shared_ptr<TClient>& Client) -> bool { for (const auto& [id, client] : clients) {
if (Client->Name.get() == Name) { if (client->name.get() == Name) {
Id = Client->ID.get(); return int(client->id);
return false;
} }
return true; }
}); return -1;
return Id;
} }
sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) { sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) {
@ -542,56 +540,51 @@ sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string
} }
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) { std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto maybe_client = mEngine->Network()->get_client(ClientID(ID), bmp::State::Authentication);
if (MaybeClient) { if (maybe_client) {
return MaybeClient.value()->Name.get(); return maybe_client.value()->name.get();
} else { } else {
return ""; return "";
} }
} }
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto vehicles = mEngine->Network()->get_vehicles_owned_by(ClientID(ID));
if (MaybeClient) { if (vehicles.empty()) {
auto Client = MaybeClient.value();
auto VehicleData = Client->VehicleData.synchronize();
if (VehicleData->empty()) {
return sol::lua_nil; return sol::lua_nil;
} }
sol::state_view StateView(mState); sol::state_view state_view(mState);
sol::table Result = StateView.create_table(); sol::table result = state_view.create_table();
for (const auto& v : *VehicleData) { for (const auto& [vid, vehicle] : vehicles) {
Result[v.ID()] = v.Data().substr(3); result[vid] = vehicle->data.get();
} }
return Result; return result;
} else
return sol::lua_nil;
} }
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) { std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetVehicleStatus(int VID) {
std::pair<sol::table, std::string> Result; auto maybe_vehicle = mEngine->Network()->get_vehicle(VehicleID(VID));
auto MaybeClient = GetClient(mEngine->Server(), PID); if (maybe_vehicle) {
if (MaybeClient) { sol::state_view state_view(mState);
auto Client = MaybeClient.value(); sol::table result = state_view.create_table();
std::string VehiclePos = Client->GetCarPositionRaw(VID); auto veh = maybe_vehicle.value();
auto status = veh->get_status();
if (VehiclePos.empty()) { result["pos"]["x"] = status.pos.x;
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found")); result["pos"]["y"] = status.pos.y;
Result.second = "Vehicle not found"; result["pos"]["z"] = status.pos.z;
return Result; result["vel"]["x"] = status.vel.x;
} result["vel"]["y"] = status.vel.y;
result["vel"]["z"] = status.vel.z;
sol::table t = Lua_JsonDecode(VehiclePos); result["rvel"]["x"] = status.rvel.x;
if (t == sol::lua_nil) { result["rvel"]["y"] = status.rvel.y;
Result.second = "Packet decode failed"; result["rvel"]["z"] = status.rvel.z;
} result["rot"]["x"] = status.rot.x;
// return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil)); result["rot"]["y"] = status.rot.y;
Result.first = t; result["rot"]["z"] = status.rot.z;
return Result; result["rot"]["w"] = status.rot.w;
result["time"] = status.time;
return { result, "" };
} else { } else {
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired")); return { sol::lua_nil, fmt::format("Vehicle {} not found", VID) };
Result.second = "No such player";
return Result;
} }
} }
@ -753,8 +746,8 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table { MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
return Lua_GetPlayerVehicles(ID); return Lua_GetPlayerVehicles(ID);
}); });
MPTable.set_function("GetPositionRaw", [&](int PID, int VID) -> std::pair<sol::table, std::string> { MPTable.set_function("GetVehicleStatus", [&](int VID) -> std::pair<sol::table, std::string> {
return Lua_GetPositionRaw(PID, VID); return Lua_GetVehicleStatus(VID);
}); });
MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage); MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
MPTable.set_function("GetPlayers", [&]() -> sol::table { MPTable.set_function("GetPlayers", [&]() -> sol::table {
@ -855,7 +848,7 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
FSTable.set_function("ListDirectories", [this](const std::string& Path) { FSTable.set_function("ListDirectories", [this](const std::string& Path) {
return Lua_FS_ListDirectories(Path); return Lua_FS_ListDirectories(Path);
}); });
Start(); mThread = boost::scoped_thread<>(&StateThreadData::Start, this);
} }
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLuaChunk& Script) { std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLuaChunk& Script) {
@ -901,7 +894,7 @@ void TLuaEngine::StateThreadData::RegisterEvent(const std::string& EventName, co
mEngine->RegisterEvent(EventName, mStateId, FunctionName); mEngine->RegisterEvent(EventName, mStateId, FunctionName);
} }
void TLuaEngine::StateThreadData::operator()() { void TLuaEngine::StateThreadData::Start() {
RegisterThread("Lua:" + mStateId); RegisterThread("Lua:" + mStateId);
while (!Application::IsShuttingDown()) { while (!Application::IsShuttingDown()) {
{ // StateExecuteQueue Scope { // StateExecuteQueue Scope

View File

@ -135,21 +135,15 @@ int BeamMPServerMain(MainArguments Arguments) {
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5)); TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
}); });
TServer Server(Arguments.List);
auto LuaEngine = std::make_shared<TLuaEngine>(); auto LuaEngine = std::make_shared<TLuaEngine>();
LuaEngine->SetServer(&Server);
Application::Console().InitializeLuaConsole(*LuaEngine); Application::Console().InitializeLuaConsole(*LuaEngine);
RegisterThread("Main"); RegisterThread("Main");
beammp_trace("Running in debug mode on a debug build"); beammp_trace("Running in debug mode on a debug build");
TResourceManager ResourceManager; std::shared_ptr<Network> network = std::make_shared<Network>();
TPPSMonitor PPSMonitor(Server); THeartbeatThread Heartbeat(network);
THeartbeatThread Heartbeat(ResourceManager, Server); LuaEngine->SetNetwork(network);
TNetwork Network(Server, PPSMonitor, ResourceManager);
LuaEngine->SetNetwork(&Network);
PPSMonitor.SetNetwork(Network);
Application::CheckForUpdates(); Application::CheckForUpdates();
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine); TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);

View File

@ -15,6 +15,7 @@
"rapidjson", "rapidjson",
"sol2", "sol2",
"toml11", "toml11",
"zstd" "zstd",
"glm"
] ]
} }