Skip to content

Commit

Permalink
FLHook compiling once again, made logger a static class with a theade…
Browse files Browse the repository at this point in the history
…d queue to allow for multi-threaded logging
  • Loading branch information
Lazrius committed Nov 17, 2023
1 parent 0666449 commit 7ec1ae0
Show file tree
Hide file tree
Showing 75 changed files with 2,719 additions and 2,476 deletions.
2 changes: 1 addition & 1 deletion FLHookSDK
48 changes: 48 additions & 0 deletions include/API/FLHook/PersonalityHelper.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#pragma once

class PersonalityHelper
{
friend FLHook;

std::map<std::wstring, pub::AI::Personality> pilots;
std::map<std::wstring, pub::AI::Personality::EvadeDodgeUseStruct> evadeDodge;
std::map<std::wstring, pub::AI::Personality::EvadeBreakUseStruct> evadeBreak;
std::map<std::wstring, pub::AI::Personality::BuzzHeadTowardUseStruct> buzzHead;
std::map<std::wstring, pub::AI::Personality::BuzzPassByUseStruct> buzzPass;
std::map<std::wstring, pub::AI::Personality::TrailUseStruct> trail;
std::map<std::wstring, pub::AI::Personality::StrafeUseStruct> strafe;
std::map<std::wstring, pub::AI::Personality::EngineKillUseStruct> engineKill;
std::map<std::wstring, pub::AI::Personality::RepairUseStruct> repair;
std::map<std::wstring, pub::AI::Personality::GunUseStruct> gun;
std::map<std::wstring, pub::AI::Personality::MissileUseStruct> missile;
std::map<std::wstring, pub::AI::Personality::MineUseStruct> mine;
std::map<std::wstring, pub::AI::Personality::MissileReactionStruct> missileReaction;
std::map<std::wstring, pub::AI::Personality::DamageReactionStruct> damageReaction;
std::map<std::wstring, pub::AI::Personality::CountermeasureUseStruct> cm;
std::map<std::wstring, pub::AI::Personality::FormationUseStruct> formation;
std::map<std::wstring, pub::AI::Personality::JobStruct> job;

Action<pub::AI::Personality, Error> GetPersonality(const std::wstring& pilotNickname);
static void SetDirection(INI_Reader& ini, float (&direction)[4]);

void LoadEvadeDodge(INI_Reader& ini);
void LoadEvadeBreak(INI_Reader& ini);
void LoadBuzzHead(INI_Reader& ini);
void LoadBuzzPass(INI_Reader& ini);
void LoadTrail(INI_Reader& ini);
void LoadStrafe(INI_Reader& ini);
void LoadEngineKill(INI_Reader& ini);
void LoadRepair(INI_Reader& ini);
void LoadGun(INI_Reader& ini);
void LoadMine(INI_Reader& ini);
void LoadMissileReaction(INI_Reader& ini);
void LoadDamageReaction(INI_Reader& ini);
void LoadCM(INI_Reader& ini);
void LoadFormation(INI_Reader& ini);
static void GetDifficulty(INI_Reader& ini, int& difficulty);
void LoadJob(INI_Reader& ini);
void LoadMissile(INI_Reader& ini);
void LoadPilot(INI_Reader& ini);

PersonalityHelper();
};
7 changes: 6 additions & 1 deletion include/API/Types/ClientId.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,12 @@ class ClientId
[[nodiscard]]
Action<ShipId, Error> GetShipId() const;

// TODO: Implement.
/**
* @brief Get the average latency of the clients connection to the server
* @returns On success : The average latency in ms
* @returns On fail : InvalidClientId error
*/
[[nodiscard]]
Action<uint, Error> GetLatency() const;

/**
Expand Down
14 changes: 0 additions & 14 deletions include/API/Utils/FileUtils.hpp

This file was deleted.

28 changes: 0 additions & 28 deletions include/API/Utils/IniUtils.hpp

This file was deleted.

62 changes: 62 additions & 0 deletions include/API/Utils/Logger.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#pragma once

#include <Singleton.hpp>

#include <Core/Templates/Macros.hpp>
#include <concurrent_queue.h>
#include <optional>
#include <spdlog/spdlog.h>

enum class LogLevel
{
Trace = spdlog::level::trace,
Debug = spdlog::level::debug,
Info = spdlog::level::info,
Warn = spdlog::level::warn,
Err = spdlog::level::err,
};

enum class LogFile
{
// Log to FLHook.log & Console
Default,
// Only log to console
ConsoleOnly,
};

class FLHook;
class DLL Logger final
{
struct LogMessage
{
LogLevel level;
LogFile file;
std::wstring message;
void* retAddress;
};

friend FLHook;
inline static bool consoleAllocated = true;
inline static HANDLE consoleInput;
inline static HANDLE consoleOutput;

inline static std::jthread commandThread;
inline static std::jthread loggingThread;
inline static concurrency::concurrent_queue<LogMessage> logQueue;
inline static concurrency::concurrent_queue<std::wstring> commandQueue;

static std::wstring SetLogSource(void* addr);

// Thread Funcs

static void GetConsoleInput(std::stop_token st);
static void PrintToConsole(std::stop_token st);

static void Init();

public:
static void Log(LogFile file, LogLevel level, std::wstring_view str);
static void Log(LogLevel level, std::wstring_view str);

static std::optional<std::wstring> GetCommand();
};
20 changes: 10 additions & 10 deletions include/API/Utils/Serializer.hpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#pragma once

#include "API/Utils/Logger.hpp"
#include "Core/FLHook.hpp"
#include "Core/Logger.hpp"

namespace nlohmann
{
Expand Down Expand Up @@ -39,7 +39,7 @@ class Serializer
// If no file is provided, we can search the class metadata.
if (fileToSave.empty())
{
FLHook::GetLogger().Log(LogLevel::Err, L"While trying to serialize, a file the fileName was empty.");
Logger::Log(LogLevel::Err, L"While trying to serialize, a file the fileName was empty.");
throw std::invalid_argument("While trying to serialize, a file the fileName was empty.");
}

Expand All @@ -51,15 +51,15 @@ class Serializer
folderPath.remove_filename();
if (!create_directories(folderPath) && !exists(folderPath))
{
FLHook::GetLogger().Log(LogLevel::Warn, std::format(L"Unable to create directories for {} when serializing json.", folderPath.wstring()));
Logger::Log(LogLevel::Warn, std::format(L"Unable to create directories for {} when serializing json.", folderPath.wstring()));
return;
}
}

std::ofstream out(fileToSave);
if (!out.good() || !out.is_open())
{
FLHook::GetLogger().Log(LogLevel::Warn, std::format(L"Unable to open {} for writing.", fileToSave));
Logger::Log(LogLevel::Warn, std::format(L"Unable to open {} for writing.", fileToSave));
return;
}

Expand All @@ -78,15 +78,15 @@ class Serializer
}
catch ([[maybe_unused]] nlohmann::json::parse_error& exc)
{
FLHook::GetLogger().Log(LogLevel::Err, L"Unable to process JSON. It could not be parsed. See log for more detail.");
Logger::Log(LogLevel::Err, L"Unable to process JSON. It could not be parsed. See log for more detail.");
}
catch ([[maybe_unused]] nlohmann::json::type_error& exc)
{
FLHook::GetLogger().Log(LogLevel::Err, L"Unable to process JSON. It could not be parsed. See log for more detail.");
Logger::Log(LogLevel::Err, L"Unable to process JSON. It could not be parsed. See log for more detail.");
}
catch ([[maybe_unused]] nlohmann::json::exception& exc)
{
FLHook::GetLogger().Log(LogLevel::Err, L"Unable to process JSON. It could not be parsed. See log for more detail.");
Logger::Log(LogLevel::Err, L"Unable to process JSON. It could not be parsed. See log for more detail.");
}

return std::make_unique<T>();
Expand All @@ -100,14 +100,14 @@ class Serializer
if (fileName.empty())
{
std::string err = "While trying to deserialize, a file, the fileName was empty.";
FLHook::GetLogger().Log(LogLevel::Err, StringUtils::stows(err));
Logger::Log(LogLevel::Err, StringUtils::stows(err));
throw std::invalid_argument(err);
}

const bool exists = std::filesystem::exists(fileName);
if (!exists && !createIfNotExists)
{
FLHook::GetLogger().Log(LogLevel::Err, std::format(L"Couldn't load JSON File ({})", fileName));
Logger::Log(LogLevel::Err, std::format(L"Couldn't load JSON File ({})", fileName));
return std::make_unique<T>();
}

Expand All @@ -122,7 +122,7 @@ class Serializer
std::wifstream file(fileName);
if (!file || !file.is_open() || !file.good())
{
FLHook::GetLogger().Log(LogLevel::Warn, std::format(L"Unable to open JSON file {}", fileName));
Logger::Log(LogLevel::Warn, std::format(L"Unable to open JSON file {}", fileName));
return std::make_unique<T>();
}

Expand Down
File renamed without changes.
File renamed without changes.
15 changes: 13 additions & 2 deletions include/Core/ClientServerInterface.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ class IServerImplHook

// Base.cpp
static void __stdcall BaseEnter(BaseId baseId, ClientId client);
static void BaseEnterInnerAfter(BaseId baseId, ClientId client);
static void BaseExitInner(BaseId baseId, ClientId client);
static void __stdcall BaseExit(BaseId baseId, ClientId client);
static void __stdcall BaseInfoRequest(unsigned int unk1, unsigned int unk2, bool unk3);
static void __stdcall Dock([[maybe_unused]] const uint& unk1, [[maybe_unused]] const uint& unk2);
Expand All @@ -47,6 +49,7 @@ class IServerImplHook
static void __stdcall DestroyCharacter(const CHARACTER_ID& unk1, ClientId client);
static void __stdcall RequestRankLevel(ClientId client, uint unk1, int unk2);
static void __stdcall RequestPlayerStats(ClientId client, uint unk1, int unk2);
static bool CharacterInfoReqInner(ClientId client, bool);

// ChatHooks.cpp
static bool SubmitChatInner(ClientId from, ulong size, const void* rdlReader, ClientId to, int);
Expand All @@ -58,15 +61,19 @@ class IServerImplHook
static bool OnConnectInner(ClientId client);

// Equipment.cpp
static void ActivateEquipInner(ClientId client, const XActivateEquip& aq);
static void __stdcall ActivateEquip(ClientId client, const XActivateEquip& aq);
static void __stdcall ReqEquipment(const EquipDescList& edl, ClientId client);
static void __stdcall FireWeapon(ClientId client, const XFireWeaponInfo& fwi);
static void __stdcall SetWeaponGroup(ClientId client, uint unk1, int unk2);
static void __stdcall SpRequestUseItem(const SSPUseItem& ui, ClientId client);
static void ActivateThrustersInner(ClientId client, const XActivateThrusters& at);
static void __stdcall ActivateThrusters(ClientId client, const XActivateThrusters& at);
static void ActivateCruiseInner(ClientId client, const XActivateCruise& ac);
static void __stdcall ActivateCruise(ClientId client, const XActivateCruise& ac);

// Goods.cpp
static bool GFGoodSellInner(const SGFGoodSellInfo& gsi, ClientId client);
static void __stdcall GFGoodSell(const SGFGoodSellInfo& unk1, ClientId client);
static void __stdcall GFGoodBuy(const SGFGoodBuyInfo& unk1, ClientId client);
static void __stdcall GFGoodVaporized(const SGFGoodVaporizedInfo& gvi, ClientId client);
Expand All @@ -84,6 +91,7 @@ class IServerImplHook
static void __stdcall JumpInComplete(SystemId systemId, ShipId shipId);

// LaunchComplete.cpp
static void LaunchCompleteInner(BaseId, ShipId shipId);
static void __stdcall LaunchComplete(BaseId baseId, ShipId shipId);

// Location.cpp
Expand Down Expand Up @@ -120,6 +128,8 @@ class IServerImplHook
// OnConnect.cpp
static void __stdcall OnConnect(ClientId client);

static void PlayerLaunchInner(ShipId shipId, ClientId client);
static void PlayerLaunchInnerAfter(ShipId shipId, ClientId client);
// PlayerLaunch.cpp
static void __stdcall PlayerLaunch(ShipId shipId, ClientId client);

Expand All @@ -145,6 +155,7 @@ class IServerImplHook
static void __stdcall RequestTrade(ClientId client1, ClientId client2);
static void __stdcall StopTradeRequest(ClientId client);
static void __stdcall TradeResponse(const unsigned char* unk1, int unk2, ClientId client);
static void TerminateTradeInnerAfter(ClientId client, int accepted);
static void __stdcall TerminateTrade(ClientId client, int accepted);

// Tradelane.cpp
Expand Down Expand Up @@ -183,7 +194,7 @@ class IServerImplHook
#define CallServerPostamble(catchArgs, rval) \
} \
CatchHook({ \
FLHook::GetLogger().Log(LogLevel::Err, std::format(L"Exception in {} on server call", StringUtils::stows(__FUNCTION__))); \
Logger::Log(LogLevel::Err, std::format(L"Exception in {} on server call", StringUtils::stows(__FUNCTION__))); \
bool ret = catchArgs; \
if (!ret) \
{ \
Expand All @@ -209,7 +220,7 @@ class IServerImplHook
{ \
if (client.GetData().disconnected) \
{ \
FLHook::GetLogger().Log(LogLevel::Debug, std::format(L"Ignoring disconnected client in {} id={}", StringUtils::stows(__FUNCTION__), client)); \
Logger::Log(LogLevel::Debug, std::format(L"Ignoring disconnected client in {} id={}", StringUtils::stows(__FUNCTION__), client)); \
return; \
}; \
}
2 changes: 2 additions & 0 deletions include/Core/Commands/ExternalCommandProcessor.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include "AbstractExternalCommandProcessor.hpp"

/*
class ExternalCommandProcessor final : public AbstractExternalCommandProcessor, public Singleton<ExternalCommandProcessor>
{
// clang-format off
Expand All @@ -19,3 +20,4 @@ class ExternalCommandProcessor final : public AbstractExternalCommandProcessor,
std::optional<nlohmann::json> ProcessCommand(const nlohmann::json& command) override;
std::vector<std::wstring_view> GetCommands() override;
};
*/
15 changes: 8 additions & 7 deletions include/Core/Commands/UserCommandProcessor.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ class UserCommandProcessor final : public Singleton<UserCommandProcessor>, publi
void InvitePlayerByName(std::wstring_view invitee);
void InvitePlayerById(ClientId inviteeId);
void FactionInvite(std::wstring_view factionTag);
void DeleteMail(std::wstring_view mailID, std::wstring_view readOnlyDel);
void ReadMail(uint mailId);
void ListMail(int pageNumber, std::wstring_view unread);
// void DeleteMail(std::wstring_view mailID, std::wstring_view readOnlyDel);
// void ReadMail(uint mailId);
// void ListMail(int pageNumber, std::wstring_view unread);
void GiveCash(std::wstring_view characterName, std::wstring_view amount);
void Help(std::wstring_view module, std::wstring_view command);

// clang-format off
constexpr inline static std::array<CommandInfo<UserCommandProcessor>, 15> commands = {
{AddCommand(UserCommandProcessor, L"/ids", GetClientIds, L"/ids", L"Lists all the players and their internal client id numbers."),
AddCommand(UserCommandProcessor, L"/setdiemsgsize", SetDieMessageFontSize, L"/setdiemsgsize [option]",
Expand All @@ -38,13 +39,13 @@ class UserCommandProcessor final : public Singleton<UserCommandProcessor>, publi
AddCommand(UserCommandProcessor, L"/invite", InvitePlayerByName, L"/invite <name>", L"invites specified player to group"),
AddCommand(UserCommandProcessor, L"/invite$", InvitePlayerById, L"/invite$ <id>", L"invites specified player to group by client id"),
AddCommand(UserCommandProcessor, L"/finv", FactionInvite, L"/finv <prefix>", L"invites players that matches the listed prefix in their name"),
AddCommand(UserCommandProcessor, L"/delmail", DeleteMail, L"/delmail <id>", L"deletes specified mail"),
AddCommand(UserCommandProcessor, L"/readmail", ReadMail, L"/readmail <id>", L"prints specified mail."),
AddCommand(UserCommandProcessor, L"/listmail", ListMail, L"/listmail [page]", L"lists the mails of the specified page."),
//AddCommand(UserCommandProcessor, L"/delmail", DeleteMail, L"/delmail <id>", L"deletes specified mail"),
//AddCommand(UserCommandProcessor, L"/readmail", ReadMail, L"/readmail <id>", L"prints specified mail."),
//AddCommand(UserCommandProcessor, L"/listmail", ListMail, L"/listmail [page]", L"lists the mails of the specified page."),
AddCommand(UserCommandProcessor, L"/givecash", GiveCash, L"/givecash <target> <amount>", L"gives speicified amount of cash to named target"),
AddCommand(UserCommandProcessor, L"/help", Help, L"/help [module] [command]", L"gives speicified amount of cash to named target")}
};

// clang-format on
GetCommandsFunc(commands);

template <int N>
Expand Down
13 changes: 13 additions & 0 deletions include/Core/DebugTools.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#pragma once

class DebugTools
{
inline static std::unordered_map<std::string, uint> hashMap;
inline static std::allocator<BYTE> allocator;

static uint CreateIdDetour(const char* str);

public:
DebugTools() = delete;
static void Init();
};
Loading

0 comments on commit 7ec1ae0

Please sign in to comment.