diff options
author | GeckoEidechse <gecko.eidechse+git@pm.me> | 2023-09-17 01:45:16 +0200 |
---|---|---|
committer | GeckoEidechse <gecko.eidechse+git@pm.me> | 2023-09-17 01:45:16 +0200 |
commit | 5cbe9f7317899cd815b38d9f083bc99738fc1dd3 (patch) | |
tree | 9afdce5ae5e76f68be85c25a84afcff86f31d3f8 | |
parent | b7823492e802456d44e4919940267081bf436f08 (diff) | |
download | NorthstarLauncher-5cbe9f7317899cd815b38d9f083bc99738fc1dd3.tar.gz NorthstarLauncher-5cbe9f7317899cd815b38d9f083bc99738fc1dd3.zip |
test ci format checkindentation-test
75 files changed, 2551 insertions, 2551 deletions
diff --git a/NorthstarDLL/client/audio.cpp b/NorthstarDLL/client/audio.cpp index 9fcac982..94ce8353 100644 --- a/NorthstarDLL/client/audio.cpp +++ b/NorthstarDLL/client/audio.cpp @@ -28,8 +28,8 @@ EventOverrideData::EventOverrideData() // Empty stereo 48000 WAVE file unsigned char EMPTY_WAVE[45] = {0x52, 0x49, 0x46, 0x46, 0x25, 0x00, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6D, 0x74, - 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x44, 0xAC, 0x00, 0x00, 0x88, 0x58, - 0x01, 0x00, 0x02, 0x00, 0x10, 0x00, 0x64, 0x61, 0x74, 0x61, 0x74, 0x00, 0x00, 0x00, 0x00}; + 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x44, 0xAC, 0x00, 0x00, 0x88, 0x58, + 0x01, 0x00, 0x02, 0x00, 0x10, 0x00, 0x64, 0x61, 0x74, 0x61, 0x74, 0x00, 0x00, 0x00, 0x00}; EventOverrideData::EventOverrideData(const std::string& data, const fs::path& path) { @@ -45,9 +45,9 @@ EventOverrideData::EventOverrideData(const std::string& data, const fs::path& pa if (!fs::exists(samplesFolder)) { spdlog::error( - "Failed reading audio override file {}: samples folder doesn't exist; should be named the same as the definition file without " - "JSON extension.", - path.string()); + "Failed reading audio override file {}: samples folder doesn't exist; should be named the same as the definition file without " + "JSON extension.", + path.string()); return; } @@ -58,10 +58,10 @@ EventOverrideData::EventOverrideData(const std::string& data, const fs::path& pa if (dataJson.HasParseError()) { spdlog::error( - "Failed reading audio override file {}: encountered parse error \"{}\" at offset {}", - path.string(), - GetParseError_En(dataJson.GetParseError()), - dataJson.GetErrorOffset()); + "Failed reading audio override file {}: encountered parse error \"{}\" at offset {}", + path.string(), + GetParseError_En(dataJson.GetParseError()), + dataJson.GetErrorOffset()); return; } @@ -87,7 +87,7 @@ EventOverrideData::EventOverrideData(const std::string& data, const fs::path& pa if (!eventId.IsString()) { spdlog::error( - "Failed reading audio override file {}: EventId array has a value of invalid type, all must be strings", path.string()); + "Failed reading audio override file {}: EventId array has a value of invalid type, all must be strings", path.string()); return; } @@ -103,8 +103,8 @@ EventOverrideData::EventOverrideData(const std::string& data, const fs::path& pa else { spdlog::error( - "Failed reading audio override file {}: EventId property is of invalid type (must be a string or an array of strings)", - path.string()); + "Failed reading audio override file {}: EventId property is of invalid type (must be a string or an array of strings)", + path.string()); return; } @@ -118,8 +118,8 @@ EventOverrideData::EventOverrideData(const std::string& data, const fs::path& pa if (!eventId.IsString()) { spdlog::error( - "Failed reading audio override file {}: EventIdRegex array has a value of invalid type, all must be strings", - path.string()); + "Failed reading audio override file {}: EventIdRegex array has a value of invalid type, all must be strings", + path.string()); return; } @@ -154,8 +154,8 @@ EventOverrideData::EventOverrideData(const std::string& data, const fs::path& pa else { spdlog::error( - "Failed reading audio override file {}: EventIdRegex property is of invalid type (must be a string or an array of strings)", - path.string()); + "Failed reading audio override file {}: EventIdRegex property is of invalid type (must be a string or an array of strings)", + path.string()); return; } } @@ -181,8 +181,8 @@ EventOverrideData::EventOverrideData(const std::string& data, const fs::path& pa else { spdlog::error( - "Failed reading audio override file {}: AudioSelectionStrategy string must be either \"sequential\" or \"random\"", - path.string()); + "Failed reading audio override file {}: AudioSelectionStrategy string must be either \"sequential\" or \"random\"", + path.string()); return; } } @@ -217,25 +217,25 @@ EventOverrideData::EventOverrideData(const std::string& data, const fs::path& pa // thread off the file read // should we spawn one thread per read? or should there be a cap to the number of reads at once? std::thread readThread( - [pathString, fileSize, data] - { - std::shared_lock lock(g_CustomAudioManager.m_loadingMutex); - std::ifstream wavStream(pathString, std::ios::binary); - - // would be weird if this got hit, since it would've worked previously - if (wavStream.fail()) - { - spdlog::error("Failed async read of audio sample {}", pathString); - return; - } - - // read from after the header first to preserve the empty header, then read the header last - wavStream.seekg(0, std::ios::beg); - wavStream.read(reinterpret_cast<char*>(data), fileSize); - wavStream.close(); - - spdlog::info("Finished async read of audio sample {}", pathString); - }); + [pathString, fileSize, data] + { + std::shared_lock lock(g_CustomAudioManager.m_loadingMutex); + std::ifstream wavStream(pathString, std::ios::binary); + + // would be weird if this got hit, since it would've worked previously + if (wavStream.fail()) + { + spdlog::error("Failed async read of audio sample {}", pathString); + return; + } + + // read from after the header first to preserve the empty header, then read the header last + wavStream.seekg(0, std::ios::beg); + wavStream.read(reinterpret_cast<char*>(data), fileSize); + wavStream.close(); + + spdlog::info("Finished async read of audio sample {}", pathString); + }); readThread.detach(); } @@ -244,13 +244,13 @@ EventOverrideData::EventOverrideData(const std::string& data, const fs::path& pa /* if (dataJson.HasMember("EnableOnLoopedSounds")) { - if (!dataJson["EnableOnLoopedSounds"].IsBool()) - { - spdlog::error("Failed reading audio override file {}: EnableOnLoopedSounds property is of invalid type (must be a bool)", + if (!dataJson["EnableOnLoopedSounds"].IsBool()) + { + spdlog::error("Failed reading audio override file {}: EnableOnLoopedSounds property is of invalid type (must be a bool)", path.string()); return; - } + } - EnableOnLoopedSounds = dataJson["EnableOnLoopedSounds"].GetBool(); + EnableOnLoopedSounds = dataJson["EnableOnLoopedSounds"].GetBool(); } */ @@ -367,7 +367,7 @@ bool ShouldPlayAudioEvent(const char* eventName, const std::shared_ptr<EventOver // forward declare bool __declspec(noinline) __fastcall LoadSampleMetadata_Internal( - uintptr_t parentEvent, void* sample, void* audioBuffer, unsigned int audioBufferLength, int audioType); + uintptr_t parentEvent, void* sample, void* audioBuffer, unsigned int audioBufferLength, int audioType); // DO NOT TOUCH THIS FUNCTION // The actual logic of it in a separate function (forcefully not inlined) to preserve the r12 register, which holds the event pointer. @@ -388,7 +388,7 @@ bool, __fastcall, (void* sample, void* audioBuffer, unsigned int audioBufferLeng // DO NOT INLINE THIS FUNCTION // See comment below. bool __declspec(noinline) __fastcall LoadSampleMetadata_Internal( - uintptr_t parentEvent, void* sample, void* audioBuffer, unsigned int audioBufferLength, int audioType) + uintptr_t parentEvent, void* sample, void* audioBuffer, unsigned int audioBufferLength, int audioType) { char* eventName = (char*)parentEvent + 0x110; diff --git a/NorthstarDLL/client/chatcommand.cpp b/NorthstarDLL/client/chatcommand.cpp index 9cf34e43..49bd8c47 100644 --- a/NorthstarDLL/client/chatcommand.cpp +++ b/NorthstarDLL/client/chatcommand.cpp @@ -29,7 +29,7 @@ void ConCommand_log(const CCommand& args) ON_DLL_LOAD_CLIENT_RELIESON("engine.dll", ClientChatCommand, ConCommand, (CModule module)) { ClientSayText = - module.Offset(0x54780).RCast<void(__fastcall*)(void* a1, const char* message, uint64_t isIngameChat, bool isTeamChat)>(); + module.Offset(0x54780).RCast<void(__fastcall*)(void* a1, const char* message, uint64_t isIngameChat, bool isTeamChat)>(); RegisterConCommand("say", ConCommand_say, "Enters a message in public chat", FCVAR_CLIENTDLL); RegisterConCommand("say_team", ConCommand_say_team, "Enters a message in team chat", FCVAR_CLIENTDLL); RegisterConCommand("log", ConCommand_log, "Log a message to the local chat window", FCVAR_CLIENTDLL); diff --git a/NorthstarDLL/client/clientauthhooks.cpp b/NorthstarDLL/client/clientauthhooks.cpp index e66da6c8..e9cee10a 100644 --- a/NorthstarDLL/client/clientauthhooks.cpp +++ b/NorthstarDLL/client/clientauthhooks.cpp @@ -22,7 +22,7 @@ void, __fastcall, (void* a1)) { // if player has agreed to send token and we aren't already authing, try to auth if (Cvar_ns_has_agreed_to_send_token->GetInt() == AGREED_TO_SEND_TOKEN && - !g_pMasterServerManager->m_bOriginAuthWithMasterServerInProgress) + !g_pMasterServerManager->m_bOriginAuthWithMasterServerInProgress) g_pMasterServerManager->AuthenticateOriginWithMasterServer(R2::g_pLocalPlayerUserID, R2::g_pLocalPlayerOriginToken); // invalidate key so auth will fail @@ -56,8 +56,8 @@ ON_DLL_LOAD_CLIENT_RELIESON("engine.dll", ClientAuthHooks, ConVar, (CModule modu // this cvar will save to cfg once initially agreed with Cvar_ns_has_agreed_to_send_token = new ConVar( - "ns_has_agreed_to_send_token", - "0", - FCVAR_ARCHIVE_PLAYERPROFILE, - "whether the user has agreed to send their origin token to the northstar masterserver"); + "ns_has_agreed_to_send_token", + "0", + FCVAR_ARCHIVE_PLAYERPROFILE, + "whether the user has agreed to send their origin token to the northstar masterserver"); } diff --git a/NorthstarDLL/client/debugoverlay.cpp b/NorthstarDLL/client/debugoverlay.cpp index cdb14693..7bb4adae 100644 --- a/NorthstarDLL/client/debugoverlay.cpp +++ b/NorthstarDLL/client/debugoverlay.cpp @@ -98,24 +98,24 @@ void, __fastcall, (OverlayBase_t * pOverlay)) if (pCurrBox->a > 0) { RenderBox( - pCurrBox->origin, - pCurrBox->angles, - pCurrBox->mins, - pCurrBox->maxs, - Color(pCurrBox->r, pCurrBox->g, pCurrBox->b, pCurrBox->a), - false, - false); + pCurrBox->origin, + pCurrBox->angles, + pCurrBox->mins, + pCurrBox->maxs, + Color(pCurrBox->r, pCurrBox->g, pCurrBox->b, pCurrBox->a), + false, + false); } if (pCurrBox->a < 255) { RenderWireframeBox( - pCurrBox->origin, - pCurrBox->angles, - pCurrBox->mins, - pCurrBox->maxs, - Color(pCurrBox->r, pCurrBox->g, pCurrBox->b, 255), - false, - false); + pCurrBox->origin, + pCurrBox->angles, + pCurrBox->mins, + pCurrBox->maxs, + Color(pCurrBox->r, pCurrBox->g, pCurrBox->b, 255), + false, + false); } } break; diff --git a/NorthstarDLL/client/languagehooks.cpp b/NorthstarDLL/client/languagehooks.cpp index 4251dbbd..cbf846e7 100644 --- a/NorthstarDLL/client/languagehooks.cpp +++ b/NorthstarDLL/client/languagehooks.cpp @@ -62,9 +62,9 @@ char*, __fastcall, ()) if (!CheckLangAudioExists((char*)forcedLanguage)) { spdlog::info( - "User tried to force the language (-language) to \"{}\", but audio for this language doesn't exist and the game is bound " - "to error, falling back to next option...", - forcedLanguage); + "User tried to force the language (-language) to \"{}\", but audio for this language doesn't exist and the game is bound " + "to error, falling back to next option...", + forcedLanguage); } else { @@ -80,9 +80,9 @@ char*, __fastcall, ()) if (!CheckLangAudioExists(lang)) { if (strcmp(lang, "russian") != - 0) // don't log for "russian" since it's the default and that means Origin detection just didn't change it most likely + 0) // don't log for "russian" since it's the default and that means Origin detection just didn't change it most likely spdlog::info( - "Origin detected language \"{}\", but we do not have audio for it installed, falling back to the next option", lang); + "Origin detected language \"{}\", but we do not have audio for it installed, falling back to the next option", lang); } else { @@ -92,14 +92,14 @@ char*, __fastcall, ()) } Tier0_DetectDefaultLanguageType(); // force the global in tier0 to be populated with language inferred from user's system rather than - // defaulting to Russian + // defaulting to Russian canOriginDictateLang = false; // Origin has no say anymore, we will fallback to user's system setup language auto lang = GetGameLanguage(); spdlog::info("Detected system language: {}", lang); if (!CheckLangAudioExists(lang)) { spdlog::warn("Caution, audio for this language does NOT exist. You might want to override your game language with -language " - "command line option."); + "command line option."); auto lang = GetAnyInstalledAudioLanguage(); spdlog::warn("Falling back to the first installed audio language: {}", lang.c_str()); strncpy(ingameLang1, lang.c_str(), 256); diff --git a/NorthstarDLL/client/latencyflex.cpp b/NorthstarDLL/client/latencyflex.cpp index 25e38c7a..0a13717c 100644 --- a/NorthstarDLL/client/latencyflex.cpp +++ b/NorthstarDLL/client/latencyflex.cpp @@ -26,10 +26,10 @@ ON_DLL_LOAD_CLIENT_RELIESON("client.dll", LatencyFlex, ConVar, (CModule module)) if (pLfxModule = LoadLibraryA("latencyflex_layer.dll")) m_winelfx_WaitAndBeginFrame = - reinterpret_cast<void (*)()>(reinterpret_cast<void*>(GetProcAddress(pLfxModule, "lfx_WaitAndBeginFrame"))); + reinterpret_cast<void (*)()>(reinterpret_cast<void*>(GetProcAddress(pLfxModule, "lfx_WaitAndBeginFrame"))); else if (pLfxModule = LoadLibraryA("latencyflex_wine.dll")) m_winelfx_WaitAndBeginFrame = - reinterpret_cast<void (*)()>(reinterpret_cast<void*>(GetProcAddress(pLfxModule, "winelfx_WaitAndBeginFrame"))); + reinterpret_cast<void (*)()>(reinterpret_cast<void*>(GetProcAddress(pLfxModule, "winelfx_WaitAndBeginFrame"))); else { spdlog::info("Unable to load LatencyFleX library, LatencyFleX disabled."); diff --git a/NorthstarDLL/client/localchatwriter.cpp b/NorthstarDLL/client/localchatwriter.cpp index 848d898f..0c1315ea 100644 --- a/NorthstarDLL/client/localchatwriter.cpp +++ b/NorthstarDLL/client/localchatwriter.cpp @@ -73,31 +73,31 @@ typedef void(__fastcall* ConvertANSIToUnicodeType)(LPCSTR ansi, int ansiCharLeng ConvertANSIToUnicodeType ConvertANSIToUnicode; LocalChatWriter::SwatchColor swatchColors[4] = { - LocalChatWriter::MainTextColor, - LocalChatWriter::SameTeamNameColor, - LocalChatWriter::EnemyTeamNameColor, - LocalChatWriter::NetworkNameColor, + LocalChatWriter::MainTextColor, + LocalChatWriter::SameTeamNameColor, + LocalChatWriter::EnemyTeamNameColor, + LocalChatWriter::NetworkNameColor, }; Color darkColors[8] = { - Color {0, 0, 0, 255}, - Color {205, 49, 49, 255}, - Color {13, 188, 121, 255}, - Color {229, 229, 16, 255}, - Color {36, 114, 200, 255}, - Color {188, 63, 188, 255}, - Color {17, 168, 205, 255}, - Color {229, 229, 229, 255}}; + Color {0, 0, 0, 255}, + Color {205, 49, 49, 255}, + Color {13, 188, 121, 255}, + Color {229, 229, 16, 255}, + Color {36, 114, 200, 255}, + Color {188, 63, 188, 255}, + Color {17, 168, 205, 255}, + Color {229, 229, 229, 255}}; Color lightColors[8] = { - Color {102, 102, 102, 255}, - Color {241, 76, 76, 255}, - Color {35, 209, 139, 255}, - Color {245, 245, 67, 255}, - Color {59, 142, 234, 255}, - Color {214, 112, 214, 255}, - Color {41, 184, 219, 255}, - Color {255, 255, 255, 255}}; + Color {102, 102, 102, 255}, + Color {241, 76, 76, 255}, + Color {35, 209, 139, 255}, + Color {245, 245, 67, 255}, + Color {59, 142, 234, 255}, + Color {214, 112, 214, 255}, + Color {41, 184, 219, 255}, + Color {255, 255, 255, 255}}; class AnsiEscapeParser { diff --git a/NorthstarDLL/core/convar/concommand.cpp b/NorthstarDLL/core/convar/concommand.cpp index 732e0d1f..2be16ca5 100644 --- a/NorthstarDLL/core/convar/concommand.cpp +++ b/NorthstarDLL/core/convar/concommand.cpp @@ -123,7 +123,7 @@ char* ConCommandBase::CopyString(const char* szFrom) const } typedef void (*ConCommandConstructorType)( - ConCommand* newCommand, const char* name, FnCommandCallback_t callback, const char* helpString, int flags, void* parent); + ConCommand* newCommand, const char* name, FnCommandCallback_t callback, const char* helpString, int flags, void* parent); ConCommandConstructorType ConCommandConstructor; void RegisterConCommand(const char* name, FnCommandCallback_t callback, const char* helpString, int flags) @@ -136,7 +136,7 @@ void RegisterConCommand(const char* name, FnCommandCallback_t callback, const ch } void RegisterConCommand( - const char* name, FnCommandCallback_t callback, const char* helpString, int flags, FnCommandCompletionCallback completionCallback) + const char* name, FnCommandCallback_t callback, const char* helpString, int flags, FnCommandCompletionCallback completionCallback) { spdlog::info("Registering ConCommand {}", name); diff --git a/NorthstarDLL/core/convar/concommand.h b/NorthstarDLL/core/convar/concommand.h index 89363bc7..4f77451c 100644 --- a/NorthstarDLL/core/convar/concommand.h +++ b/NorthstarDLL/core/convar/concommand.h @@ -84,7 +84,7 @@ typedef void (*FnCommandCallback_t)(const CCommand& command); // Returns 0 to COMMAND_COMPLETION_MAXITEMS worth of completion strings //----------------------------------------------------------------------------- typedef int (*__fastcall FnCommandCompletionCallback)( - const char* partial, char commands[COMMAND_COMPLETION_MAXITEMS][COMMAND_COMPLETION_ITEM_LENGTH]); + const char* partial, char commands[COMMAND_COMPLETION_MAXITEMS][COMMAND_COMPLETION_ITEM_LENGTH]); // From r5reloaded class ConCommandBase @@ -137,4 +137,4 @@ class ConCommand : public ConCommandBase void RegisterConCommand(const char* name, void (*callback)(const CCommand&), const char* helpString, int flags); void RegisterConCommand( - const char* name, void (*callback)(const CCommand&), const char* helpString, int flags, FnCommandCompletionCallback completionCallback); + const char* name, void (*callback)(const CCommand&), const char* helpString, int flags, FnCommandCompletionCallback completionCallback); diff --git a/NorthstarDLL/core/convar/convar.cpp b/NorthstarDLL/core/convar/convar.cpp index 9aaaca66..15d93fa7 100644 --- a/NorthstarDLL/core/convar/convar.cpp +++ b/NorthstarDLL/core/convar/convar.cpp @@ -8,16 +8,16 @@ #include <float.h> typedef void (*ConVarRegisterType)( - ConVar* pConVar, - const char* pszName, - const char* pszDefaultValue, - int nFlags, - const char* pszHelpString, - bool bMin, - float fMin, - bool bMax, - float fMax, - void* pCallback); + ConVar* pConVar, + const char* pszName, + const char* pszDefaultValue, + int nFlags, + const char* pszHelpString, + bool bMin, + float fMin, + bool bMax, + float fMax, + void* pCallback); ConVarRegisterType conVarRegister; typedef void (*ConVarMallocType)(void* pConVarMaloc, int a2, int a3); @@ -64,15 +64,15 @@ ConVar::ConVar(const char* pszName, const char* pszDefaultValue, int nFlags, con // Purpose: constructor //----------------------------------------------------------------------------- ConVar::ConVar( - const char* pszName, - const char* pszDefaultValue, - int nFlags, - const char* pszHelpString, - bool bMin, - float fMin, - bool bMax, - float fMax, - FnChangeCallback_t pCallback) + const char* pszName, + const char* pszDefaultValue, + int nFlags, + const char* pszHelpString, + bool bMin, + float fMin, + bool bMax, + float fMax, + FnChangeCallback_t pCallback) { spdlog::info("Registering Convar {}", pszName); @@ -423,7 +423,7 @@ bool ConVar::SetColorFromString(const char* pszValue) } if (nRGBA[0] >= 0 && nRGBA[0] <= 255 && nRGBA[1] >= 0 && nRGBA[1] <= 255 && nRGBA[2] >= 0 && nRGBA[2] <= 255 && nRGBA[3] >= 0 && - nRGBA[3] <= 255) + nRGBA[3] <= 255) { // printf("*** WOW! Found a color!! ***\n"); diff --git a/NorthstarDLL/core/convar/convar.h b/NorthstarDLL/core/convar/convar.h index 4b00e25f..532f60e7 100644 --- a/NorthstarDLL/core/convar/convar.h +++ b/NorthstarDLL/core/convar/convar.h @@ -20,7 +20,7 @@ // ConVar only #define FCVAR_PROTECTED \ (1 << 5) // It's a server cvar, but we don't send the data since it's a password, etc. Sends 1 if it's not bland/zero, 0 otherwise as - // value. + // value. #define FCVAR_SPONLY (1 << 6) // This cvar cannot be changed by clients connected to a multiplayer server. #define FCVAR_ARCHIVE (1 << 7) // set to cause it to be saved to vars.rc #define FCVAR_NOTIFY (1 << 8) // notifies players when changed @@ -29,8 +29,8 @@ #define FCVAR_PRINTABLEONLY (1 << 10) // This cvar's string cannot contain unprintable characters ( e.g., used for player name etc ). #define FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS \ (1 << 10) // When on concommands this allows remote clients to execute this cmd on the server. - // We are changing the default behavior of concommands to disallow execution by remote clients without - // this flag due to the number existing concommands that can lag or crash the server when clients abuse them. + // We are changing the default behavior of concommands to disallow execution by remote clients without + // this flag due to the number existing concommands that can lag or crash the server when clients abuse them. #define FCVAR_UNLOGGED (1 << 11) // If this is a FCVAR_SERVER, don't log changes to the log file / console if we are creating a log #define FCVAR_NEVER_AS_STRING (1 << 12) // never try to print that cvar @@ -55,7 +55,7 @@ #define FCVAR_SERVER_CAN_EXECUTE \ (1 << 28) // the server is allowed to execute this command on clients via - // ClientCommand/NET_StringCmd/CBaseClientState::ProcessStringCmd. + // ClientCommand/NET_StringCmd/CBaseClientState::ProcessStringCmd. #define FCVAR_SERVER_CANNOT_QUERY \ (1 << 29) // If this is set, then the server is not allowed to query this cvar's value (via IServerPluginHelpers::StartQueryCvarValue). @@ -64,7 +64,7 @@ // FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS in all places this flag was previously used #define FCVAR_CLIENTCMD_CAN_EXECUTE \ (1 << 30) // IVEngineClient::ClientCmd is allowed to execute this command. - // Note: IVEngineClient::ClientCmd_Unrestricted can run any client command. + // Note: IVEngineClient::ClientCmd_Unrestricted can run any client command. #define FCVAR_ACCESSIBLE_FROM_THREADS (1 << 25) // used as a debugging tool necessary to check material system thread convars @@ -75,40 +75,40 @@ // flag => string stuff const std::multimap<int, const char*> g_PrintCommandFlags = { - {FCVAR_UNREGISTERED, "UNREGISTERED"}, - {FCVAR_DEVELOPMENTONLY, "DEVELOPMENTONLY"}, - {FCVAR_GAMEDLL, "GAMEDLL"}, - {FCVAR_CLIENTDLL, "CLIENTDLL"}, - {FCVAR_HIDDEN, "HIDDEN"}, - {FCVAR_PROTECTED, "PROTECTED"}, - {FCVAR_SPONLY, "SPONLY"}, - {FCVAR_ARCHIVE, "ARCHIVE"}, - {FCVAR_NOTIFY, "NOTIFY"}, - {FCVAR_USERINFO, "USERINFO"}, - - // TODO: PRINTABLEONLY and GAMEDLL_FOR_REMOTE_CLIENTS are both 1<<10, one is for vars and one is for commands - // this fucking sucks i think - {FCVAR_PRINTABLEONLY, "PRINTABLEONLY"}, - {FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS, "GAMEDLL_FOR_REMOTE_CLIENTS"}, - - {FCVAR_UNLOGGED, "UNLOGGED"}, - {FCVAR_NEVER_AS_STRING, "NEVER_AS_STRING"}, - {FCVAR_REPLICATED, "REPLICATED"}, - {FCVAR_CHEAT, "CHEAT"}, - {FCVAR_SS, "SS"}, - {FCVAR_DEMO, "DEMO"}, - {FCVAR_DONTRECORD, "DONTRECORD"}, - {FCVAR_SS_ADDED, "SS_ADDED"}, - {FCVAR_RELEASE, "RELEASE"}, - {FCVAR_RELOAD_MATERIALS, "RELOAD_MATERIALS"}, - {FCVAR_RELOAD_TEXTURES, "RELOAD_TEXTURES"}, - {FCVAR_NOT_CONNECTED, "NOT_CONNECTED"}, - {FCVAR_MATERIAL_SYSTEM_THREAD, "MATERIAL_SYSTEM_THREAD"}, - {FCVAR_ARCHIVE_PLAYERPROFILE, "ARCHIVE_PLAYERPROFILE"}, - {FCVAR_SERVER_CAN_EXECUTE, "SERVER_CAN_EXECUTE"}, - {FCVAR_SERVER_CANNOT_QUERY, "SERVER_CANNOT_QUERY"}, - {FCVAR_CLIENTCMD_CAN_EXECUTE, "UNKNOWN"}, - {FCVAR_ACCESSIBLE_FROM_THREADS, "ACCESSIBLE_FROM_THREADS"}}; + {FCVAR_UNREGISTERED, "UNREGISTERED"}, + {FCVAR_DEVELOPMENTONLY, "DEVELOPMENTONLY"}, + {FCVAR_GAMEDLL, "GAMEDLL"}, + {FCVAR_CLIENTDLL, "CLIENTDLL"}, + {FCVAR_HIDDEN, "HIDDEN"}, + {FCVAR_PROTECTED, "PROTECTED"}, + {FCVAR_SPONLY, "SPONLY"}, + {FCVAR_ARCHIVE, "ARCHIVE"}, + {FCVAR_NOTIFY, "NOTIFY"}, + {FCVAR_USERINFO, "USERINFO"}, + + // TODO: PRINTABLEONLY and GAMEDLL_FOR_REMOTE_CLIENTS are both 1<<10, one is for vars and one is for commands + // this fucking sucks i think + {FCVAR_PRINTABLEONLY, "PRINTABLEONLY"}, + {FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS, "GAMEDLL_FOR_REMOTE_CLIENTS"}, + + {FCVAR_UNLOGGED, "UNLOGGED"}, + {FCVAR_NEVER_AS_STRING, "NEVER_AS_STRING"}, + {FCVAR_REPLICATED, "REPLICATED"}, + {FCVAR_CHEAT, "CHEAT"}, + {FCVAR_SS, "SS"}, + {FCVAR_DEMO, "DEMO"}, + {FCVAR_DONTRECORD, "DONTRECORD"}, + {FCVAR_SS_ADDED, "SS_ADDED"}, + {FCVAR_RELEASE, "RELEASE"}, + {FCVAR_RELOAD_MATERIALS, "RELOAD_MATERIALS"}, + {FCVAR_RELOAD_TEXTURES, "RELOAD_TEXTURES"}, + {FCVAR_NOT_CONNECTED, "NOT_CONNECTED"}, + {FCVAR_MATERIAL_SYSTEM_THREAD, "MATERIAL_SYSTEM_THREAD"}, + {FCVAR_ARCHIVE_PLAYERPROFILE, "ARCHIVE_PLAYERPROFILE"}, + {FCVAR_SERVER_CAN_EXECUTE, "SERVER_CAN_EXECUTE"}, + {FCVAR_SERVER_CANNOT_QUERY, "SERVER_CANNOT_QUERY"}, + {FCVAR_CLIENTCMD_CAN_EXECUTE, "UNKNOWN"}, + {FCVAR_ACCESSIBLE_FROM_THREADS, "ACCESSIBLE_FROM_THREADS"}}; //----------------------------------------------------------------------------- // Forward declarations @@ -128,15 +128,15 @@ class ConVar ConVar(void) {}; ConVar(const char* pszName, const char* pszDefaultValue, int nFlags, const char* pszHelpString); ConVar( - const char* pszName, - const char* pszDefaultValue, - int nFlags, - const char* pszHelpString, - bool bMin, - float fMin, - bool bMax, - float fMax, - FnChangeCallback_t pCallback); + const char* pszName, + const char* pszDefaultValue, + int nFlags, + const char* pszHelpString, + bool bMin, + float fMin, + bool bMax, + float fMax, + FnChangeCallback_t pCallback); ~ConVar(void); const char* GetBaseName(void) const; diff --git a/NorthstarDLL/core/filesystem/filesystem.cpp b/NorthstarDLL/core/filesystem/filesystem.cpp index e4da647f..e3b76a45 100644 --- a/NorthstarDLL/core/filesystem/filesystem.cpp +++ b/NorthstarDLL/core/filesystem/filesystem.cpp @@ -74,7 +74,7 @@ void SetNewModSearchPaths(Mod* mod) if ((fs::absolute(mod->m_ModDirectory) / MOD_OVERRIDE_DIR).string().compare(sCurrentModPath)) { AddSearchPath( - &*(*g_pFilesystem), (fs::absolute(mod->m_ModDirectory) / MOD_OVERRIDE_DIR).string().c_str(), "GAME", PATH_ADD_TO_HEAD); + &*(*g_pFilesystem), (fs::absolute(mod->m_ModDirectory) / MOD_OVERRIDE_DIR).string().c_str(), "GAME", PATH_ADD_TO_HEAD); sCurrentModPath = (fs::absolute(mod->m_ModDirectory) / MOD_OVERRIDE_DIR).string(); } } diff --git a/NorthstarDLL/core/filesystem/filesystem.h b/NorthstarDLL/core/filesystem/filesystem.h index ac1c5986..c2c6b7d0 100644 --- a/NorthstarDLL/core/filesystem/filesystem.h +++ b/NorthstarDLL/core/filesystem/filesystem.h @@ -52,7 +52,7 @@ class IFileSystem int (*Read)(IFileSystem::VTable2** fileSystem, void* pOutput, int size, FileHandle_t file); void* unknown[1]; FileHandle_t (*Open)( - IFileSystem::VTable2** fileSystem, const char* pFileName, const char* pOptions, const char* pathID, int64_t unknown); + IFileSystem::VTable2** fileSystem, const char* pFileName, const char* pOptions, const char* pathID, int64_t unknown); void (*Close)(IFileSystem* fileSystem, FileHandle_t file); long long (*Seek)(IFileSystem::VTable2** fileSystem, FileHandle_t file, long long offset, long long whence); void* unknown2[5]; diff --git a/NorthstarDLL/core/filesystem/rpakfilesystem.cpp b/NorthstarDLL/core/filesystem/rpakfilesystem.cpp index 8d50b07a..bb936006 100644 --- a/NorthstarDLL/core/filesystem/rpakfilesystem.cpp +++ b/NorthstarDLL/core/filesystem/rpakfilesystem.cpp @@ -165,7 +165,7 @@ void LoadCustomMapPaks(char** pakName, bool* bNeedToFreePakName) bHasOriginalPak = true; *bNeedToFreePakName = - true; // we can't free this memory until we're done with the pak, so let whatever's calling this deal with it + true; // we can't free this memory until we're done with the pak, so let whatever's calling this deal with it } else g_pPakLoadManager->LoadPakAsync((modPakPath / pak.m_sPakName).string().c_str(), ePakLoadSource::MAP); @@ -210,7 +210,7 @@ int, __fastcall, (char* pPath, void* unknownSingleton, int flags, void* pCallbac // sp_<map> rpaks contain tutorial ghost data // sucks to have to load the entire rpak for that but sp was never meant to be done on dedi if (IsDedicatedServer() && (Tier0::CommandLine()->CheckParm("-nopakdedi") || - strncmp(&originalPath[0], "common", 6) && strncmp(&originalPath[0], "sp_", 3))) + strncmp(&originalPath[0], "common", 6) && strncmp(&originalPath[0], "sp_", 3))) { if (bNeedToFreePakName) delete[] pPath; diff --git a/NorthstarDLL/core/hooks.cpp b/NorthstarDLL/core/hooks.cpp index 4363c0e2..1d251a58 100644 --- a/NorthstarDLL/core/hooks.cpp +++ b/NorthstarDLL/core/hooks.cpp @@ -13,7 +13,7 @@ AUTOHOOK_INIT() // called from the ON_DLL_LOAD macros __dllLoadCallback::__dllLoadCallback( - eDllLoadCallbackSide side, const std::string dllName, DllLoadCallbackFuncType callback, std::string uniqueStr, std::string reliesOn) + eDllLoadCallbackSide side, const std::string dllName, DllLoadCallbackFuncType callback, std::string uniqueStr, std::string reliesOn) { // parse reliesOn array from string std::vector<std::string> reliesOnArray; @@ -78,7 +78,7 @@ void __fileAutohook::DispatchForModule(const char* pModuleName) for (__autohook* hook : hooks) if ((hook->iAddressResolutionMode == __autohook::OFFSET_STRING && !strncmp(pModuleName, hook->pAddrString, iModuleNameLen)) || - (hook->iAddressResolutionMode == __autohook::PROCADDRESS && !strcmp(pModuleName, hook->pModuleName))) + (hook->iAddressResolutionMode == __autohook::PROCADDRESS && !strcmp(pModuleName, hook->pModuleName))) hook->Dispatch(); } @@ -184,7 +184,7 @@ void AddDllLoadCallback(std::string dll, DllLoadCallbackFuncType callback, std:: } void AddDllLoadCallbackForDedicatedServer( - std::string dll, DllLoadCallbackFuncType callback, std::string tag, std::vector<std::string> reliesOn) + std::string dll, DllLoadCallbackFuncType callback, std::string tag, std::vector<std::string> reliesOn) { if (!IsDedicatedServer()) return; @@ -254,13 +254,13 @@ AUTOHOOK_ABSOLUTEADDR(_GetCommandLineA, (LPVOID)GetCommandLineA, LPSTR, WINAPI, // both either space after or ending with if (!isDedi && argBuffer.str().find("-northstar") != std::string::npos) MessageBoxA( - NULL, - "The \"-northstar\" command line option is NOT supposed to go into ns_startup_args.txt file!\n\nThis option is " - "supposed to go into Origin/Steam game launch options, and then you are supposed to launch the original " - "Titanfall2.exe " - "rather than NorthstarLauncher.exe to make use of it.", - "Northstar Warning", - MB_ICONWARNING); + NULL, + "The \"-northstar\" command line option is NOT supposed to go into ns_startup_args.txt file!\n\nThis option is " + "supposed to go into Origin/Steam game launch options, and then you are supposed to launch the original " + "Titanfall2.exe " + "rather than NorthstarLauncher.exe to make use of it.", + "Northstar Warning", + MB_ICONWARNING); args.append(argBuffer.str()); } diff --git a/NorthstarDLL/core/hooks.h b/NorthstarDLL/core/hooks.h index 8721628a..1aac5bf3 100644 --- a/NorthstarDLL/core/hooks.h +++ b/NorthstarDLL/core/hooks.h @@ -9,9 +9,9 @@ void InstallInitialHooks(); typedef void (*DllLoadCallbackFuncType)(CModule moduleAddress); void AddDllLoadCallback(std::string dll, DllLoadCallbackFuncType callback, std::string tag = "", std::vector<std::string> reliesOn = {}); void AddDllLoadCallbackForDedicatedServer( - std::string dll, DllLoadCallbackFuncType callback, std::string tag = "", std::vector<std::string> reliesOn = {}); + std::string dll, DllLoadCallbackFuncType callback, std::string tag = "", std::vector<std::string> reliesOn = {}); void AddDllLoadCallbackForClient( - std::string dll, DllLoadCallbackFuncType callback, std::string tag = "", std::vector<std::string> reliesOn = {}); + std::string dll, DllLoadCallbackFuncType callback, std::string tag = "", std::vector<std::string> reliesOn = {}); void CallAllPendingDLLLoadCallbacks(); @@ -28,11 +28,11 @@ class __dllLoadCallback public: __dllLoadCallback() = delete; __dllLoadCallback( - eDllLoadCallbackSide side, - const std::string dllName, - DllLoadCallbackFuncType callback, - std::string uniqueStr, - std::string reliesOn); + eDllLoadCallbackSide side, + const std::string dllName, + DllLoadCallbackFuncType callback, + std::string uniqueStr, + std::string reliesOn); }; #define __CONCAT3(x, y, z) x##y##z @@ -47,7 +47,7 @@ class __dllLoadCallback namespace \ { \ __dllLoadCallback CONCAT2(__dllLoadCallbackInstance, __LINE__)( \ - side, dllName, CONCAT2(__dllLoadCallback, uniquestr), __STR(uniquestr), reliesOn); \ + side, dllName, CONCAT2(__dllLoadCallback, uniquestr), __STR(uniquestr), reliesOn); \ } \ void CONCAT2(__dllLoadCallback, uniquestr) args @@ -115,7 +115,7 @@ class __autohook __autohook() = delete; __autohook(__fileAutohook* autohook, const char* funcName, LPVOID absoluteAddress, LPVOID* orig, LPVOID func) - : pHookFunc(func), ppOrigFunc(orig), iAbsoluteAddress(absoluteAddress) + : pHookFunc(func), ppOrigFunc(orig), iAbsoluteAddress(absoluteAddress) { iAddressResolutionMode = ABSOLUTE_ADDR; @@ -127,7 +127,7 @@ class __autohook } __autohook(__fileAutohook* autohook, const char* funcName, const char* addrString, LPVOID* orig, LPVOID func) - : pHookFunc(func), ppOrigFunc(orig) + : pHookFunc(func), ppOrigFunc(orig) { iAddressResolutionMode = OFFSET_STRING; @@ -143,7 +143,7 @@ class __autohook } __autohook(__fileAutohook* autohook, const char* funcName, const char* moduleName, const char* procName, LPVOID* orig, LPVOID func) - : pHookFunc(func), ppOrigFunc(orig) + : pHookFunc(func), ppOrigFunc(orig) { iAddressResolutionMode = PROCADDRESS; @@ -221,7 +221,7 @@ class __autohook { \ type(*callingConvention name) args; \ __autohook CONCAT2(__autohook, __LINE__)( \ - &__FILEAUTOHOOK, __STR(name), __STR(addrString), (LPVOID*)&name, (LPVOID)CONCAT2(__autohookfunc, name)); \ + &__FILEAUTOHOOK, __STR(name), __STR(addrString), (LPVOID*)&name, (LPVOID)CONCAT2(__autohookfunc, name)); \ } \ type callingConvention CONCAT2(__autohookfunc, name) args @@ -232,7 +232,7 @@ class __autohook { \ type(*callingConvention name) args; \ __autohook \ - CONCAT2(__autohook, __LINE__)(&__FILEAUTOHOOK, __STR(name), addr, (LPVOID*)&name, (LPVOID)CONCAT2(__autohookfunc, name)); \ + CONCAT2(__autohook, __LINE__)(&__FILEAUTOHOOK, __STR(name), addr, (LPVOID*)&name, (LPVOID)CONCAT2(__autohookfunc, name)); \ } \ type callingConvention CONCAT2(__autohookfunc, name) args @@ -243,7 +243,7 @@ class __autohook { \ type(*callingConvention name) args; \ __autohook CONCAT2(__autohook, __LINE__)( \ - &__FILEAUTOHOOK, __STR(name), __STR(moduleName), __STR(procName), (LPVOID*)&name, (LPVOID)CONCAT2(__autohookfunc, name)); \ + &__FILEAUTOHOOK, __STR(name), __STR(moduleName), __STR(procName), (LPVOID*)&name, (LPVOID)CONCAT2(__autohookfunc, name)); \ } \ type callingConvention CONCAT2(__autohookfunc, name) \ args diff --git a/NorthstarDLL/core/math/bitbuf.h b/NorthstarDLL/core/math/bitbuf.h index 8e8e216f..fbcc1b51 100644 --- a/NorthstarDLL/core/math/bitbuf.h +++ b/NorthstarDLL/core/math/bitbuf.h @@ -7,9 +7,9 @@ INLINE int GetBitForBitnum(int bitNum) { static int bitsForBitnum[] = { - (1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4), (1 << 5), (1 << 6), (1 << 7), (1 << 8), (1 << 9), (1 << 10), - (1 << 11), (1 << 12), (1 << 13), (1 << 14), (1 << 15), (1 << 16), (1 << 17), (1 << 18), (1 << 19), (1 << 20), (1 << 21), - (1 << 22), (1 << 23), (1 << 24), (1 << 25), (1 << 26), (1 << 27), (1 << 28), (1 << 29), (1 << 30), (1 << 31), + (1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4), (1 << 5), (1 << 6), (1 << 7), (1 << 8), (1 << 9), (1 << 10), + (1 << 11), (1 << 12), (1 << 13), (1 << 14), (1 << 15), (1 << 16), (1 << 17), (1 << 18), (1 << 19), (1 << 20), (1 << 21), + (1 << 22), (1 << 23), (1 << 24), (1 << 25), (1 << 26), (1 << 27), (1 << 28), (1 << 29), (1 << 30), (1 << 31), }; return bitsForBitnum[(bitNum) & (BITS_PER_INT - 1)]; @@ -45,39 +45,39 @@ static INLINE u32 LoadLittleDWord(u32* base, size_t dwordIndex) #include <algorithm> static inline const u32 s_nMaskTable[33] = { - 0, - (1 << 1) - 1, - (1 << 2) - 1, - (1 << 3) - 1, - (1 << 4) - 1, - (1 << 5) - 1, - (1 << 6) - 1, - (1 << 7) - 1, - (1 << 8) - 1, - (1 << 9) - 1, - (1 << 10) - 1, - (1 << 11) - 1, - (1 << 12) - 1, - (1 << 13) - 1, - (1 << 14) - 1, - (1 << 15) - 1, - (1 << 16) - 1, - (1 << 17) - 1, - (1 << 18) - 1, - (1 << 19) - 1, - (1 << 20) - 1, - (1 << 21) - 1, - (1 << 22) - 1, - (1 << 23) - 1, - (1 << 24) - 1, - (1 << 25) - 1, - (1 << 26) - 1, - (1 << 27) - 1, - (1 << 28) - 1, - (1 << 29) - 1, - (1 << 30) - 1, - 0x7fffffff, - 0xffffffff, + 0, + (1 << 1) - 1, + (1 << 2) - 1, + (1 << 3) - 1, + (1 << 4) - 1, + (1 << 5) - 1, + (1 << 6) - 1, + (1 << 7) - 1, + (1 << 8) - 1, + (1 << 9) - 1, + (1 << 10) - 1, + (1 << 11) - 1, + (1 << 12) - 1, + (1 << 13) - 1, + (1 << 14) - 1, + (1 << 15) - 1, + (1 << 16) - 1, + (1 << 17) - 1, + (1 << 18) - 1, + (1 << 19) - 1, + (1 << 20) - 1, + (1 << 21) - 1, + (1 << 22) - 1, + (1 << 23) - 1, + (1 << 24) - 1, + (1 << 25) - 1, + (1 << 26) - 1, + (1 << 27) - 1, + (1 << 28) - 1, + (1 << 29) - 1, + (1 << 30) - 1, + 0x7fffffff, + 0xffffffff, }; enum EBitCoordType @@ -273,158 +273,158 @@ class BFRead : public BitBufferBase } /*INLINE float ReadBitCoord() { - i32 intval = 0, fractval = 0, signbit = 0; - float value = 0.0; - - // Read the required integer and fraction flags - intval = ReadOneBit(); - fractval = ReadOneBit(); - - // If we got either parse them, otherwise it's a zero. - if (intval || fractval) { - // Read the sign bit - signbit = ReadOneBit(); - - // If there's an integer, read it in - if (intval) { - // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE] - intval = ReadUBitLong(COORD_INTEGER_BITS) + 1; - } + i32 intval = 0, fractval = 0, signbit = 0; + float value = 0.0; - // If there's a fraction, read it in - if (fractval) { - fractval = ReadUBitLong(COORD_FRACTIONAL_BITS); - } + // Read the required integer and fraction flags + intval = ReadOneBit(); + fractval = ReadOneBit(); - // Calculate the correct floating point value - value = intval + ((float)fractval * COORD_RESOLUTION); + // If we got either parse them, otherwise it's a zero. + if (intval || fractval) { + // Read the sign bit + signbit = ReadOneBit(); - // Fixup the sign if negative. - if (signbit) - value = -value; - } + // If there's an integer, read it in + if (intval) { + // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE] + intval = ReadUBitLong(COORD_INTEGER_BITS) + 1; + } + + // If there's a fraction, read it in + if (fractval) { + fractval = ReadUBitLong(COORD_FRACTIONAL_BITS); + } + + // Calculate the correct floating point value + value = intval + ((float)fractval * COORD_RESOLUTION); + + // Fixup the sign if negative. + if (signbit) + value = -value; + } - return value; + return value; } INLINE float ReadBitCoordMP() { - i32 intval = 0, fractval = 0, signbit = 0; - float value = 0.0; + i32 intval = 0, fractval = 0, signbit = 0; + float value = 0.0; - bool inBounds = ReadOneBit() ? true : false; + bool inBounds = ReadOneBit() ? true : false; - // Read the required integer and fraction flags - intval = ReadOneBit(); + // Read the required integer and fraction flags + intval = ReadOneBit(); - // If we got either parse them, otherwise it's a zero. - if (intval) { - // Read the sign bit - signbit = ReadOneBit(); + // If we got either parse them, otherwise it's a zero. + if (intval) { + // Read the sign bit + signbit = ReadOneBit(); - // If there's an integer, read it in - // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE] - if (inBounds) - value = ReadUBitLong(COORD_INTEGER_BITS_MP) + 1; - else - value = ReadUBitLong(COORD_INTEGER_BITS) + 1; - } + // If there's an integer, read it in + // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE] + if (inBounds) + value = ReadUBitLong(COORD_INTEGER_BITS_MP) + 1; + else + value = ReadUBitLong(COORD_INTEGER_BITS) + 1; + } - // Fixup the sign if negative. - if (signbit) - value = -value; + // Fixup the sign if negative. + if (signbit) + value = -value; - return value; + return value; } INLINE float ReadBitCellCoord(int bits, EBitCoordType coordType) { - bool bIntegral = (coordType == kCW_Integral); - bool bLowPrecision = (coordType == kCW_LowPrecision); + bool bIntegral = (coordType == kCW_Integral); + bool bLowPrecision = (coordType == kCW_LowPrecision); - int intval = 0, fractval = 0; - float value = 0.0; + int intval = 0, fractval = 0; + float value = 0.0; - if (bIntegral) - value = ReadUBitLong(bits); - else { - intval = ReadUBitLong(bits); + if (bIntegral) + value = ReadUBitLong(bits); + else { + intval = ReadUBitLong(bits); - // If there's a fraction, read it in - fractval = ReadUBitLong(bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS); + // If there's a fraction, read it in + fractval = ReadUBitLong(bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS); - // Calculate the correct floating point value - value = intval + ((float)fractval * (bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION)); - } + // Calculate the correct floating point value + value = intval + ((float)fractval * (bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION)); + } - return value; + return value; } INLINE float ReadBitNormal() { - // Read the sign bit - i32 signbit = ReadOneBit(); + // Read the sign bit + i32 signbit = ReadOneBit(); - // Read the fractional part - u32 fractval = ReadUBitLong(NORMAL_FRACTIONAL_BITS); + // Read the fractional part + u32 fractval = ReadUBitLong(NORMAL_FRACTIONAL_BITS); - // Calculate the correct floating point value - float value = (float)fractval * NORMAL_RESOLUTION; + // Calculate the correct floating point value + float value = (float)fractval * NORMAL_RESOLUTION; - // Fixup the sign if negative. - if (signbit) - value = -value; + // Fixup the sign if negative. + if (signbit) + value = -value; - return value; + return value; } INLINE void ReadBitVec3Coord(Vector& fa) { - i32 xflag, yflag, zflag; + i32 xflag, yflag, zflag; - // This vector must be initialized! Otherwise, If any of the flags aren't set, - // the corresponding component will not be read and will be stack garbage. - fa.Init(0, 0, 0); + // This vector must be initialized! Otherwise, If any of the flags aren't set, + // the corresponding component will not be read and will be stack garbage. + fa.Init(0, 0, 0); - xflag = ReadOneBit(); - yflag = ReadOneBit(); - zflag = ReadOneBit(); + xflag = ReadOneBit(); + yflag = ReadOneBit(); + zflag = ReadOneBit(); - if (xflag) - fa[0] = ReadBitCoord(); - if (yflag) - fa[1] = ReadBitCoord(); - if (zflag) - fa[2] = ReadBitCoord(); + if (xflag) + fa[0] = ReadBitCoord(); + if (yflag) + fa[1] = ReadBitCoord(); + if (zflag) + fa[2] = ReadBitCoord(); } INLINE void ReadBitVec3Normal(Vector& fa) { - i32 xflag = ReadOneBit(); - i32 yflag = ReadOneBit(); + i32 xflag = ReadOneBit(); + i32 yflag = ReadOneBit(); - if (xflag) - fa[0] = ReadBitNormal(); - else - fa[0] = 0.0f; + if (xflag) + fa[0] = ReadBitNormal(); + else + fa[0] = 0.0f; - if (yflag) - fa[1] = ReadBitNormal(); - else - fa[1] = 0.0f; + if (yflag) + fa[1] = ReadBitNormal(); + else + fa[1] = 0.0f; - // The first two imply the third (but not its sign) - i32 znegative = ReadOneBit(); + // The first two imply the third (but not its sign) + i32 znegative = ReadOneBit(); - float fafafbfb = fa[0] * fa[0] + fa[1] * fa[1]; - if (fafafbfb < 1.0f) - fa[2] = sqrt(1.0f - fafafbfb); - else - fa[2] = 0.0f; + float fafafbfb = fa[0] * fa[0] + fa[1] * fa[1]; + if (fafafbfb < 1.0f) + fa[2] = sqrt(1.0f - fafafbfb); + else + fa[2] = 0.0f; - if (znegative) - fa[2] = -fa[2]; + if (znegative) + fa[2] = -fa[2]; } INLINE void ReadBitAngles(QAngle& fa) { - Vector tmp; - ReadBitVec3Coord(tmp); - fa.Init(tmp.x, tmp.y, tmp.z); + Vector tmp; + ReadBitVec3Coord(tmp); + fa.Init(tmp.x, tmp.y, tmp.z); }*/ INLINE float ReadBitAngle(int numBits) @@ -970,72 +970,72 @@ class BFWrite : public BitBufferBase } /*INLINE void WriteBitCoord(const float f) { - i32 signbit = (f <= -COORD_RESOLUTION); - i32 intval = (i32)abs(f); - i32 fractval = abs((i32)(f * COORD_DENOMINATOR)) & (COORD_DENOMINATOR - 1); - - // Send the bit flags that indicate whether we have an integer part and/or a fraction part. - WriteOneBit(intval); - WriteOneBit(fractval); - - if (intval || fractval) { - // Send the sign bit - WriteOneBit(signbit); - - // Send the integer if we have one. - if (intval) { - // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] - intval--; - WriteUBitLong((u32)intval, COORD_INTEGER_BITS); - } + i32 signbit = (f <= -COORD_RESOLUTION); + i32 intval = (i32)abs(f); + i32 fractval = abs((i32)(f * COORD_DENOMINATOR)) & (COORD_DENOMINATOR - 1); - // Send the fraction if we have one - if (fractval) { - WriteUBitLong((u32)fractval, COORD_FRACTIONAL_BITS); - } - } + // Send the bit flags that indicate whether we have an integer part and/or a fraction part. + WriteOneBit(intval); + WriteOneBit(fractval); + + if (intval || fractval) { + // Send the sign bit + WriteOneBit(signbit); + + // Send the integer if we have one. + if (intval) { + // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] + intval--; + WriteUBitLong((u32)intval, COORD_INTEGER_BITS); + } + + // Send the fraction if we have one + if (fractval) { + WriteUBitLong((u32)fractval, COORD_FRACTIONAL_BITS); + } + } } INLINE void WriteBitCoordMP(const float f) { - i32 signbit = (f <= -COORD_RESOLUTION); - i32 intval = (i32)abs(f); - i32 fractval = (abs((i32)(f * COORD_DENOMINATOR)) & (COORD_DENOMINATOR - 1)); + i32 signbit = (f <= -COORD_RESOLUTION); + i32 intval = (i32)abs(f); + i32 fractval = (abs((i32)(f * COORD_DENOMINATOR)) & (COORD_DENOMINATOR - 1)); - bool bInBounds = intval < (1 << COORD_INTEGER_BITS_MP); + bool bInBounds = intval < (1 << COORD_INTEGER_BITS_MP); - WriteOneBit(bInBounds); + WriteOneBit(bInBounds); - // Send the sign bit - WriteOneBit(intval); + // Send the sign bit + WriteOneBit(intval); - if (intval) { - WriteOneBit(signbit); + if (intval) { + WriteOneBit(signbit); - // Send the integer if we have one. - // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] - intval--; + // Send the integer if we have one. + // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] + intval--; - if (bInBounds) - WriteUBitLong((u32)intval, COORD_INTEGER_BITS_MP); - else - WriteUBitLong((u32)intval, COORD_INTEGER_BITS); - } + if (bInBounds) + WriteUBitLong((u32)intval, COORD_INTEGER_BITS_MP); + else + WriteUBitLong((u32)intval, COORD_INTEGER_BITS); + } } INLINE void WriteBitCellCoord(const float f, int bits, EBitCoordType coordType) { - bool bIntegral = (coordType == kCW_Integral); - bool bLowPrecision = (coordType == kCW_LowPrecision); + bool bIntegral = (coordType == kCW_Integral); + bool bLowPrecision = (coordType == kCW_LowPrecision); - i32 intval = (i32)abs(f); - i32 fractval = bLowPrecision ? (abs((i32)(f * COORD_DENOMINATOR_LOWPRECISION)) & (COORD_DENOMINATOR_LOWPRECISION - 1)) : + i32 intval = (i32)abs(f); + i32 fractval = bLowPrecision ? (abs((i32)(f * COORD_DENOMINATOR_LOWPRECISION)) & (COORD_DENOMINATOR_LOWPRECISION - 1)) : (abs((i32)(f * COORD_DENOMINATOR)) & (COORD_DENOMINATOR - 1)); - if (bIntegral) - WriteUBitLong((u32)intval, bits); - else { - WriteUBitLong((u32)intval, bits); - WriteUBitLong((u32)fractval, bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS); - } + if (bIntegral) + WriteUBitLong((u32)intval, bits); + else { + WriteUBitLong((u32)intval, bits); + WriteUBitLong((u32)fractval, bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS); + } }*/ INLINE void SeekToBit(int bit) @@ -1048,58 +1048,58 @@ class BFWrite : public BitBufferBase } /*INLINE void WriteBitVec3Coord(const Vector& fa) { - i32 xflag, yflag, zflag; + i32 xflag, yflag, zflag; - xflag = (fa[0] >= COORD_RESOLUTION) || (fa[0] <= -COORD_RESOLUTION); - yflag = (fa[1] >= COORD_RESOLUTION) || (fa[1] <= -COORD_RESOLUTION); - zflag = (fa[2] >= COORD_RESOLUTION) || (fa[2] <= -COORD_RESOLUTION); + xflag = (fa[0] >= COORD_RESOLUTION) || (fa[0] <= -COORD_RESOLUTION); + yflag = (fa[1] >= COORD_RESOLUTION) || (fa[1] <= -COORD_RESOLUTION); + zflag = (fa[2] >= COORD_RESOLUTION) || (fa[2] <= -COORD_RESOLUTION); - WriteOneBit(xflag); - WriteOneBit(yflag); - WriteOneBit(zflag); + WriteOneBit(xflag); + WriteOneBit(yflag); + WriteOneBit(zflag); - if (xflag) - WriteBitCoord(fa[0]); - if (yflag) - WriteBitCoord(fa[1]); - if (zflag) - WriteBitCoord(fa[2]); + if (xflag) + WriteBitCoord(fa[0]); + if (yflag) + WriteBitCoord(fa[1]); + if (zflag) + WriteBitCoord(fa[2]); } INLINE void WriteBitNormal(float f) { - i32 signbit = (f <= -NORMAL_RESOLUTION); + i32 signbit = (f <= -NORMAL_RESOLUTION); - // NOTE: Since +/-1 are valid values for a normal, I'm going to encode that as all ones - u32 fractval = abs((i32)(f * NORMAL_DENOMINATOR)); + // NOTE: Since +/-1 are valid values for a normal, I'm going to encode that as all ones + u32 fractval = abs((i32)(f * NORMAL_DENOMINATOR)); - // clamp.. - if (fractval > NORMAL_DENOMINATOR) - fractval = NORMAL_DENOMINATOR; + // clamp.. + if (fractval > NORMAL_DENOMINATOR) + fractval = NORMAL_DENOMINATOR; - // Send the sign bit - WriteOneBit(signbit); + // Send the sign bit + WriteOneBit(signbit); - // Send the fractional component - WriteUBitLong(fractval, NORMAL_FRACTIONAL_BITS); + // Send the fractional component + WriteUBitLong(fractval, NORMAL_FRACTIONAL_BITS); } INLINE void WriteBitVec3Normal(const Vector& fa) { - i32 xflag, yflag; + i32 xflag, yflag; - xflag = (fa[0] >= NORMAL_RESOLUTION) || (fa[0] <= -NORMAL_RESOLUTION); - yflag = (fa[1] >= NORMAL_RESOLUTION) || (fa[1] <= -NORMAL_RESOLUTION); + xflag = (fa[0] >= NORMAL_RESOLUTION) || (fa[0] <= -NORMAL_RESOLUTION); + yflag = (fa[1] >= NORMAL_RESOLUTION) || (fa[1] <= -NORMAL_RESOLUTION); - WriteOneBit(xflag); - WriteOneBit(yflag); + WriteOneBit(xflag); + WriteOneBit(yflag); - if (xflag) - WriteBitNormal(fa[0]); - if (yflag) - WriteBitNormal(fa[1]); + if (xflag) + WriteBitNormal(fa[0]); + if (yflag) + WriteBitNormal(fa[1]); - // Write z sign bit - i32 signbit = (fa[2] <= -NORMAL_RESOLUTION); - WriteOneBit(signbit); + // Write z sign bit + i32 signbit = (fa[2] <= -NORMAL_RESOLUTION); + WriteOneBit(signbit); }*/ INLINE void WriteBitAngle(float angle, int numBits) @@ -1126,9 +1126,9 @@ class BFWrite : public BitBufferBase } /*INLINE void WriteBitAngles(const QAngle& fa) { - // FIXME: - Vector tmp(fa.x, fa.y, fa.z); - WriteBitVec3Coord(tmp); + // FIXME: + Vector tmp(fa.x, fa.y, fa.z); + WriteBitVec3Coord(tmp); }*/ private: diff --git a/NorthstarDLL/core/memalloc.cpp b/NorthstarDLL/core/memalloc.cpp index 69ce6f54..4f3df43c 100644 --- a/NorthstarDLL/core/memalloc.cpp +++ b/NorthstarDLL/core/memalloc.cpp @@ -16,7 +16,7 @@ extern "C" void* _malloc_base(size_t n) /*extern "C" void* malloc(size_t n) { - return _malloc_base(n); + return _malloc_base(n); }*/ extern "C" void _free_base(void* p) diff --git a/NorthstarDLL/core/memalloc.h b/NorthstarDLL/core/memalloc.h index 7df68429..97f60012 100644 --- a/NorthstarDLL/core/memalloc.h +++ b/NorthstarDLL/core/memalloc.h @@ -1,7 +1,7 @@ #pragma once #include "rapidjson/document.h" -//#include "include/rapidjson/allocators.h" +// #include "include/rapidjson/allocators.h" extern "C" void* _malloc_base(size_t size); extern "C" void* _calloc_base(size_t const count, size_t const size); diff --git a/NorthstarDLL/core/memory.cpp b/NorthstarDLL/core/memory.cpp index 3770586f..603dcd84 100644 --- a/NorthstarDLL/core/memory.cpp +++ b/NorthstarDLL/core/memory.cpp @@ -199,9 +199,9 @@ CModule::CModule(const HMODULE pModule) const IMAGE_SECTION_HEADER& hCurrentSection = hSection[i]; // Get current section. ModuleSections_t moduleSection = ModuleSections_t( - std::string(reinterpret_cast<const char*>(hCurrentSection.Name)), - static_cast<uintptr_t>(m_pModuleBase + hCurrentSection.VirtualAddress), - hCurrentSection.SizeOfRawData); + std::string(reinterpret_cast<const char*>(hCurrentSection.Name)), + static_cast<uintptr_t>(m_pModuleBase + hCurrentSection.VirtualAddress), + hCurrentSection.SizeOfRawData); if (!strcmp((const char*)hCurrentSection.Name, ".text")) m_ExecutableCode = moduleSection; diff --git a/NorthstarDLL/core/memory.h b/NorthstarDLL/core/memory.h index db0a38b3..6aeb1d45 100644 --- a/NorthstarDLL/core/memory.h +++ b/NorthstarDLL/core/memory.h @@ -52,7 +52,7 @@ class CModule : public CMemoryAddress { ModuleSections_t(void) = default; ModuleSections_t(const std::string& svSectionName, uintptr_t pSectionBase, size_t nSectionSize) - : m_svSectionName(svSectionName), m_pSectionBase(pSectionBase), m_nSectionSize(nSectionSize) + : m_svSectionName(svSectionName), m_pSectionBase(pSectionBase), m_nSectionSize(nSectionSize) { } diff --git a/NorthstarDLL/core/structs.h b/NorthstarDLL/core/structs.h index ac29f711..4bdd73c9 100644 --- a/NorthstarDLL/core/structs.h +++ b/NorthstarDLL/core/structs.h @@ -18,8 +18,8 @@ /* OFFSET_STRUCT(Name) { - STRUCT_SIZE(0x100) // Total in-memory struct size - FIELD(0x0, int field) // offset, signature + STRUCT_SIZE(0x100) // Total in-memory struct size + FIELD(0x0, int field) // offset, signature } */ diff --git a/NorthstarDLL/core/tier0.cpp b/NorthstarDLL/core/tier0.cpp index 3b9996a1..d81433de 100644 --- a/NorthstarDLL/core/tier0.cpp +++ b/NorthstarDLL/core/tier0.cpp @@ -19,7 +19,7 @@ void TryCreateGlobalMemAlloc() { // init memalloc stuff CreateGlobalMemAlloc = - reinterpret_cast<CreateGlobalMemAllocType>(GetProcAddress(GetModuleHandleA("tier0.dll"), "CreateGlobalMemAlloc")); + reinterpret_cast<CreateGlobalMemAllocType>(GetProcAddress(GetModuleHandleA("tier0.dll"), "CreateGlobalMemAlloc")); Tier0::g_pMemAllocSingleton = CreateGlobalMemAlloc(); // if it already exists, this returns the preexisting IMemAlloc instance } diff --git a/NorthstarDLL/dedicated/dedicated.cpp b/NorthstarDLL/dedicated/dedicated.cpp index 34282f51..45a5d061 100644 --- a/NorthstarDLL/dedicated/dedicated.cpp +++ b/NorthstarDLL/dedicated/dedicated.cpp @@ -65,7 +65,7 @@ void RunServer(CDedicatedExports* dedicated) g_pEngine->Frame(); std::this_thread::sleep_for( - std::chrono::duration<double, std::ratio<1>>(g_pGlobals->m_flTickInterval - fmin(Tier0::Plat_FloatTime() - frameStart, 0.25))); + std::chrono::duration<double, std::ratio<1>>(g_pGlobals->m_flTickInterval - fmin(Tier0::Plat_FloatTime() - frameStart, 0.25))); } } @@ -75,13 +75,13 @@ class DedicatedConsoleServerPresence : public ServerPresenceReporter void ReportPresence(const ServerPresence* pServerPresence) override { SetConsoleTitleA(fmt::format( - "{} - {} {}/{} players ({})", - pServerPresence->m_sServerName, - pServerPresence->m_MapName, - pServerPresence->m_iPlayerCount, - pServerPresence->m_iMaxPlayers, - pServerPresence->m_PlaylistName) - .c_str()); + "{} - {} {}/{} players ({})", + pServerPresence->m_sServerName, + pServerPresence->m_MapName, + pServerPresence->m_iPlayerCount, + pServerPresence->m_iMaxPlayers, + pServerPresence->m_PlaylistName) + .c_str()); } }; @@ -292,7 +292,7 @@ ON_DLL_LOAD_DEDI("server.dll", DedicatedServerGameDLL, (CModule module)) { module.Offset(0x6BA350).Patch("C3"); // dont load skins.rson from rpak if we don't have rpaks, as loading it will cause a crash module.Offset(0x6BA300).Patch( - "B8 C8 00 00 00 C3"); // return 200 as the number of skins from server.dll + 6BA300, this is the normal value read from - // skins.rson and should be updated when we need it more modular + "B8 C8 00 00 00 C3"); // return 200 as the number of skins from server.dll + 6BA300, this is the normal value read from + // skins.rson and should be updated when we need it more modular } } diff --git a/NorthstarDLL/dedicated/dedicatedmaterialsystem.cpp b/NorthstarDLL/dedicated/dedicatedmaterialsystem.cpp index 5bd6ea93..6d316278 100644 --- a/NorthstarDLL/dedicated/dedicatedmaterialsystem.cpp +++ b/NorthstarDLL/dedicated/dedicatedmaterialsystem.cpp @@ -27,7 +27,7 @@ HRESULT, __stdcall, ( DriverType = 5; // D3D_DRIVER_TYPE_WARP return D3D11CreateDevice( - pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels, SDKVersion, ppDevice, pFeatureLevel, ppImmediateContext); + pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels, SDKVersion, ppDevice, pFeatureLevel, ppImmediateContext); } ON_DLL_LOAD_DEDI("materialsystem_dx11.dll", DedicatedServerMaterialSystem, (CModule module)) diff --git a/NorthstarDLL/engine/hoststate.cpp b/NorthstarDLL/engine/hoststate.cpp index 2ad21fcf..7a0e9be2 100644 --- a/NorthstarDLL/engine/hoststate.cpp +++ b/NorthstarDLL/engine/hoststate.cpp @@ -35,15 +35,15 @@ void ServerStartingOrChangingMap() memset(commandBuf, 0, sizeof(commandBuf)); CCommand tempCommand = *(CCommand*)&commandBuf; if (sLastMode.length() && - CCommand__Tokenize( - tempCommand, fmt::format("exec server/cleanup_gamemode_{}", sLastMode).c_str(), R2::cmd_source_t::kCommandSrcCode)) + CCommand__Tokenize( + tempCommand, fmt::format("exec server/cleanup_gamemode_{}", sLastMode).c_str(), R2::cmd_source_t::kCommandSrcCode)) _Cmd_Exec_f(tempCommand, false, false); memset(commandBuf, 0, sizeof(commandBuf)); if (CCommand__Tokenize( - tempCommand, - fmt::format("exec server/setup_gamemode_{}", sLastMode = Cvar_mp_gamemode->GetString()).c_str(), - R2::cmd_source_t::kCommandSrcCode)) + tempCommand, + fmt::format("exec server/setup_gamemode_{}", sLastMode = Cvar_mp_gamemode->GetString()).c_str(), + R2::cmd_source_t::kCommandSrcCode)) { _Cmd_Exec_f(tempCommand, false, false); } @@ -151,7 +151,7 @@ void, __fastcall, (CHostState* self)) memset(commandBuf, 0, sizeof(commandBuf)); CCommand tempCommand = *(CCommand*)&commandBuf; if (CCommand__Tokenize( - tempCommand, fmt::format("exec server/cleanup_gamemode_{}", sLastMode).c_str(), R2::cmd_source_t::kCommandSrcCode)) + tempCommand, fmt::format("exec server/cleanup_gamemode_{}", sLastMode).c_str(), R2::cmd_source_t::kCommandSrcCode)) { _Cmd_Exec_f(tempCommand, false, false); Cbuf_Execute(); diff --git a/NorthstarDLL/engine/hoststate.h b/NorthstarDLL/engine/hoststate.h index a77385ef..80940aaf 100644 --- a/NorthstarDLL/engine/hoststate.h +++ b/NorthstarDLL/engine/hoststate.h @@ -37,7 +37,7 @@ namespace R2 bool m_bLetToolsOverrideLoadGameEnts; // During a load game, this tells Foundry to override ents that are selected in Hammer. bool m_bSplitScreenConnect; bool m_bGameHasShutDownAndFlushedMemory; // This is false once we load a map into memory, and set to true once the map is unloaded - // and all memory flushed + // and all memory flushed bool m_bWorkshopMapDownloadPending; }; diff --git a/NorthstarDLL/engine/r2engine.cpp b/NorthstarDLL/engine/r2engine.cpp index 67a628fd..06ecacd0 100644 --- a/NorthstarDLL/engine/r2engine.cpp +++ b/NorthstarDLL/engine/r2engine.cpp @@ -19,7 +19,7 @@ namespace R2 server_state_t* g_pServerState; char* g_pModName = - nullptr; // we cant set this up here atm since we dont have an offset to it in engine, instead we store it in IsRespawnMod + nullptr; // we cant set this up here atm since we dont have an offset to it in engine, instead we store it in IsRespawnMod CGlobalVars* g_pGlobals; } // namespace R2 diff --git a/NorthstarDLL/logging/crashhandler.cpp b/NorthstarDLL/logging/crashhandler.cpp index 5d120d1f..6cc0f5d3 100644 --- a/NorthstarDLL/logging/crashhandler.cpp +++ b/NorthstarDLL/logging/crashhandler.cpp @@ -13,16 +13,16 @@ std::shared_ptr<ExceptionLog> storedException {}; #define RUNTIME_EXCEPTION 3765269347 // clang format did this :/ std::map<int, std::string> ExceptionNames = { - {EXCEPTION_ACCESS_VIOLATION, "Access Violation"}, {EXCEPTION_IN_PAGE_ERROR, "Access Violation"}, - {EXCEPTION_ARRAY_BOUNDS_EXCEEDED, "Array bounds exceeded"}, {EXCEPTION_DATATYPE_MISALIGNMENT, "Datatype misalignment"}, - {EXCEPTION_FLT_DENORMAL_OPERAND, "Denormal operand"}, {EXCEPTION_FLT_DIVIDE_BY_ZERO, "Divide by zero (float)"}, - {EXCEPTION_FLT_INEXACT_RESULT, "Inexact float result"}, {EXCEPTION_FLT_INVALID_OPERATION, "Invalid operation"}, - {EXCEPTION_FLT_OVERFLOW, "Numeric overflow (float)"}, {EXCEPTION_FLT_STACK_CHECK, "Stack check"}, - {EXCEPTION_FLT_UNDERFLOW, "Numeric underflow (float)"}, {EXCEPTION_ILLEGAL_INSTRUCTION, "Illegal instruction"}, - {EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero (int)"}, {EXCEPTION_INT_OVERFLOW, "Numeric overfloat (int)"}, - {EXCEPTION_INVALID_DISPOSITION, "Invalid disposition"}, {EXCEPTION_NONCONTINUABLE_EXCEPTION, "Non-continuable exception"}, - {EXCEPTION_PRIV_INSTRUCTION, "Priviledged instruction"}, {EXCEPTION_STACK_OVERFLOW, "Stack overflow"}, - {RUNTIME_EXCEPTION, "Uncaught runtime exception:"}, + {EXCEPTION_ACCESS_VIOLATION, "Access Violation"}, {EXCEPTION_IN_PAGE_ERROR, "Access Violation"}, + {EXCEPTION_ARRAY_BOUNDS_EXCEEDED, "Array bounds exceeded"}, {EXCEPTION_DATATYPE_MISALIGNMENT, "Datatype misalignment"}, + {EXCEPTION_FLT_DENORMAL_OPERAND, "Denormal operand"}, {EXCEPTION_FLT_DIVIDE_BY_ZERO, "Divide by zero (float)"}, + {EXCEPTION_FLT_INEXACT_RESULT, "Inexact float result"}, {EXCEPTION_FLT_INVALID_OPERATION, "Invalid operation"}, + {EXCEPTION_FLT_OVERFLOW, "Numeric overflow (float)"}, {EXCEPTION_FLT_STACK_CHECK, "Stack check"}, + {EXCEPTION_FLT_UNDERFLOW, "Numeric underflow (float)"}, {EXCEPTION_ILLEGAL_INSTRUCTION, "Illegal instruction"}, + {EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero (int)"}, {EXCEPTION_INT_OVERFLOW, "Numeric overfloat (int)"}, + {EXCEPTION_INVALID_DISPOSITION, "Invalid disposition"}, {EXCEPTION_NONCONTINUABLE_EXCEPTION, "Non-continuable exception"}, + {EXCEPTION_PRIV_INSTRUCTION, "Priviledged instruction"}, {EXCEPTION_STACK_OVERFLOW, "Stack overflow"}, + {RUNTIME_EXCEPTION, "Uncaught runtime exception:"}, }; void PrintExceptionLog(ExceptionLog& exc) @@ -67,10 +67,10 @@ void PrintExceptionLog(ExceptionLog& exc) if (!IsDedicatedServer()) MessageBoxA( - 0, - "Northstar has crashed! Crash info can be found in R2Northstar/logs", - "Northstar has crashed!", - MB_ICONERROR | MB_OK | MB_SYSTEMMODAL); + 0, + "Northstar has crashed! Crash info can be found in R2Northstar/logs", + "Northstar has crashed!", + MB_ICONERROR | MB_OK | MB_SYSTEMMODAL); NS::log::FlushLoggers(); } @@ -111,16 +111,16 @@ template <> struct fmt::formatter<M128A> : fmt::formatter<string_view> int v3 = obj.High & INT_MAX; int v4 = obj.High >> 32; return fmt::format_to( - ctx.out(), - "[ {:G}, {:G}, {:G}, {:G}], [ 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x} ]", - *reinterpret_cast<float*>(&v1), - *reinterpret_cast<float*>(&v2), - *reinterpret_cast<float*>(&v3), - *reinterpret_cast<float*>(&v4), - v1, - v2, - v3, - v4); + ctx.out(), + "[ {:G}, {:G}, {:G}, {:G}], [ 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x} ]", + *reinterpret_cast<float*>(&v1), + *reinterpret_cast<float*>(&v2), + *reinterpret_cast<float*>(&v3), + *reinterpret_cast<float*>(&v4), + v1, + v2, + v3, + v4); } }; @@ -153,7 +153,7 @@ void GenerateTrace(ExceptionLog& exc, bool skipErrorHandlingFrames = true, int n if (!haveSkippedErrorHandlingFrames) { if (!strncmp(backtraceModuleFullName, crashedModuleFullName, MAX_PATH) && - !strncmp(backtraceModuleName, crashedModuleName, MAX_PATH)) + !strncmp(backtraceModuleName, crashedModuleName, MAX_PATH)) { haveSkippedErrorHandlingFrames = true; } @@ -248,13 +248,13 @@ void CreateMiniDump(EXCEPTION_POINTERS* exceptionInfo) dumpExceptionInfo.ClientPointers = false; MiniDumpWriteDump( - GetCurrentProcess(), - GetCurrentProcessId(), - hMinidumpFile, - MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory), - &dumpExceptionInfo, - nullptr, - nullptr); + GetCurrentProcess(), + GetCurrentProcessId(), + hMinidumpFile, + MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory), + &dumpExceptionInfo, + nullptr, + nullptr); CloseHandle(hMinidumpFile); } else @@ -344,7 +344,7 @@ void RuntimeExceptionHandler() else { spdlog::error( - "std::current_exception() returned nullptr while being handled by RuntimeExceptionHandler. This should never happen!"); + "std::current_exception() returned nullptr while being handled by RuntimeExceptionHandler. This should never happen!"); std::abort(); } } diff --git a/NorthstarDLL/logging/logging.cpp b/NorthstarDLL/logging/logging.cpp index 2e8605d6..79c6d5c4 100644 --- a/NorthstarDLL/logging/logging.cpp +++ b/NorthstarDLL/logging/logging.cpp @@ -63,7 +63,7 @@ void CreateLogFiles() { spdlog::error("Failed creating log file!"); MessageBoxA( - 0, "Failed creating log file! Make sure the profile directory is writable.", "Northstar Warning", MB_ICONWARNING | MB_OK); + 0, "Failed creating log file! Make sure the profile directory is writable.", "Northstar Warning", MB_ICONWARNING | MB_OK); } } } diff --git a/NorthstarDLL/logging/logging.h b/NorthstarDLL/logging/logging.h index af4b506c..0070c17f 100644 --- a/NorthstarDLL/logging/logging.h +++ b/NorthstarDLL/logging/logging.h @@ -119,13 +119,13 @@ class ExternalConsoleSink : public CustomSink { private: std::map<spdlog::level::level_enum, std::string> m_LogColours = { - {spdlog::level::trace, NS::Colors::TRACE.ToANSIColor()}, - {spdlog::level::debug, NS::Colors::DEBUG.ToANSIColor()}, - {spdlog::level::info, NS::Colors::INFO.ToANSIColor()}, - {spdlog::level::warn, NS::Colors::WARN.ToANSIColor()}, - {spdlog::level::err, NS::Colors::ERR.ToANSIColor()}, - {spdlog::level::critical, NS::Colors::CRIT.ToANSIColor()}, - {spdlog::level::off, NS::Colors::OFF.ToANSIColor()}}; + {spdlog::level::trace, NS::Colors::TRACE.ToANSIColor()}, + {spdlog::level::debug, NS::Colors::DEBUG.ToANSIColor()}, + {spdlog::level::info, NS::Colors::INFO.ToANSIColor()}, + {spdlog::level::warn, NS::Colors::WARN.ToANSIColor()}, + {spdlog::level::err, NS::Colors::ERR.ToANSIColor()}, + {spdlog::level::critical, NS::Colors::CRIT.ToANSIColor()}, + {spdlog::level::off, NS::Colors::OFF.ToANSIColor()}}; std::string default_color = "\033[39;49m"; diff --git a/NorthstarDLL/logging/loghooks.cpp b/NorthstarDLL/logging/loghooks.cpp index 53a85c1b..41712c8a 100644 --- a/NorthstarDLL/logging/loghooks.cpp +++ b/NorthstarDLL/logging/loghooks.cpp @@ -47,26 +47,26 @@ enum class SpewType_t }; const std::unordered_map<SpewType_t, const char*> PrintSpewTypes = { - {SpewType_t::SPEW_MESSAGE, "SPEW_MESSAGE"}, - {SpewType_t::SPEW_WARNING, "SPEW_WARNING"}, - {SpewType_t::SPEW_ASSERT, "SPEW_ASSERT"}, - {SpewType_t::SPEW_ERROR, "SPEW_ERROR"}, - {SpewType_t::SPEW_LOG, "SPEW_LOG"}}; + {SpewType_t::SPEW_MESSAGE, "SPEW_MESSAGE"}, + {SpewType_t::SPEW_WARNING, "SPEW_WARNING"}, + {SpewType_t::SPEW_ASSERT, "SPEW_ASSERT"}, + {SpewType_t::SPEW_ERROR, "SPEW_ERROR"}, + {SpewType_t::SPEW_LOG, "SPEW_LOG"}}; // these are used to define the base text colour for these things const std::unordered_map<SpewType_t, spdlog::level::level_enum> PrintSpewLevels = { - {SpewType_t::SPEW_MESSAGE, spdlog::level::level_enum::info}, - {SpewType_t::SPEW_WARNING, spdlog::level::level_enum::warn}, - {SpewType_t::SPEW_ASSERT, spdlog::level::level_enum::err}, - {SpewType_t::SPEW_ERROR, spdlog::level::level_enum::err}, - {SpewType_t::SPEW_LOG, spdlog::level::level_enum::info}}; + {SpewType_t::SPEW_MESSAGE, spdlog::level::level_enum::info}, + {SpewType_t::SPEW_WARNING, spdlog::level::level_enum::warn}, + {SpewType_t::SPEW_ASSERT, spdlog::level::level_enum::err}, + {SpewType_t::SPEW_ERROR, spdlog::level::level_enum::err}, + {SpewType_t::SPEW_LOG, spdlog::level::level_enum::info}}; const std::unordered_map<SpewType_t, const char> PrintSpewTypes_Short = { - {SpewType_t::SPEW_MESSAGE, 'M'}, - {SpewType_t::SPEW_WARNING, 'W'}, - {SpewType_t::SPEW_ASSERT, 'A'}, - {SpewType_t::SPEW_ERROR, 'E'}, - {SpewType_t::SPEW_LOG, 'L'}}; + {SpewType_t::SPEW_MESSAGE, 'M'}, + {SpewType_t::SPEW_WARNING, 'W'}, + {SpewType_t::SPEW_ASSERT, 'A'}, + {SpewType_t::SPEW_ERROR, 'E'}, + {SpewType_t::SPEW_LOG, 'L'}}; ICenterPrint* pInternalCenterPrint = NULL; diff --git a/NorthstarDLL/logging/sourceconsole.h b/NorthstarDLL/logging/sourceconsole.h index 3abcc470..701a9ac9 100644 --- a/NorthstarDLL/logging/sourceconsole.h +++ b/NorthstarDLL/logging/sourceconsole.h @@ -68,13 +68,13 @@ class SourceConsoleSink : public CustomSink { private: std::map<spdlog::level::level_enum, SourceColor> m_LogColours = { - {spdlog::level::trace, NS::Colors::TRACE.ToSourceColor()}, - {spdlog::level::debug, NS::Colors::DEBUG.ToSourceColor()}, - {spdlog::level::info, NS::Colors::INFO.ToSourceColor()}, - {spdlog::level::warn, NS::Colors::WARN.ToSourceColor()}, - {spdlog::level::err, NS::Colors::ERR.ToSourceColor()}, - {spdlog::level::critical, NS::Colors::CRIT.ToSourceColor()}, - {spdlog::level::off, NS::Colors::OFF.ToSourceColor()}}; + {spdlog::level::trace, NS::Colors::TRACE.ToSourceColor()}, + {spdlog::level::debug, NS::Colors::DEBUG.ToSourceColor()}, + {spdlog::level::info, NS::Colors::INFO.ToSourceColor()}, + {spdlog::level::warn, NS::Colors::WARN.ToSourceColor()}, + {spdlog::level::err, NS::Colors::ERR.ToSourceColor()}, + {spdlog::level::critical, NS::Colors::CRIT.ToSourceColor()}, + {spdlog::level::off, NS::Colors::OFF.ToSourceColor()}}; protected: void custom_sink_it_(const custom_log_msg& msg); diff --git a/NorthstarDLL/masterserver/masterserver.cpp b/NorthstarDLL/masterserver/masterserver.cpp index c2bbdfd8..891879ba 100644 --- a/NorthstarDLL/masterserver/masterserver.cpp +++ b/NorthstarDLL/masterserver/masterserver.cpp @@ -25,15 +25,15 @@ ConVar* Cvar_ns_masterserver_hostname; ConVar* Cvar_ns_curl_log_enable; RemoteServerInfo::RemoteServerInfo( - const char* newId, - const char* newName, - const char* newDescription, - const char* newMap, - const char* newPlaylist, - const char* newRegion, - int newPlayerCount, - int newMaxPlayers, - bool newRequiresPassword) + const char* newId, + const char* newName, + const char* newDescription, + const char* newMap, + const char* newPlaylist, + const char* newRegion, + int newPlayerCount, + int newMaxPlayers, + bool newRequiresPassword) { // passworded servers don't have public ips requiresPassword = newRequiresPassword; @@ -96,68 +96,68 @@ void MasterServerManager::AuthenticateOriginWithMasterServer(const char* uid, co std::string tokenStr(originToken); std::thread requestThread( - [this, uidStr, tokenStr]() - { - spdlog::info("Trying to authenticate with northstar masterserver for user {}", uidStr); - - CURL* curl = curl_easy_init(); - SetCommonHttpClientOptions(curl); - std::string readBuffer; - curl_easy_setopt( - curl, - CURLOPT_URL, - fmt::format("{}/client/origin_auth?id={}&token={}", Cvar_ns_masterserver_hostname->GetString(), uidStr, tokenStr).c_str()); - curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET"); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - - CURLcode result = curl_easy_perform(curl); - - if (result == CURLcode::CURLE_OK) - { - m_bSuccessfullyConnected = true; - - rapidjson_document originAuthInfo; - originAuthInfo.Parse(readBuffer.c_str()); - - if (originAuthInfo.HasParseError()) - { - spdlog::error( - "Failed reading origin auth info response: encountered parse error \"{}\"", - rapidjson::GetParseError_En(originAuthInfo.GetParseError())); - goto REQUEST_END_CLEANUP; - } - - if (!originAuthInfo.IsObject() || !originAuthInfo.HasMember("success")) - { - spdlog::error("Failed reading origin auth info response: malformed response object {}", readBuffer); - goto REQUEST_END_CLEANUP; - } - - if (originAuthInfo["success"].IsTrue() && originAuthInfo.HasMember("token") && originAuthInfo["token"].IsString()) - { - strncpy_s( - m_sOwnClientAuthToken, - sizeof(m_sOwnClientAuthToken), - originAuthInfo["token"].GetString(), - sizeof(m_sOwnClientAuthToken) - 1); - spdlog::info("Northstar origin authentication completed successfully!"); - } - else - spdlog::error("Northstar origin authentication failed"); - } - else - { - spdlog::error("Failed performing northstar origin auth: error {}", curl_easy_strerror(result)); - m_bSuccessfullyConnected = false; - } - - // we goto this instead of returning so we always hit this - REQUEST_END_CLEANUP: - m_bOriginAuthWithMasterServerInProgress = false; - m_bOriginAuthWithMasterServerDone = true; - curl_easy_cleanup(curl); - }); + [this, uidStr, tokenStr]() + { + spdlog::info("Trying to authenticate with northstar masterserver for user {}", uidStr); + + CURL* curl = curl_easy_init(); + SetCommonHttpClientOptions(curl); + std::string readBuffer; + curl_easy_setopt( + curl, + CURLOPT_URL, + fmt::format("{}/client/origin_auth?id={}&token={}", Cvar_ns_masterserver_hostname->GetString(), uidStr, tokenStr).c_str()); + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET"); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); + + CURLcode result = curl_easy_perform(curl); + + if (result == CURLcode::CURLE_OK) + { + m_bSuccessfullyConnected = true; + + rapidjson_document originAuthInfo; + originAuthInfo.Parse(readBuffer.c_str()); + + if (originAuthInfo.HasParseError()) + { + spdlog::error( + "Failed reading origin auth info response: encountered parse error \"{}\"", + rapidjson::GetParseError_En(originAuthInfo.GetParseError())); + goto REQUEST_END_CLEANUP; + } + + if (!originAuthInfo.IsObject() || !originAuthInfo.HasMember("success")) + { + spdlog::error("Failed reading origin auth info response: malformed response object {}", readBuffer); + goto REQUEST_END_CLEANUP; + } + + if (originAuthInfo["success"].IsTrue() && originAuthInfo.HasMember("token") && originAuthInfo["token"].IsString()) + { + strncpy_s( + m_sOwnClientAuthToken, + sizeof(m_sOwnClientAuthToken), + originAuthInfo["token"].GetString(), + sizeof(m_sOwnClientAuthToken) - 1); + spdlog::info("Northstar origin authentication completed successfully!"); + } + else + spdlog::error("Northstar origin authentication failed"); + } + else + { + spdlog::error("Failed performing northstar origin auth: error {}", curl_easy_strerror(result)); + m_bSuccessfullyConnected = false; + } + + // we goto this instead of returning so we always hit this + REQUEST_END_CLEANUP: + m_bOriginAuthWithMasterServerInProgress = false; + m_bOriginAuthWithMasterServerDone = true; + curl_easy_cleanup(curl); + }); requestThread.detach(); } @@ -168,164 +168,164 @@ void MasterServerManager::RequestServerList() m_bScriptRequestingServerList = true; std::thread requestThread( - [this]() - { - // make sure we never have 2 threads writing at once - // i sure do hope this is actually threadsafe - while (m_bRequestingServerList) - Sleep(100); - - m_bRequestingServerList = true; - m_bScriptRequestingServerList = true; - - spdlog::info("Requesting server list from {}", Cvar_ns_masterserver_hostname->GetString()); - - CURL* curl = curl_easy_init(); - SetCommonHttpClientOptions(curl); - - std::string readBuffer; - curl_easy_setopt(curl, CURLOPT_URL, fmt::format("{}/client/servers", Cvar_ns_masterserver_hostname->GetString()).c_str()); - curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET"); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - - CURLcode result = curl_easy_perform(curl); - - if (result == CURLcode::CURLE_OK) - { - m_bSuccessfullyConnected = true; - - rapidjson_document serverInfoJson; - serverInfoJson.Parse(readBuffer.c_str()); - - if (serverInfoJson.HasParseError()) - { - spdlog::error( - "Failed reading masterserver response: encountered parse error \"{}\"", - rapidjson::GetParseError_En(serverInfoJson.GetParseError())); - goto REQUEST_END_CLEANUP; - } - - if (serverInfoJson.IsObject() && serverInfoJson.HasMember("error")) - { - spdlog::error("Failed reading masterserver response: got fastify error response"); - spdlog::error(readBuffer); - goto REQUEST_END_CLEANUP; - } - - if (!serverInfoJson.IsArray()) - { - spdlog::error("Failed reading masterserver response: root object is not an array"); - goto REQUEST_END_CLEANUP; - } - - rapidjson::GenericArray<false, rapidjson_document::GenericValue> serverArray = serverInfoJson.GetArray(); - - spdlog::info("Got {} servers", serverArray.Size()); - - for (auto& serverObj : serverArray) - { - if (!serverObj.IsObject()) - { - spdlog::error("Failed reading masterserver response: member of server array is not an object"); - goto REQUEST_END_CLEANUP; - } - - // todo: verify json props are fine before adding to m_remoteServers - if (!serverObj.HasMember("id") || !serverObj["id"].IsString() || !serverObj.HasMember("name") || - !serverObj["name"].IsString() || !serverObj.HasMember("description") || !serverObj["description"].IsString() || - !serverObj.HasMember("map") || !serverObj["map"].IsString() || !serverObj.HasMember("playlist") || - !serverObj["playlist"].IsString() || !serverObj.HasMember("playerCount") || !serverObj["playerCount"].IsNumber() || - !serverObj.HasMember("maxPlayers") || !serverObj["maxPlayers"].IsNumber() || !serverObj.HasMember("hasPassword") || - !serverObj["hasPassword"].IsBool() || !serverObj.HasMember("modInfo") || !serverObj["modInfo"].HasMember("Mods") || - !serverObj["modInfo"]["Mods"].IsArray()) - { - spdlog::error("Failed reading masterserver response: malformed server object"); - continue; - }; - - const char* id = serverObj["id"].GetString(); - - RemoteServerInfo* newServer = nullptr; - - bool createNewServerInfo = true; - for (RemoteServerInfo& server : m_vRemoteServers) - { - // if server already exists, update info rather than adding to it - if (!strncmp((const char*)server.id, id, 32)) - { - server = RemoteServerInfo( - id, - serverObj["name"].GetString(), - serverObj["description"].GetString(), - serverObj["map"].GetString(), - serverObj["playlist"].GetString(), - (serverObj.HasMember("region") && serverObj["region"].IsString()) ? serverObj["region"].GetString() : "", - serverObj["playerCount"].GetInt(), - serverObj["maxPlayers"].GetInt(), - serverObj["hasPassword"].IsTrue()); - newServer = &server; - createNewServerInfo = false; - break; - } - } - - // server didn't exist - if (createNewServerInfo) - newServer = &m_vRemoteServers.emplace_back( - id, - serverObj["name"].GetString(), - serverObj["description"].GetString(), - serverObj["map"].GetString(), - serverObj["playlist"].GetString(), - (serverObj.HasMember("region") && serverObj["region"].IsString()) ? serverObj["region"].GetString() : "", - serverObj["playerCount"].GetInt(), - serverObj["maxPlayers"].GetInt(), - serverObj["hasPassword"].IsTrue()); - - newServer->requiredMods.clear(); - for (auto& requiredMod : serverObj["modInfo"]["Mods"].GetArray()) - { - RemoteModInfo modInfo; - - if (!requiredMod.HasMember("RequiredOnClient") || !requiredMod["RequiredOnClient"].IsTrue()) - continue; - - if (!requiredMod.HasMember("Name") || !requiredMod["Name"].IsString()) - continue; - modInfo.Name = requiredMod["Name"].GetString(); - - if (!requiredMod.HasMember("Version") || !requiredMod["Version"].IsString()) - continue; - modInfo.Version = requiredMod["Version"].GetString(); - - newServer->requiredMods.push_back(modInfo); - } - // Can probably re-enable this later with a -verbose flag, but slows down loading of the server browser quite a bit as - // is - // spdlog::info( - // "Server {} on map {} with playlist {} has {}/{} players", serverObj["name"].GetString(), - // serverObj["map"].GetString(), serverObj["playlist"].GetString(), serverObj["playerCount"].GetInt(), - // serverObj["maxPlayers"].GetInt()); - } - - std::sort( - m_vRemoteServers.begin(), - m_vRemoteServers.end(), - [](RemoteServerInfo& a, RemoteServerInfo& b) { return a.playerCount > b.playerCount; }); - } - else - { - spdlog::error("Failed requesting servers: error {}", curl_easy_strerror(result)); - m_bSuccessfullyConnected = false; - } - - // we goto this instead of returning so we always hit this - REQUEST_END_CLEANUP: - m_bRequestingServerList = false; - m_bScriptRequestingServerList = false; - curl_easy_cleanup(curl); - }); + [this]() + { + // make sure we never have 2 threads writing at once + // i sure do hope this is actually threadsafe + while (m_bRequestingServerList) + Sleep(100); + + m_bRequestingServerList = true; + m_bScriptRequestingServerList = true; + + spdlog::info("Requesting server list from {}", Cvar_ns_masterserver_hostname->GetString()); + + CURL* curl = curl_easy_init(); + SetCommonHttpClientOptions(curl); + + std::string readBuffer; + curl_easy_setopt(curl, CURLOPT_URL, fmt::format("{}/client/servers", Cvar_ns_masterserver_hostname->GetString()).c_str()); + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET"); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); + + CURLcode result = curl_easy_perform(curl); + + if (result == CURLcode::CURLE_OK) + { + m_bSuccessfullyConnected = true; + + rapidjson_document serverInfoJson; + serverInfoJson.Parse(readBuffer.c_str()); + + if (serverInfoJson.HasParseError()) + { + spdlog::error( + "Failed reading masterserver response: encountered parse error \"{}\"", + rapidjson::GetParseError_En(serverInfoJson.GetParseError())); + goto REQUEST_END_CLEANUP; + } + + if (serverInfoJson.IsObject() && serverInfoJson.HasMember("error")) + { + spdlog::error("Failed reading masterserver response: got fastify error response"); + spdlog::error(readBuffer); + goto REQUEST_END_CLEANUP; + } + + if (!serverInfoJson.IsArray()) + { + spdlog::error("Failed reading masterserver response: root object is not an array"); + goto REQUEST_END_CLEANUP; + } + + rapidjson::GenericArray<false, rapidjson_document::GenericValue> serverArray = serverInfoJson.GetArray(); + + spdlog::info("Got {} servers", serverArray.Size()); + + for (auto& serverObj : serverArray) + { + if (!serverObj.IsObject()) + { + spdlog::error("Failed reading masterserver response: member of server array is not an object"); + goto REQUEST_END_CLEANUP; + } + + // todo: verify json props are fine before adding to m_remoteServers + if (!serverObj.HasMember("id") || !serverObj["id"].IsString() || !serverObj.HasMember("name") || + !serverObj["name"].IsString() || !serverObj.HasMember("description") || !serverObj["description"].IsString() || + !serverObj.HasMember("map") || !serverObj["map"].IsString() || !serverObj.HasMember("playlist") || + !serverObj["playlist"].IsString() || !serverObj.HasMember("playerCount") || !serverObj["playerCount"].IsNumber() || + !serverObj.HasMember("maxPlayers") || !serverObj["maxPlayers"].IsNumber() || !serverObj.HasMember("hasPassword") || + !serverObj["hasPassword"].IsBool() || !serverObj.HasMember("modInfo") || !serverObj["modInfo"].HasMember("Mods") || + !serverObj["modInfo"]["Mods"].IsArray()) + { + spdlog::error("Failed reading masterserver response: malformed server object"); + continue; + }; + + const char* id = serverObj["id"].GetString(); + + RemoteServerInfo* newServer = nullptr; + + bool createNewServerInfo = true; + for (RemoteServerInfo& server : m_vRemoteServers) + { + // if server already exists, update info rather than adding to it + if (!strncmp((const char*)server.id, id, 32)) + { + server = RemoteServerInfo( + id, + serverObj["name"].GetString(), + serverObj["description"].GetString(), + serverObj["map"].GetString(), + serverObj["playlist"].GetString(), + (serverObj.HasMember("region") && serverObj["region"].IsString()) ? serverObj["region"].GetString() : "", + serverObj["playerCount"].GetInt(), + serverObj["maxPlayers"].GetInt(), + serverObj["hasPassword"].IsTrue()); + newServer = &server; + createNewServerInfo = false; + break; + } + } + + // server didn't exist + if (createNewServerInfo) + newServer = &m_vRemoteServers.emplace_back( + id, + serverObj["name"].GetString(), + serverObj["description"].GetString(), + serverObj["map"].GetString(), + serverObj["playlist"].GetString(), + (serverObj.HasMember("region") && serverObj["region"].IsString()) ? serverObj["region"].GetString() : "", + serverObj["playerCount"].GetInt(), + serverObj["maxPlayers"].GetInt(), + serverObj["hasPassword"].IsTrue()); + + newServer->requiredMods.clear(); + for (auto& requiredMod : serverObj["modInfo"]["Mods"].GetArray()) + { + RemoteModInfo modInfo; + + if (!requiredMod.HasMember("RequiredOnClient") || !requiredMod["RequiredOnClient"].IsTrue()) + continue; + + if (!requiredMod.HasMember("Name") || !requiredMod["Name"].IsString()) + continue; + modInfo.Name = requiredMod["Name"].GetString(); + + if (!requiredMod.HasMember("Version") || !requiredMod["Version"].IsString()) + continue; + modInfo.Version = requiredMod["Version"].GetString(); + + newServer->requiredMods.push_back(modInfo); + } + // Can probably re-enable this later with a -verbose flag, but slows down loading of the server browser quite a bit as + // is + // spdlog::info( + // "Server {} on map {} with playlist {} has {}/{} players", serverObj["name"].GetString(), + // serverObj["map"].GetString(), serverObj["playlist"].GetString(), serverObj["playerCount"].GetInt(), + // serverObj["maxPlayers"].GetInt()); + } + + std::sort( + m_vRemoteServers.begin(), + m_vRemoteServers.end(), + [](RemoteServerInfo& a, RemoteServerInfo& b) { return a.playerCount > b.playerCount; }); + } + else + { + spdlog::error("Failed requesting servers: error {}", curl_easy_strerror(result)); + m_bSuccessfullyConnected = false; + } + + // we goto this instead of returning so we always hit this + REQUEST_END_CLEANUP: + m_bRequestingServerList = false; + m_bScriptRequestingServerList = false; + curl_easy_cleanup(curl); + }); requestThread.detach(); } @@ -335,108 +335,108 @@ void MasterServerManager::RequestMainMenuPromos() m_bHasMainMenuPromoData = false; std::thread requestThread( - [this]() - { - while (m_bOriginAuthWithMasterServerInProgress || !m_bOriginAuthWithMasterServerDone) - Sleep(500); - - CURL* curl = curl_easy_init(); - SetCommonHttpClientOptions(curl); - - std::string readBuffer; - curl_easy_setopt( - curl, CURLOPT_URL, fmt::format("{}/client/mainmenupromos", Cvar_ns_masterserver_hostname->GetString()).c_str()); - curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET"); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - - CURLcode result = curl_easy_perform(curl); - - if (result == CURLcode::CURLE_OK) - { - m_bSuccessfullyConnected = true; - - rapidjson_document mainMenuPromoJson; - mainMenuPromoJson.Parse(readBuffer.c_str()); - - if (mainMenuPromoJson.HasParseError()) - { - spdlog::error( - "Failed reading masterserver main menu promos response: encountered parse error \"{}\"", - rapidjson::GetParseError_En(mainMenuPromoJson.GetParseError())); - goto REQUEST_END_CLEANUP; - } - - if (!mainMenuPromoJson.IsObject()) - { - spdlog::error("Failed reading masterserver main menu promos response: root object is not an object"); - goto REQUEST_END_CLEANUP; - } - - if (mainMenuPromoJson.HasMember("error")) - { - spdlog::error("Failed reading masterserver response: got fastify error response"); - spdlog::error(readBuffer); - goto REQUEST_END_CLEANUP; - } - - if (!mainMenuPromoJson.HasMember("newInfo") || !mainMenuPromoJson["newInfo"].IsObject() || - !mainMenuPromoJson["newInfo"].HasMember("Title1") || !mainMenuPromoJson["newInfo"]["Title1"].IsString() || - !mainMenuPromoJson["newInfo"].HasMember("Title2") || !mainMenuPromoJson["newInfo"]["Title2"].IsString() || - !mainMenuPromoJson["newInfo"].HasMember("Title3") || !mainMenuPromoJson["newInfo"]["Title3"].IsString() || - - !mainMenuPromoJson.HasMember("largeButton") || !mainMenuPromoJson["largeButton"].IsObject() || - !mainMenuPromoJson["largeButton"].HasMember("Title") || !mainMenuPromoJson["largeButton"]["Title"].IsString() || - !mainMenuPromoJson["largeButton"].HasMember("Text") || !mainMenuPromoJson["largeButton"]["Text"].IsString() || - !mainMenuPromoJson["largeButton"].HasMember("Url") || !mainMenuPromoJson["largeButton"]["Url"].IsString() || - !mainMenuPromoJson["largeButton"].HasMember("ImageIndex") || - !mainMenuPromoJson["largeButton"]["ImageIndex"].IsNumber() || - - !mainMenuPromoJson.HasMember("smallButton1") || !mainMenuPromoJson["smallButton1"].IsObject() || - !mainMenuPromoJson["smallButton1"].HasMember("Title") || !mainMenuPromoJson["smallButton1"]["Title"].IsString() || - !mainMenuPromoJson["smallButton1"].HasMember("Url") || !mainMenuPromoJson["smallButton1"]["Url"].IsString() || - !mainMenuPromoJson["smallButton1"].HasMember("ImageIndex") || - !mainMenuPromoJson["smallButton1"]["ImageIndex"].IsNumber() || - - !mainMenuPromoJson.HasMember("smallButton2") || !mainMenuPromoJson["smallButton2"].IsObject() || - !mainMenuPromoJson["smallButton2"].HasMember("Title") || !mainMenuPromoJson["smallButton2"]["Title"].IsString() || - !mainMenuPromoJson["smallButton2"].HasMember("Url") || !mainMenuPromoJson["smallButton2"]["Url"].IsString() || - !mainMenuPromoJson["smallButton2"].HasMember("ImageIndex") || - !mainMenuPromoJson["smallButton2"]["ImageIndex"].IsNumber()) - { - spdlog::error("Failed reading masterserver main menu promos response: malformed json object"); - goto REQUEST_END_CLEANUP; - } - - m_sMainMenuPromoData.newInfoTitle1 = mainMenuPromoJson["newInfo"]["Title1"].GetString(); - m_sMainMenuPromoData.newInfoTitle2 = mainMenuPromoJson["newInfo"]["Title2"].GetString(); - m_sMainMenuPromoData.newInfoTitle3 = mainMenuPromoJson["newInfo"]["Title3"].GetString(); - - m_sMainMenuPromoData.largeButtonTitle = mainMenuPromoJson["largeButton"]["Title"].GetString(); - m_sMainMenuPromoData.largeButtonText = mainMenuPromoJson["largeButton"]["Text"].GetString(); - m_sMainMenuPromoData.largeButtonUrl = mainMenuPromoJson["largeButton"]["Url"].GetString(); - m_sMainMenuPromoData.largeButtonImageIndex = mainMenuPromoJson["largeButton"]["ImageIndex"].GetInt(); - - m_sMainMenuPromoData.smallButton1Title = mainMenuPromoJson["smallButton1"]["Title"].GetString(); - m_sMainMenuPromoData.smallButton1Url = mainMenuPromoJson["smallButton1"]["Url"].GetString(); - m_sMainMenuPromoData.smallButton1ImageIndex = mainMenuPromoJson["smallButton1"]["ImageIndex"].GetInt(); - - m_sMainMenuPromoData.smallButton2Title = mainMenuPromoJson["smallButton2"]["Title"].GetString(); - m_sMainMenuPromoData.smallButton2Url = mainMenuPromoJson["smallButton2"]["Url"].GetString(); - m_sMainMenuPromoData.smallButton2ImageIndex = mainMenuPromoJson["smallButton2"]["ImageIndex"].GetInt(); - - m_bHasMainMenuPromoData = true; - } - else - { - spdlog::error("Failed requesting main menu promos: error {}", curl_easy_strerror(result)); - m_bSuccessfullyConnected = false; - } - - REQUEST_END_CLEANUP: - // nothing lol - curl_easy_cleanup(curl); - }); + [this]() + { + while (m_bOriginAuthWithMasterServerInProgress || !m_bOriginAuthWithMasterServerDone) + Sleep(500); + + CURL* curl = curl_easy_init(); + SetCommonHttpClientOptions(curl); + + std::string readBuffer; + curl_easy_setopt( + curl, CURLOPT_URL, fmt::format("{}/client/mainmenupromos", Cvar_ns_masterserver_hostname->GetString()).c_str()); + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET"); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); + + CURLcode result = curl_easy_perform(curl); + + if (result == CURLcode::CURLE_OK) + { + m_bSuccessfullyConnected = true; + + rapidjson_document mainMenuPromoJson; + mainMenuPromoJson.Parse(readBuffer.c_str()); + + if (mainMenuPromoJson.HasParseError()) + { + spdlog::error( + "Failed reading masterserver main menu promos response: encountered parse error \"{}\"", + rapidjson::GetParseError_En(mainMenuPromoJson.GetParseError())); + goto REQUEST_END_CLEANUP; + } + + if (!mainMenuPromoJson.IsObject()) + { + spdlog::error("Failed reading masterserver main menu promos response: root object is not an object"); + goto REQUEST_END_CLEANUP; + } + + if (mainMenuPromoJson.HasMember("error")) + { + spdlog::error("Failed reading masterserver response: got fastify error response"); + spdlog::error(readBuffer); + goto REQUEST_END_CLEANUP; + } + + if (!mainMenuPromoJson.HasMember("newInfo") || !mainMenuPromoJson["newInfo"].IsObject() || + !mainMenuPromoJson["newInfo"].HasMember("Title1") || !mainMenuPromoJson["newInfo"]["Title1"].IsString() || + !mainMenuPromoJson["newInfo"].HasMember("Title2") || !mainMenuPromoJson["newInfo"]["Title2"].IsString() || + !mainMenuPromoJson["newInfo"].HasMember("Title3") || !mainMenuPromoJson["newInfo"]["Title3"].IsString() || + + !mainMenuPromoJson.HasMember("largeButton") || !mainMenuPromoJson["largeButton"].IsObject() || + !mainMenuPromoJson["largeButton"].HasMember("Title") || !mainMenuPromoJson["largeButton"]["Title"].IsString() || + !mainMenuPromoJson["largeButton"].HasMember("Text") || !mainMenuPromoJson["largeButton"]["Text"].IsString() || + !mainMenuPromoJson["largeButton"].HasMember("Url") || !mainMenuPromoJson["largeButton"]["Url"].IsString() || + !mainMenuPromoJson["largeButton"].HasMember("ImageIndex") || + !mainMenuPromoJson["largeButton"]["ImageIndex"].IsNumber() || + + !mainMenuPromoJson.HasMember("smallButton1") || !mainMenuPromoJson["smallButton1"].IsObject() || + !mainMenuPromoJson["smallButton1"].HasMember("Title") || !mainMenuPromoJson["smallButton1"]["Title"].IsString() || + !mainMenuPromoJson["smallButton1"].HasMember("Url") || !mainMenuPromoJson["smallButton1"]["Url"].IsString() || + !mainMenuPromoJson["smallButton1"].HasMember("ImageIndex") || + !mainMenuPromoJson["smallButton1"]["ImageIndex"].IsNumber() || + + !mainMenuPromoJson.HasMember("smallButton2") || !mainMenuPromoJson["smallButton2"].IsObject() || + !mainMenuPromoJson["smallButton2"].HasMember("Title") || !mainMenuPromoJson["smallButton2"]["Title"].IsString() || + !mainMenuPromoJson["smallButton2"].HasMember("Url") || !mainMenuPromoJson["smallButton2"]["Url"].IsString() || + !mainMenuPromoJson["smallButton2"].HasMember("ImageIndex") || + !mainMenuPromoJson["smallButton2"]["ImageIndex"].IsNumber()) + { + spdlog::error("Failed reading masterserver main menu promos response: malformed json object"); + goto REQUEST_END_CLEANUP; + } + + m_sMainMenuPromoData.newInfoTitle1 = mainMenuPromoJson["newInfo"]["Title1"].GetString(); + m_sMainMenuPromoData.newInfoTitle2 = mainMenuPromoJson["newInfo"]["Title2"].GetString(); + m_sMainMenuPromoData.newInfoTitle3 = mainMenuPromoJson["newInfo"]["Title3"].GetString(); + + m_sMainMenuPromoData.largeButtonTitle = mainMenuPromoJson["largeButton"]["Title"].GetString(); + m_sMainMenuPromoData.largeButtonText = mainMenuPromoJson["largeButton"]["Text"].GetString(); + m_sMainMenuPromoData.largeButtonUrl = mainMenuPromoJson["largeButton"]["Url"].GetString(); + m_sMainMenuPromoData.largeButtonImageIndex = mainMenuPromoJson["largeButton"]["ImageIndex"].GetInt(); + + m_sMainMenuPromoData.smallButton1Title = mainMenuPromoJson["smallButton1"]["Title"].GetString(); + m_sMainMenuPromoData.smallButton1Url = mainMenuPromoJson["smallButton1"]["Url"].GetString(); + m_sMainMenuPromoData.smallButton1ImageIndex = mainMenuPromoJson["smallButton1"]["ImageIndex"].GetInt(); + + m_sMainMenuPromoData.smallButton2Title = mainMenuPromoJson["smallButton2"]["Title"].GetString(); + m_sMainMenuPromoData.smallButton2Url = mainMenuPromoJson["smallButton2"]["Url"].GetString(); + m_sMainMenuPromoData.smallButton2ImageIndex = mainMenuPromoJson["smallButton2"]["ImageIndex"].GetInt(); + + m_bHasMainMenuPromoData = true; + } + else + { + spdlog::error("Failed requesting main menu promos: error {}", curl_easy_strerror(result)); + m_bSuccessfullyConnected = false; + } + + REQUEST_END_CLEANUP: + // nothing lol + curl_easy_cleanup(curl); + }); requestThread.detach(); } @@ -456,122 +456,122 @@ void MasterServerManager::AuthenticateWithOwnServer(const char* uid, const char* std::string tokenStr(playerToken); std::thread requestThread( - [this, uidStr, tokenStr]() - { - CURL* curl = curl_easy_init(); - SetCommonHttpClientOptions(curl); - - std::string readBuffer; - curl_easy_setopt( - curl, - CURLOPT_URL, - fmt::format("{}/client/auth_with_self?id={}&playerToken={}", Cvar_ns_masterserver_hostname->GetString(), uidStr, tokenStr) - .c_str()); - curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - - CURLcode result = curl_easy_perform(curl); - - if (result == CURLcode::CURLE_OK) - { - m_bSuccessfullyConnected = true; - - rapidjson_document authInfoJson; - authInfoJson.Parse(readBuffer.c_str()); - - if (authInfoJson.HasParseError()) - { - spdlog::error( - "Failed reading masterserver authentication response: encountered parse error \"{}\"", - rapidjson::GetParseError_En(authInfoJson.GetParseError())); - goto REQUEST_END_CLEANUP; - } - - if (!authInfoJson.IsObject()) - { - spdlog::error("Failed reading masterserver authentication response: root object is not an object"); - goto REQUEST_END_CLEANUP; - } - - if (authInfoJson.HasMember("error")) - { - spdlog::error("Failed reading masterserver response: got fastify error response"); - spdlog::error(readBuffer); - - if (authInfoJson["error"].HasMember("msg")) - m_sAuthFailureReason = authInfoJson["error"]["msg"].GetString(); - else if (authInfoJson["error"].HasMember("enum")) - m_sAuthFailureReason = authInfoJson["error"]["enum"].GetString(); - else - m_sAuthFailureReason = "No error message provided"; - - goto REQUEST_END_CLEANUP; - } - - if (!authInfoJson["success"].IsTrue()) - { - spdlog::error("Authentication with masterserver failed: \"success\" is not true"); - goto REQUEST_END_CLEANUP; - } - - if (!authInfoJson.HasMember("success") || !authInfoJson.HasMember("id") || !authInfoJson["id"].IsString() || - !authInfoJson.HasMember("authToken") || !authInfoJson["authToken"].IsString() || - !authInfoJson.HasMember("persistentData") || !authInfoJson["persistentData"].IsArray()) - { - spdlog::error("Failed reading masterserver authentication response: malformed json object"); - goto REQUEST_END_CLEANUP; - } - - RemoteAuthData newAuthData {}; - strncpy_s(newAuthData.uid, sizeof(newAuthData.uid), authInfoJson["id"].GetString(), sizeof(newAuthData.uid) - 1); - - newAuthData.pdataSize = authInfoJson["persistentData"].GetArray().Size(); - newAuthData.pdata = new char[newAuthData.pdataSize]; - // memcpy(newAuthData.pdata, authInfoJson["persistentData"].GetString(), newAuthData.pdataSize); - - int i = 0; - // note: persistentData is a uint8array because i had problems getting strings to behave, it sucks but it's just how it be - // unfortunately potentially refactor later - for (auto& byte : authInfoJson["persistentData"].GetArray()) - { - if (!byte.IsUint() || byte.GetUint() > 255) - { - spdlog::error("Failed reading masterserver authentication response: malformed json object"); - goto REQUEST_END_CLEANUP; - } - - newAuthData.pdata[i++] = static_cast<char>(byte.GetUint()); - } - - std::lock_guard<std::mutex> guard(g_pServerAuthentication->m_AuthDataMutex); - g_pServerAuthentication->m_RemoteAuthenticationData.clear(); - g_pServerAuthentication->m_RemoteAuthenticationData.insert( - std::make_pair(authInfoJson["authToken"].GetString(), newAuthData)); - - m_bSuccessfullyAuthenticatedWithGameServer = true; - } - else - { - spdlog::error("Failed authenticating with own server: error {}", curl_easy_strerror(result)); - m_bSuccessfullyConnected = false; - m_bSuccessfullyAuthenticatedWithGameServer = false; - m_bScriptAuthenticatingWithGameServer = false; - } - - REQUEST_END_CLEANUP: - m_bAuthenticatingWithGameServer = false; - m_bScriptAuthenticatingWithGameServer = false; - - if (m_bNewgameAfterSelfAuth) - { - // pretty sure this is threadsafe? - R2::Cbuf_AddText(R2::Cbuf_GetCurrentPlayer(), "ns_end_reauth_and_leave_to_lobby", R2::cmd_source_t::kCommandSrcCode); - m_bNewgameAfterSelfAuth = false; - } - - curl_easy_cleanup(curl); - }); + [this, uidStr, tokenStr]() + { + CURL* curl = curl_easy_init(); + SetCommonHttpClientOptions(curl); + + std::string readBuffer; + curl_easy_setopt( + curl, + CURLOPT_URL, + fmt::format("{}/client/auth_with_self?id={}&playerToken={}", Cvar_ns_masterserver_hostname->GetString(), uidStr, tokenStr) + .c_str()); + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); + + CURLcode result = curl_easy_perform(curl); + + if (result == CURLcode::CURLE_OK) + { + m_bSuccessfullyConnected = true; + + rapidjson_document authInfoJson; + authInfoJson.Parse(readBuffer.c_str()); + + if (authInfoJson.HasParseError()) + { + spdlog::error( + "Failed reading masterserver authentication response: encountered parse error \"{}\"", + rapidjson::GetParseError_En(authInfoJson.GetParseError())); + goto REQUEST_END_CLEANUP; + } + + if (!authInfoJson.IsObject()) + { + spdlog::error("Failed reading masterserver authentication response: root object is not an object"); + goto REQUEST_END_CLEANUP; + } + + if (authInfoJson.HasMember("error")) + { + spdlog::error("Failed reading masterserver response: got fastify error response"); + spdlog::error(readBuffer); + + if (authInfoJson["error"].HasMember("msg")) + m_sAuthFailureReason = authInfoJson["error"]["msg"].GetString(); + else if (authInfoJson["error"].HasMember("enum")) + m_sAuthFailureReason = authInfoJson["error"]["enum"].GetString(); + else + m_sAuthFailureReason = "No error message provided"; + + goto REQUEST_END_CLEANUP; + } + + if (!authInfoJson["success"].IsTrue()) + { + spdlog::error("Authentication with masterserver failed: \"success\" is not true"); + goto REQUEST_END_CLEANUP; + } + + if (!authInfoJson.HasMember("success") || !authInfoJson.HasMember("id") || !authInfoJson["id"].IsString() || + !authInfoJson.HasMember("authToken") || !authInfoJson["authToken"].IsString() || + !authInfoJson.HasMember("persistentData") || !authInfoJson["persistentData"].IsArray()) + { + spdlog::error("Failed reading masterserver authentication response: malformed json object"); + goto REQUEST_END_CLEANUP; + } + + RemoteAuthData newAuthData {}; + strncpy_s(newAuthData.uid, sizeof(newAuthData.uid), authInfoJson["id"].GetString(), sizeof(newAuthData.uid) - 1); + + newAuthData.pdataSize = authInfoJson["persistentData"].GetArray().Size(); + newAuthData.pdata = new char[newAuthData.pdataSize]; + // memcpy(newAuthData.pdata, authInfoJson["persistentData"].GetString(), newAuthData.pdataSize); + + int i = 0; + // note: persistentData is a uint8array because i had problems getting strings to behave, it sucks but it's just how it be + // unfortunately potentially refactor later + for (auto& byte : authInfoJson["persistentData"].GetArray()) + { + if (!byte.IsUint() || byte.GetUint() > 255) + { + spdlog::error("Failed reading masterserver authentication response: malformed json object"); + goto REQUEST_END_CLEANUP; + } + + newAuthData.pdata[i++] = static_cast<char>(byte.GetUint()); + } + + std::lock_guard<std::mutex> guard(g_pServerAuthentication->m_AuthDataMutex); + g_pServerAuthentication->m_RemoteAuthenticationData.clear(); + g_pServerAuthentication->m_RemoteAuthenticationData.insert( + std::make_pair(authInfoJson["authToken"].GetString(), newAuthData)); + + m_bSuccessfullyAuthenticatedWithGameServer = true; + } + else + { + spdlog::error("Failed authenticating with own server: error {}", curl_easy_strerror(result)); + m_bSuccessfullyConnected = false; + m_bSuccessfullyAuthenticatedWithGameServer = false; + m_bScriptAuthenticatingWithGameServer = false; + } + + REQUEST_END_CLEANUP: + m_bAuthenticatingWithGameServer = false; + m_bScriptAuthenticatingWithGameServer = false; + + if (m_bNewgameAfterSelfAuth) + { + // pretty sure this is threadsafe? + R2::Cbuf_AddText(R2::Cbuf_GetCurrentPlayer(), "ns_end_reauth_and_leave_to_lobby", R2::cmd_source_t::kCommandSrcCode); + m_bNewgameAfterSelfAuth = false; + } + + curl_easy_cleanup(curl); + }); requestThread.detach(); } @@ -593,121 +593,121 @@ void MasterServerManager::AuthenticateWithServer(const char* uid, const char* pl std::string passwordStr(password); std::thread requestThread( - [this, uidStr, tokenStr, serverIdStr, passwordStr, server]() - { - // esnure that any persistence saving is done, so we know masterserver has newest - while (m_bSavingPersistentData) - Sleep(100); - - spdlog::info("Attempting authentication with server of id \"{}\"", serverIdStr); - - CURL* curl = curl_easy_init(); - SetCommonHttpClientOptions(curl); - - std::string readBuffer; - curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - - { - char* escapedPassword = curl_easy_escape(curl, passwordStr.c_str(), passwordStr.length()); - - curl_easy_setopt( - curl, - CURLOPT_URL, - fmt::format( - "{}/client/auth_with_server?id={}&playerToken={}&server={}&password={}", - Cvar_ns_masterserver_hostname->GetString(), - uidStr, - tokenStr, - serverIdStr, - escapedPassword) - .c_str()); - - curl_free(escapedPassword); - } - - CURLcode result = curl_easy_perform(curl); - - if (result == CURLcode::CURLE_OK) - { - m_bSuccessfullyConnected = true; - - rapidjson_document connectionInfoJson; - connectionInfoJson.Parse(readBuffer.c_str()); - - if (connectionInfoJson.HasParseError()) - { - spdlog::error( - "Failed reading masterserver authentication response: encountered parse error \"{}\"", - rapidjson::GetParseError_En(connectionInfoJson.GetParseError())); - goto REQUEST_END_CLEANUP; - } - - if (!connectionInfoJson.IsObject()) - { - spdlog::error("Failed reading masterserver authentication response: root object is not an object"); - goto REQUEST_END_CLEANUP; - } - - if (connectionInfoJson.HasMember("error")) - { - spdlog::error("Failed reading masterserver response: got fastify error response"); - spdlog::error(readBuffer); - - if (connectionInfoJson["error"].HasMember("msg")) - m_sAuthFailureReason = connectionInfoJson["error"]["msg"].GetString(); - else if (connectionInfoJson["error"].HasMember("enum")) - m_sAuthFailureReason = connectionInfoJson["error"]["enum"].GetString(); - else - m_sAuthFailureReason = "No error message provided"; - - goto REQUEST_END_CLEANUP; - } - - if (!connectionInfoJson["success"].IsTrue()) - { - spdlog::error("Authentication with masterserver failed: \"success\" is not true"); - goto REQUEST_END_CLEANUP; - } - - if (!connectionInfoJson.HasMember("success") || !connectionInfoJson.HasMember("ip") || - !connectionInfoJson["ip"].IsString() || !connectionInfoJson.HasMember("port") || - !connectionInfoJson["port"].IsNumber() || !connectionInfoJson.HasMember("authToken") || - !connectionInfoJson["authToken"].IsString()) - { - spdlog::error("Failed reading masterserver authentication response: malformed json object"); - goto REQUEST_END_CLEANUP; - } - - m_pendingConnectionInfo.ip.S_un.S_addr = inet_addr(connectionInfoJson["ip"].GetString()); - m_pendingConnectionInfo.port = (unsigned short)connectionInfoJson["port"].GetUint(); - - strncpy_s( - m_pendingConnectionInfo.authToken, - sizeof(m_pendingConnectionInfo.authToken), - connectionInfoJson["authToken"].GetString(), - sizeof(m_pendingConnectionInfo.authToken) - 1); - - m_bHasPendingConnectionInfo = true; - m_bSuccessfullyAuthenticatedWithGameServer = true; - - m_currentServer = server; - m_sCurrentServerPassword = passwordStr; - } - else - { - spdlog::error("Failed authenticating with server: error {}", curl_easy_strerror(result)); - m_bSuccessfullyConnected = false; - m_bSuccessfullyAuthenticatedWithGameServer = false; - m_bScriptAuthenticatingWithGameServer = false; - } - - REQUEST_END_CLEANUP: - m_bAuthenticatingWithGameServer = false; - m_bScriptAuthenticatingWithGameServer = false; - curl_easy_cleanup(curl); - }); + [this, uidStr, tokenStr, serverIdStr, passwordStr, server]() + { + // esnure that any persistence saving is done, so we know masterserver has newest + while (m_bSavingPersistentData) + Sleep(100); + + spdlog::info("Attempting authentication with server of id \"{}\"", serverIdStr); + + CURL* curl = curl_easy_init(); + SetCommonHttpClientOptions(curl); + + std::string readBuffer; + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); + + { + char* escapedPassword = curl_easy_escape(curl, passwordStr.c_str(), passwordStr.length()); + + curl_easy_setopt( + curl, + CURLOPT_URL, + fmt::format( + "{}/client/auth_with_server?id={}&playerToken={}&server={}&password={}", + Cvar_ns_masterserver_hostname->GetString(), + uidStr, + tokenStr, + serverIdStr, + escapedPassword) + .c_str()); + + curl_free(escapedPassword); + } + + CURLcode result = curl_easy_perform(curl); + + if (result == CURLcode::CURLE_OK) + { + m_bSuccessfullyConnected = true; + + rapidjson_document connectionInfoJson; + connectionInfoJson.Parse(readBuffer.c_str()); + + if (connectionInfoJson.HasParseError()) + { + spdlog::error( + "Failed reading masterserver authentication response: encountered parse error \"{}\"", + rapidjson::GetParseError_En(connectionInfoJson.GetParseError())); + goto REQUEST_END_CLEANUP; + } + + if (!connectionInfoJson.IsObject()) + { + spdlog::error("Failed reading masterserver authentication response: root object is not an object"); + goto REQUEST_END_CLEANUP; + } + + if (connectionInfoJson.HasMember("error")) + { + spdlog::error("Failed reading masterserver response: got fastify error response"); + spdlog::error(readBuffer); + + if (connectionInfoJson["error"].HasMember("msg")) + m_sAuthFailureReason = connectionInfoJson["error"]["msg"].GetString(); + else if (connectionInfoJson["error"].HasMember("enum")) + m_sAuthFailureReason = connectionInfoJson["error"]["enum"].GetString(); + else + m_sAuthFailureReason = "No error message provided"; + + goto REQUEST_END_CLEANUP; + } + + if (!connectionInfoJson["success"].IsTrue()) + { + spdlog::error("Authentication with masterserver failed: \"success\" is not true"); + goto REQUEST_END_CLEANUP; + } + + if (!connectionInfoJson.HasMember("success") || !connectionInfoJson.HasMember("ip") || + !connectionInfoJson["ip"].IsString() || !connectionInfoJson.HasMember("port") || + !connectionInfoJson["port"].IsNumber() || !connectionInfoJson.HasMember("authToken") || + !connectionInfoJson["authToken"].IsString()) + { + spdlog::error("Failed reading masterserver authentication response: malformed json object"); + goto REQUEST_END_CLEANUP; + } + + m_pendingConnectionInfo.ip.S_un.S_addr = inet_addr(connectionInfoJson["ip"].GetString()); + m_pendingConnectionInfo.port = (unsigned short)connectionInfoJson["port"].GetUint(); + + strncpy_s( + m_pendingConnectionInfo.authToken, + sizeof(m_pendingConnectionInfo.authToken), + connectionInfoJson["authToken"].GetString(), + sizeof(m_pendingConnectionInfo.authToken) - 1); + + m_bHasPendingConnectionInfo = true; + m_bSuccessfullyAuthenticatedWithGameServer = true; + + m_currentServer = server; + m_sCurrentServerPassword = passwordStr; + } + else + { + spdlog::error("Failed authenticating with server: error {}", curl_easy_strerror(result)); + m_bSuccessfullyConnected = false; + m_bSuccessfullyAuthenticatedWithGameServer = false; + m_bScriptAuthenticatingWithGameServer = false; + } + + REQUEST_END_CLEANUP: + m_bAuthenticatingWithGameServer = false; + m_bScriptAuthenticatingWithGameServer = false; + curl_easy_cleanup(curl); + }); requestThread.detach(); } @@ -726,46 +726,46 @@ void MasterServerManager::WritePlayerPersistentData(const char* playerId, const std::string strPdata(pdata, pdataSize); std::thread requestThread( - [this, strPlayerId, strPdata, pdataSize] - { - CURL* curl = curl_easy_init(); - SetCommonHttpClientOptions(curl); - - std::string readBuffer; - curl_easy_setopt( - curl, - CURLOPT_URL, - fmt::format( - "{}/accounts/write_persistence?id={}&serverId={}", - Cvar_ns_masterserver_hostname->GetString(), - strPlayerId, - m_sOwnServerId) - .c_str()); - curl_easy_setopt(curl, CURLOPT_POST, 1L); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - - curl_mime* mime = curl_mime_init(curl); - curl_mimepart* part = curl_mime_addpart(mime); - - curl_mime_data(part, strPdata.c_str(), pdataSize); - curl_mime_name(part, "pdata"); - curl_mime_filename(part, "file.pdata"); - curl_mime_type(part, "application/octet-stream"); - - curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime); - - CURLcode result = curl_easy_perform(curl); - - if (result == CURLcode::CURLE_OK) - m_bSuccessfullyConnected = true; - else - m_bSuccessfullyConnected = false; - - curl_easy_cleanup(curl); - - m_bSavingPersistentData = false; - }); + [this, strPlayerId, strPdata, pdataSize] + { + CURL* curl = curl_easy_init(); + SetCommonHttpClientOptions(curl); + + std::string readBuffer; + curl_easy_setopt( + curl, + CURLOPT_URL, + fmt::format( + "{}/accounts/write_persistence?id={}&serverId={}", + Cvar_ns_masterserver_hostname->GetString(), + strPlayerId, + m_sOwnServerId) + .c_str()); + curl_easy_setopt(curl, CURLOPT_POST, 1L); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); + + curl_mime* mime = curl_mime_init(curl); + curl_mimepart* part = curl_mime_addpart(mime); + + curl_mime_data(part, strPdata.c_str(), pdataSize); + curl_mime_name(part, "pdata"); + curl_mime_filename(part, "file.pdata"); + curl_mime_type(part, "application/octet-stream"); + + curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime); + + CURLcode result = curl_easy_perform(curl); + + if (result == CURLcode::CURLE_OK) + m_bSuccessfullyConnected = true; + else + m_bSuccessfullyConnected = false; + + curl_easy_cleanup(curl); + + m_bSavingPersistentData = false; + }); requestThread.detach(); } @@ -830,10 +830,10 @@ void MasterServerManager::ProcessConnectionlessPacketSigreq1(std::string data) SetCommonHttpClientOptions(curl); curl_easy_setopt( - curl, - CURLOPT_URL, - fmt::format("{}/server/connect?serverId={}&token={}", Cvar_ns_masterserver_hostname->GetString(), m_sOwnServerId, token) - .c_str()); + curl, + CURLOPT_URL, + fmt::format("{}/server/connect?serverId={}&token={}", Cvar_ns_masterserver_hostname->GetString(), m_sOwnServerId, token) + .c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &pdata); @@ -858,11 +858,11 @@ void MasterServerManager::ProcessConnectionlessPacketSigreq1(std::string data) if (!obj.HasParseError() && obj.HasMember("error") && obj["error"].IsObject()) spdlog::error( - "failed to make Atlas connect pdata request {}: response status {}, error: {} ({})", - token, - respStatus, - ((obj["error"].HasMember("enum") && obj["error"]["enum"].IsString()) ? obj["error"]["enum"].GetString() : ""), - ((obj["error"].HasMember("msg") && obj["error"]["msg"].IsString()) ? obj["error"]["msg"].GetString() : "")); + "failed to make Atlas connect pdata request {}: response status {}, error: {} ({})", + token, + respStatus, + ((obj["error"].HasMember("enum") && obj["error"]["enum"].IsString()) ? obj["error"]["enum"].GetString() : ""), + ((obj["error"].HasMember("msg") && obj["error"]["msg"].IsString()) ? obj["error"]["msg"].GetString() : "")); else spdlog::error("failed to make Atlas connect pdata request {}: response status {}", token, respStatus); return; @@ -877,10 +877,10 @@ void MasterServerManager::ProcessConnectionlessPacketSigreq1(std::string data) if (pdata.length() > R2::PERSISTENCE_MAX_SIZE) { spdlog::error( - "failed to make Atlas connect pdata request {}: pdata is too large (max={} len={})", - token, - R2::PERSISTENCE_MAX_SIZE, - pdata.length()); + "failed to make Atlas connect pdata request {}: pdata is too large (max={} len={})", + token, + R2::PERSISTENCE_MAX_SIZE, + pdata.length()); return; } } @@ -904,15 +904,15 @@ void MasterServerManager::ProcessConnectionlessPacketSigreq1(std::string data) return; } curl_easy_setopt( - curl, - CURLOPT_URL, - fmt::format( - "{}/server/connect?serverId={}&token={}&reject={}", - Cvar_ns_masterserver_hostname->GetString(), - m_sOwnServerId, - token, - rejectEnc) - .c_str()); + curl, + CURLOPT_URL, + fmt::format( + "{}/server/connect?serverId={}&token={}&reject={}", + Cvar_ns_masterserver_hostname->GetString(), + m_sOwnServerId, + token, + rejectEnc) + .c_str()); curl_free(rejectEnc); // note: we don't actually have any POST data, so we can't use CURLOPT_POST or the behavior is undefined (e.g., hangs in wine) @@ -942,11 +942,11 @@ void MasterServerManager::ProcessConnectionlessPacketSigreq1(std::string data) if (!obj.HasParseError() && obj.HasMember("error") && obj["error"].IsObject()) spdlog::error( - "failed to respond to Atlas connect request {}: response status {}, error: {} ({})", - token, - respStatus, - ((obj["error"].HasMember("enum") && obj["error"]["enum"].IsString()) ? obj["error"]["enum"].GetString() : ""), - ((obj["error"].HasMember("msg") && obj["error"]["msg"].IsString()) ? obj["error"]["msg"].GetString() : "")); + "failed to respond to Atlas connect request {}: response status {}, error: {} ({})", + token, + respStatus, + ((obj["error"].HasMember("enum") && obj["error"]["enum"].IsString()) ? obj["error"]["enum"].GetString() : ""), + ((obj["error"].HasMember("msg") && obj["error"]["msg"].IsString()) ? obj["error"]["msg"].GetString() : "")); else spdlog::error("failed to respond to Atlas connect request {}: response status {}", token, respStatus); return; @@ -1034,25 +1034,25 @@ void MasterServerPresenceReporter::DestroyPresence(const ServerPresence* pServer *g_pMasterServerManager->m_sOwnServerId = 0; std::thread requestThread( - [this] - { - CURL* curl = curl_easy_init(); - SetCommonHttpClientOptions(curl); - - std::string readBuffer; - curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - curl_easy_setopt( - curl, - CURLOPT_URL, - fmt::format( - "{}/server/remove_server?id={}", Cvar_ns_masterserver_hostname->GetString(), g_pMasterServerManager->m_sOwnServerId) - .c_str()); - - CURLcode result = curl_easy_perform(curl); - curl_easy_cleanup(curl); - }); + [this] + { + CURL* curl = curl_easy_init(); + SetCommonHttpClientOptions(curl); + + std::string readBuffer; + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); + curl_easy_setopt( + curl, + CURLOPT_URL, + fmt::format( + "{}/server/remove_server?id={}", Cvar_ns_masterserver_hostname->GetString(), g_pMasterServerManager->m_sOwnServerId) + .c_str()); + + CURLcode result = curl_easy_perform(curl); + curl_easy_cleanup(curl); + }); requestThread.detach(); } @@ -1080,15 +1080,15 @@ void MasterServerPresenceReporter::RunFrame(double flCurrentTime, const ServerPr case MasterServerReportPresenceResult::Success: // Copy over the server id and auth token granted by the MS. strncpy_s( - g_pMasterServerManager->m_sOwnServerId, - sizeof(g_pMasterServerManager->m_sOwnServerId), - resultData.id.value().c_str(), - sizeof(g_pMasterServerManager->m_sOwnServerId) - 1); + g_pMasterServerManager->m_sOwnServerId, + sizeof(g_pMasterServerManager->m_sOwnServerId), + resultData.id.value().c_str(), + sizeof(g_pMasterServerManager->m_sOwnServerId) - 1); strncpy_s( - g_pMasterServerManager->m_sOwnServerAuthToken, - sizeof(g_pMasterServerManager->m_sOwnServerAuthToken), - resultData.serverAuthToken.value().c_str(), - sizeof(g_pMasterServerManager->m_sOwnServerAuthToken) - 1); + g_pMasterServerManager->m_sOwnServerAuthToken, + sizeof(g_pMasterServerManager->m_sOwnServerAuthToken), + resultData.serverAuthToken.value().c_str(), + sizeof(g_pMasterServerManager->m_sOwnServerAuthToken) - 1); break; case MasterServerReportPresenceResult::FailedNoRetry: case MasterServerReportPresenceResult::FailedNoConnect: @@ -1126,19 +1126,19 @@ void MasterServerPresenceReporter::RunFrame(double flCurrentTime, const ServerPr if (resultData.id) { strncpy_s( - g_pMasterServerManager->m_sOwnServerId, - sizeof(g_pMasterServerManager->m_sOwnServerId), - resultData.id.value().c_str(), - sizeof(g_pMasterServerManager->m_sOwnServerId) - 1); + g_pMasterServerManager->m_sOwnServerId, + sizeof(g_pMasterServerManager->m_sOwnServerId), + resultData.id.value().c_str(), + sizeof(g_pMasterServerManager->m_sOwnServerId) - 1); } if (resultData.serverAuthToken) { strncpy_s( - g_pMasterServerManager->m_sOwnServerAuthToken, - sizeof(g_pMasterServerManager->m_sOwnServerAuthToken), - resultData.serverAuthToken.value().c_str(), - sizeof(g_pMasterServerManager->m_sOwnServerAuthToken) - 1); + g_pMasterServerManager->m_sOwnServerAuthToken, + sizeof(g_pMasterServerManager->m_sOwnServerAuthToken), + resultData.serverAuthToken.value().c_str(), + sizeof(g_pMasterServerManager->m_sOwnServerAuthToken) - 1); } } } @@ -1159,141 +1159,141 @@ void MasterServerPresenceReporter::InternalAddServer(const ServerPresence* pServ spdlog::info("Attempting to register the local server to the master server."); addServerFuture = std::async( - std::launch::async, - [threadedPresence, modInfo, hostname] - { - CURL* curl = curl_easy_init(); - SetCommonHttpClientOptions(curl); - - std::string readBuffer; - curl_easy_setopt(curl, CURLOPT_POST, 1L); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - - curl_mime* mime = curl_mime_init(curl); - curl_mimepart* part = curl_mime_addpart(mime); - - // Lambda to quickly cleanup resources and return a value. - auto ReturnCleanup = - [curl, mime](MasterServerReportPresenceResult result, const char* id = "", const char* serverAuthToken = "") - { - curl_easy_cleanup(curl); - curl_mime_free(mime); - - MasterServerPresenceReporter::ReportPresenceResultData data; - data.result = result; - data.id = id; - data.serverAuthToken = serverAuthToken; - - return data; - }; - - curl_mime_data(part, modInfo.c_str(), modInfo.size()); - curl_mime_name(part, "modinfo"); - curl_mime_filename(part, "modinfo.json"); - curl_mime_type(part, "application/json"); - - curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime); - - // format every paramter because computers hate me - { - char* nameEscaped = curl_easy_escape(curl, threadedPresence.m_sServerName.c_str(), 0); - char* descEscaped = curl_easy_escape(curl, threadedPresence.m_sServerDesc.c_str(), 0); - char* mapEscaped = curl_easy_escape(curl, threadedPresence.m_MapName, 0); - char* playlistEscaped = curl_easy_escape(curl, threadedPresence.m_PlaylistName, 0); - char* passwordEscaped = curl_easy_escape(curl, threadedPresence.m_Password, 0); - - curl_easy_setopt( - curl, - CURLOPT_URL, - fmt::format( - "{}/server/" - "add_server?port={}&authPort=udp&name={}&description={}&map={}&playlist={}&maxPlayers={}&password={}", - hostname.c_str(), - threadedPresence.m_iPort, - nameEscaped, - descEscaped, - mapEscaped, - playlistEscaped, - threadedPresence.m_iMaxPlayers, - passwordEscaped) - .c_str()); - - curl_free(nameEscaped); - curl_free(descEscaped); - curl_free(mapEscaped); - curl_free(playlistEscaped); - curl_free(passwordEscaped); - } - - CURLcode result = curl_easy_perform(curl); - - if (result == CURLcode::CURLE_OK) - { - rapidjson_document serverAddedJson; - serverAddedJson.Parse(readBuffer.c_str()); - - // If we could not parse the JSON or it isn't an object, assume the MS is either wrong or we're completely out of date. - // No retry. - if (serverAddedJson.HasParseError()) - { - spdlog::error( - "Failed reading masterserver authentication response: encountered parse error \"{}\"", - rapidjson::GetParseError_En(serverAddedJson.GetParseError())); - return ReturnCleanup(MasterServerReportPresenceResult::FailedNoRetry); - } - - if (!serverAddedJson.IsObject()) - { - spdlog::error("Failed reading masterserver authentication response: root object is not an object"); - return ReturnCleanup(MasterServerReportPresenceResult::FailedNoRetry); - } - - if (serverAddedJson.HasMember("error")) - { - spdlog::error("Failed reading masterserver response: got fastify error response"); - spdlog::error(readBuffer); - - // If this is DUPLICATE_SERVER, we'll retry adding the server every 20 seconds. - // The master server will only update its internal server list and clean up dead servers on certain events. - // And then again, only if a player requests the server list after the cooldown (1 second by default), or a server is - // added/updated/removed. In any case this needs to be fixed in the master server rewrite. - if (serverAddedJson["error"].HasMember("enum") && - strcmp(serverAddedJson["error"]["enum"].GetString(), "DUPLICATE_SERVER") == 0) - { - spdlog::error("Cooling down while the master server cleans the dead server entry, if any."); - return ReturnCleanup(MasterServerReportPresenceResult::FailedDuplicateServer); - } - - // Retry until we reach max retries. - return ReturnCleanup(MasterServerReportPresenceResult::Failed); - } - - if (!serverAddedJson["success"].IsTrue()) - { - spdlog::error("Adding server to masterserver failed: \"success\" is not true"); - return ReturnCleanup(MasterServerReportPresenceResult::FailedNoRetry); - } - - if (!serverAddedJson.HasMember("id") || !serverAddedJson["id"].IsString() || - !serverAddedJson.HasMember("serverAuthToken") || !serverAddedJson["serverAuthToken"].IsString()) - { - spdlog::error("Failed reading masterserver response: malformed json object"); - return ReturnCleanup(MasterServerReportPresenceResult::FailedNoRetry); - } - - spdlog::info("Successfully registered the local server to the master server."); - return ReturnCleanup( - MasterServerReportPresenceResult::Success, - serverAddedJson["id"].GetString(), - serverAddedJson["serverAuthToken"].GetString()); - } - else - { - spdlog::error("Failed adding self to server list: error {}", curl_easy_strerror(result)); - return ReturnCleanup(MasterServerReportPresenceResult::FailedNoConnect); - } - }); + std::launch::async, + [threadedPresence, modInfo, hostname] + { + CURL* curl = curl_easy_init(); + SetCommonHttpClientOptions(curl); + + std::string readBuffer; + curl_easy_setopt(curl, CURLOPT_POST, 1L); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); + + curl_mime* mime = curl_mime_init(curl); + curl_mimepart* part = curl_mime_addpart(mime); + + // Lambda to quickly cleanup resources and return a value. + auto ReturnCleanup = + [curl, mime](MasterServerReportPresenceResult result, const char* id = "", const char* serverAuthToken = "") + { + curl_easy_cleanup(curl); + curl_mime_free(mime); + + MasterServerPresenceReporter::ReportPresenceResultData data; + data.result = result; + data.id = id; + data.serverAuthToken = serverAuthToken; + + return data; + }; + + curl_mime_data(part, modInfo.c_str(), modInfo.size()); + curl_mime_name(part, "modinfo"); + curl_mime_filename(part, "modinfo.json"); + curl_mime_type(part, "application/json"); + + curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime); + + // format every paramter because computers hate me + { + char* nameEscaped = curl_easy_escape(curl, threadedPresence.m_sServerName.c_str(), 0); + char* descEscaped = curl_easy_escape(curl, threadedPresence.m_sServerDesc.c_str(), 0); + char* mapEscaped = curl_easy_escape(curl, threadedPresence.m_MapName, 0); + char* playlistEscaped = curl_easy_escape(curl, threadedPresence.m_PlaylistName, 0); + char* passwordEscaped = curl_easy_escape(curl, threadedPresence.m_Password, 0); + + curl_easy_setopt( + curl, + CURLOPT_URL, + fmt::format( + "{}/server/" + "add_server?port={}&authPort=udp&name={}&description={}&map={}&playlist={}&maxPlayers={}&password={}", + hostname.c_str(), + threadedPresence.m_iPort, + nameEscaped, + descEscaped, + mapEscaped, + playlistEscaped, + threadedPresence.m_iMaxPlayers, + passwordEscaped) + .c_str()); + + curl_free(nameEscaped); + curl_free(descEscaped); + curl_free(mapEscaped); + curl_free(playlistEscaped); + curl_free(passwordEscaped); + } + + CURLcode result = curl_easy_perform(curl); + + if (result == CURLcode::CURLE_OK) + { + rapidjson_document serverAddedJson; + serverAddedJson.Parse(readBuffer.c_str()); + + // If we could not parse the JSON or it isn't an object, assume the MS is either wrong or we're completely out of date. + // No retry. + if (serverAddedJson.HasParseError()) + { + spdlog::error( + "Failed reading masterserver authentication response: encountered parse error \"{}\"", + rapidjson::GetParseError_En(serverAddedJson.GetParseError())); + return ReturnCleanup(MasterServerReportPresenceResult::FailedNoRetry); + } + + if (!serverAddedJson.IsObject()) + { + spdlog::error("Failed reading masterserver authentication response: root object is not an object"); + return ReturnCleanup(MasterServerReportPresenceResult::FailedNoRetry); + } + + if (serverAddedJson.HasMember("error")) + { + spdlog::error("Failed reading masterserver response: got fastify error response"); + spdlog::error(readBuffer); + + // If this is DUPLICATE_SERVER, we'll retry adding the server every 20 seconds. + // The master server will only update its internal server list and clean up dead servers on certain events. + // And then again, only if a player requests the server list after the cooldown (1 second by default), or a server is + // added/updated/removed. In any case this needs to be fixed in the master server rewrite. + if (serverAddedJson["error"].HasMember("enum") && + strcmp(serverAddedJson["error"]["enum"].GetString(), "DUPLICATE_SERVER") == 0) + { + spdlog::error("Cooling down while the master server cleans the dead server entry, if any."); + return ReturnCleanup(MasterServerReportPresenceResult::FailedDuplicateServer); + } + + // Retry until we reach max retries. + return ReturnCleanup(MasterServerReportPresenceResult::Failed); + } + + if (!serverAddedJson["success"].IsTrue()) + { + spdlog::error("Adding server to masterserver failed: \"success\" is not true"); + return ReturnCleanup(MasterServerReportPresenceResult::FailedNoRetry); + } + + if (!serverAddedJson.HasMember("id") || !serverAddedJson["id"].IsString() || + !serverAddedJson.HasMember("serverAuthToken") || !serverAddedJson["serverAuthToken"].IsString()) + { + spdlog::error("Failed reading masterserver response: malformed json object"); + return ReturnCleanup(MasterServerReportPresenceResult::FailedNoRetry); + } + + spdlog::info("Successfully registered the local server to the master server."); + return ReturnCleanup( + MasterServerReportPresenceResult::Success, + serverAddedJson["id"].GetString(), + serverAddedJson["serverAuthToken"].GetString()); + } + else + { + spdlog::error("Failed adding self to server list: error {}", curl_easy_strerror(result)); + return ReturnCleanup(MasterServerReportPresenceResult::FailedNoConnect); + } + }); } void MasterServerPresenceReporter::InternalUpdateServer(const ServerPresence* pServerPresence) @@ -1308,113 +1308,113 @@ void MasterServerPresenceReporter::InternalUpdateServer(const ServerPresence* pS const std::string modinfo = g_pMasterServerManager->m_sOwnModInfoJson; updateServerFuture = std::async( - std::launch::async, - [threadedPresence, serverId, hostname, modinfo] - { - CURL* curl = curl_easy_init(); - SetCommonHttpClientOptions(curl); - - // Lambda to quickly cleanup resources and return a value. - auto ReturnCleanup = [curl](MasterServerReportPresenceResult result, const char* id = "", const char* serverAuthToken = "") - { - curl_easy_cleanup(curl); - - MasterServerPresenceReporter::ReportPresenceResultData data; - data.result = result; - - if (id != nullptr) - { - data.id = id; - } - - if (serverAuthToken != nullptr) - { - data.serverAuthToken = serverAuthToken; - } - - return data; - }; - - std::string readBuffer; - curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); - - // send all registration info so we have all necessary info to reregister our server if masterserver goes down, - // without a restart this isn't threadsafe :terror: - { - char* nameEscaped = curl_easy_escape(curl, threadedPresence.m_sServerName.c_str(), 0); - char* descEscaped = curl_easy_escape(curl, threadedPresence.m_sServerDesc.c_str(), 0); - char* mapEscaped = curl_easy_escape(curl, threadedPresence.m_MapName, 0); - char* playlistEscaped = curl_easy_escape(curl, threadedPresence.m_PlaylistName, 0); - char* passwordEscaped = curl_easy_escape(curl, threadedPresence.m_Password, 0); - - curl_easy_setopt( - curl, - CURLOPT_URL, - fmt::format( - "{}/server/" - "update_values?id={}&port={}&authPort=udp&name={}&description={}&map={}&playlist={}&playerCount={}&" - "maxPlayers={}&password={}", - hostname.c_str(), - serverId.c_str(), - threadedPresence.m_iPort, - nameEscaped, - descEscaped, - mapEscaped, - playlistEscaped, - threadedPresence.m_iPlayerCount, - threadedPresence.m_iMaxPlayers, - passwordEscaped) - .c_str()); - - curl_free(nameEscaped); - curl_free(descEscaped); - curl_free(mapEscaped); - curl_free(playlistEscaped); - curl_free(passwordEscaped); - } - - curl_mime* mime = curl_mime_init(curl); - curl_mimepart* part = curl_mime_addpart(mime); - - curl_mime_data(part, modinfo.c_str(), modinfo.size()); - curl_mime_name(part, "modinfo"); - curl_mime_filename(part, "modinfo.json"); - curl_mime_type(part, "application/json"); - - curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime); - - CURLcode result = curl_easy_perform(curl); - - if (result == CURLcode::CURLE_OK) - { - rapidjson_document serverAddedJson; - serverAddedJson.Parse(readBuffer.c_str()); - - const char* updatedId = nullptr; - const char* updatedAuthToken = nullptr; - - if (!serverAddedJson.HasParseError() && serverAddedJson.IsObject()) - { - if (serverAddedJson.HasMember("id") && serverAddedJson["id"].IsString()) - { - updatedId = serverAddedJson["id"].GetString(); - } - - if (serverAddedJson.HasMember("serverAuthToken") && serverAddedJson["serverAuthToken"].IsString()) - { - updatedAuthToken = serverAddedJson["serverAuthToken"].GetString(); - } - } - - return ReturnCleanup(MasterServerReportPresenceResult::Success, updatedId, updatedAuthToken); - } - else - { - spdlog::warn("Heartbeat failed with error {}", curl_easy_strerror(result)); - return ReturnCleanup(MasterServerReportPresenceResult::Failed); - } - }); + std::launch::async, + [threadedPresence, serverId, hostname, modinfo] + { + CURL* curl = curl_easy_init(); + SetCommonHttpClientOptions(curl); + + // Lambda to quickly cleanup resources and return a value. + auto ReturnCleanup = [curl](MasterServerReportPresenceResult result, const char* id = "", const char* serverAuthToken = "") + { + curl_easy_cleanup(curl); + + MasterServerPresenceReporter::ReportPresenceResultData data; + data.result = result; + + if (id != nullptr) + { + data.id = id; + } + + if (serverAuthToken != nullptr) + { + data.serverAuthToken = serverAuthToken; + } + + return data; + }; + + std::string readBuffer; + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); + + // send all registration info so we have all necessary info to reregister our server if masterserver goes down, + // without a restart this isn't threadsafe :terror: + { + char* nameEscaped = curl_easy_escape(curl, threadedPresence.m_sServerName.c_str(), 0); + char* descEscaped = curl_easy_escape(curl, threadedPresence.m_sServerDesc.c_str(), 0); + char* mapEscaped = curl_easy_escape(curl, threadedPresence.m_MapName, 0); + char* playlistEscaped = curl_easy_escape(curl, threadedPresence.m_PlaylistName, 0); + char* passwordEscaped = curl_easy_escape(curl, threadedPresence.m_Password, 0); + + curl_easy_setopt( + curl, + CURLOPT_URL, + fmt::format( + "{}/server/" + "update_values?id={}&port={}&authPort=udp&name={}&description={}&map={}&playlist={}&playerCount={}&" + "maxPlayers={}&password={}", + hostname.c_str(), + serverId.c_str(), + threadedPresence.m_iPort, + nameEscaped, + descEscaped, + mapEscaped, + playlistEscaped, + threadedPresence.m_iPlayerCount, + threadedPresence.m_iMaxPlayers, + passwordEscaped) + .c_str()); + + curl_free(nameEscaped); + curl_free(descEscaped); + curl_free(mapEscaped); + curl_free(playlistEscaped); + curl_free(passwordEscaped); + } + + curl_mime* mime = curl_mime_init(curl); + curl_mimepart* part = curl_mime_addpart(mime); + + curl_mime_data(part, modinfo.c_str(), modinfo.size()); + curl_mime_name(part, "modinfo"); + curl_mime_filename(part, "modinfo.json"); + curl_mime_type(part, "application/json"); + + curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime); + + CURLcode result = curl_easy_perform(curl); + + if (result == CURLcode::CURLE_OK) + { + rapidjson_document serverAddedJson; + serverAddedJson.Parse(readBuffer.c_str()); + + const char* updatedId = nullptr; + const char* updatedAuthToken = nullptr; + + if (!serverAddedJson.HasParseError() && serverAddedJson.IsObject()) + { + if (serverAddedJson.HasMember("id") && serverAddedJson["id"].IsString()) + { + updatedId = serverAddedJson["id"].GetString(); + } + + if (serverAddedJson.HasMember("serverAuthToken") && serverAddedJson["serverAuthToken"].IsString()) + { + updatedAuthToken = serverAddedJson["serverAuthToken"].GetString(); + } + } + + return ReturnCleanup(MasterServerReportPresenceResult::Success, updatedId, updatedAuthToken); + } + else + { + spdlog::warn("Heartbeat failed with error {}", curl_easy_strerror(result)); + return ReturnCleanup(MasterServerReportPresenceResult::Failed); + } + }); } diff --git a/NorthstarDLL/masterserver/masterserver.h b/NorthstarDLL/masterserver/masterserver.h index e87b31a2..3204fdf5 100644 --- a/NorthstarDLL/masterserver/masterserver.h +++ b/NorthstarDLL/masterserver/masterserver.h @@ -39,15 +39,15 @@ class RemoteServerInfo public: RemoteServerInfo( - const char* newId, - const char* newName, - const char* newDescription, - const char* newMap, - const char* newPlaylist, - const char* newRegion, - int newPlayerCount, - int newMaxPlayers, - bool newRequiresPassword); + const char* newId, + const char* newName, + const char* newDescription, + const char* newMap, + const char* newPlaylist, + const char* newRegion, + int newPlayerCount, + int newMaxPlayers, + bool newRequiresPassword); }; struct RemoteServerConnectionInfo diff --git a/NorthstarDLL/mods/compiled/modpdef.cpp b/NorthstarDLL/mods/compiled/modpdef.cpp index 4b1b12b7..ace7ab8f 100644 --- a/NorthstarDLL/mods/compiled/modpdef.cpp +++ b/NorthstarDLL/mods/compiled/modpdef.cpp @@ -61,7 +61,7 @@ void ModManager::BuildPdef() inEnum = false; else enumAdds[currentEnum].push_back(currentLine); // only need to push_back current line, if there's syntax errors then game - // pdef parser will handle them + // pdef parser will handle them } else if (!currentLine.compare(start, 9, "$ENUM_ADD")) { diff --git a/NorthstarDLL/mods/compiled/modscriptsrson.cpp b/NorthstarDLL/mods/compiled/modscriptsrson.cpp index cbe26651..449ad777 100644 --- a/NorthstarDLL/mods/compiled/modscriptsrson.cpp +++ b/NorthstarDLL/mods/compiled/modscriptsrson.cpp @@ -32,7 +32,7 @@ void ModManager::BuildScriptsRson() When: "CONTEXT" Scripts: [ - _coolscript.gnut + _coolscript.gnut ]*/ scriptsRson += "When: \""; diff --git a/NorthstarDLL/mods/modmanager.cpp b/NorthstarDLL/mods/modmanager.cpp index 1ca51ad7..30dc5d53 100644 --- a/NorthstarDLL/mods/modmanager.cpp +++ b/NorthstarDLL/mods/modmanager.cpp @@ -35,10 +35,10 @@ Mod::Mod(fs::path modDir, char* jsonBuf) if (modJson.HasParseError()) { spdlog::error( - "Failed reading mod file {}: encountered parse error \"{}\" at offset {}", - (modDir / "mod.json").string(), - GetParseError_En(modJson.GetParseError()), - modJson.GetErrorOffset()); + "Failed reading mod file {}: encountered parse error \"{}\" at offset {}", + (modDir / "mod.json").string(), + GetParseError_En(modJson.GetParseError()), + modJson.GetErrorOffset()); return; } @@ -312,7 +312,7 @@ void Mod::ParseScripts(rapidjson_document& json) callback.DestroyCallback = scriptObj["ServerCallback"]["Destroy"].GetString(); else spdlog::warn( - "'Destroy' ServerCallback for script '{}' is not a string, skipping...", scriptObj["Path"].GetString()); + "'Destroy' ServerCallback for script '{}' is not a string, skipping...", scriptObj["Path"].GetString()); } script.Callbacks.push_back(callback); @@ -352,7 +352,7 @@ void Mod::ParseScripts(rapidjson_document& json) callback.DestroyCallback = scriptObj["ClientCallback"]["Destroy"].GetString(); else spdlog::warn( - "'Destroy' ClientCallback for script '{}' is not a string, skipping...", scriptObj["Path"].GetString()); + "'Destroy' ClientCallback for script '{}' is not a string, skipping...", scriptObj["Path"].GetString()); } script.Callbacks.push_back(callback); @@ -459,17 +459,17 @@ void Mod::ParseDependencies(rapidjson_document& json) } if (DependencyConstants.find(v->name.GetString()) != DependencyConstants.end() && - v->value.GetString() != DependencyConstants[v->name.GetString()]) + v->value.GetString() != DependencyConstants[v->name.GetString()]) { // this is fatal because otherwise the mod will probably try to use functions that dont exist, // which will cause errors further down the line that are harder to debug spdlog::error( - "'{}' attempted to register a dependency constant '{}' for '{}' that already exists for '{}'. " - "Change the constant name.", - Name, - v->name.GetString(), - v->value.GetString(), - DependencyConstants[v->name.GetString()]); + "'{}' attempted to register a dependency constant '{}' for '{}' that already exists for '{}'. " + "Change the constant name.", + Name, + v->name.GetString(), + v->value.GetString(), + DependencyConstants[v->name.GetString()]); return; } @@ -500,7 +500,7 @@ ModManager::ModManager() // note: use backslashes for these, since we use lexically_normal for file paths which uses them m_hScriptsRsonHash = STR_HASH("scripts\\vscripts\\scripts.rson"); m_hPdefHash = STR_HASH( - "cfg\\server\\persistent_player_data_version_231.pdef" // this can have multiple versions, but we use 231 so that's what we hash + "cfg\\server\\persistent_player_data_version_231.pdef" // this can have multiple versions, but we use 231 so that's what we hash ); m_hKBActHash = STR_HASH("scripts\\kb_act.lst"); @@ -552,9 +552,9 @@ auto ModConCommandCallback(const CCommand& command) for (auto& mod : g_pModManager->m_LoadedMods) { auto res = std::find_if( - mod.ConCommands.begin(), - mod.ConCommands.end(), - [&commandString](const ModConCommand* other) { return other->Name == commandString; }); + mod.ConCommands.begin(), + mod.ConCommands.end(), + [&commandString](const ModConCommand* other) { return other->Name == commandString; }); if (res != mod.ConCommands.end()) { found = *res; @@ -604,7 +604,7 @@ void ModManager::LoadMods() enabledModsStream.close(); m_EnabledModsCfg.Parse<rapidjson::ParseFlag::kParseCommentsFlag | rapidjson::ParseFlag::kParseTrailingCommasFlag>( - enabledModsStringStream.str().c_str()); + enabledModsStringStream.str().c_str()); m_bHasEnabledModsCfg = m_EnabledModsCfg.IsObject(); } @@ -656,7 +656,7 @@ void ModManager::LoadMods() if (jsonStream.fail()) { spdlog::warn( - "Mod file at '{}' does not exist or could not be read, is it installed correctly?", (modDir / "mod.json").string()); + "Mod file at '{}' does not exist or could not be read, is it installed correctly?", (modDir / "mod.json").string()); continue; } @@ -672,12 +672,12 @@ void ModManager::LoadMods() if (m_DependencyConstants.find(pair.first) != m_DependencyConstants.end() && m_DependencyConstants[pair.first] != pair.second) { spdlog::error( - "'{}' attempted to register a dependency constant '{}' for '{}' that already exists for '{}'. " - "Change the constant name.", - mod.Name, - pair.first, - pair.second, - m_DependencyConstants[pair.first]); + "'{}' attempted to register a dependency constant '{}' for '{}' that already exists for '{}'. " + "Change the constant name.", + mod.Name, + pair.first, + pair.second, + m_DependencyConstants[pair.first]); mod.m_bWasReadSuccessfully = false; break; } @@ -753,7 +753,7 @@ void ModManager::LoadMods() vpkJsonStream.close(); dVpkJson.Parse<rapidjson::ParseFlag::kParseCommentsFlag | rapidjson::ParseFlag::kParseTrailingCommasFlag>( - vpkJsonStringStream.str().c_str()); + vpkJsonStringStream.str().c_str()); bUseVPKJson = !dVpkJson.HasParseError() && dVpkJson.IsObject(); } @@ -763,8 +763,8 @@ void ModManager::LoadMods() // a bunch of checks to make sure we're only adding dir vpks and their paths are good // note: the game will literally only load vpks with the english prefix if (fs::is_regular_file(file) && file.path().extension() == ".vpk" && - file.path().string().find("english") != std::string::npos && - file.path().string().find(".bsp.pak000_dir") != std::string::npos) + file.path().string().find("english") != std::string::npos && + file.path().string().find(".bsp.pak000_dir") != std::string::npos) { std::string formattedPath = file.path().filename().string(); @@ -773,7 +773,7 @@ void ModManager::LoadMods() ModVPKEntry& modVpk = mod.Vpks.emplace_back(); modVpk.m_bAutoLoad = !bUseVPKJson || (dVpkJson.HasMember("Preload") && dVpkJson["Preload"].IsObject() && - dVpkJson["Preload"].HasMember(vpkName) && dVpkJson["Preload"][vpkName].IsTrue()); + dVpkJson["Preload"].HasMember(vpkName) && dVpkJson["Preload"][vpkName].IsTrue()); modVpk.m_sVpkPath = (file.path().parent_path() / vpkName).string(); if (m_bHasLoadedMods && modVpk.m_bAutoLoad) @@ -799,7 +799,7 @@ void ModManager::LoadMods() rpakJsonStream.close(); dRpakJson.Parse<rapidjson::ParseFlag::kParseCommentsFlag | rapidjson::ParseFlag::kParseTrailingCommasFlag>( - rpakJsonStringStream.str().c_str()); + rpakJsonStringStream.str().c_str()); bUseRpakJson = !dRpakJson.HasParseError() && dRpakJson.IsObject(); } @@ -808,8 +808,8 @@ void ModManager::LoadMods() if (bUseRpakJson && dRpakJson.HasMember("Aliases") && dRpakJson["Aliases"].IsObject()) { for (rapidjson::Value::ConstMemberIterator iterator = dRpakJson["Aliases"].MemberBegin(); - iterator != dRpakJson["Aliases"].MemberEnd(); - iterator++) + iterator != dRpakJson["Aliases"].MemberEnd(); + iterator++) { if (!iterator->name.IsString() || !iterator->value.IsString()) continue; @@ -827,12 +827,12 @@ void ModManager::LoadMods() ModRpakEntry& modPak = mod.Rpaks.emplace_back(); modPak.m_bAutoLoad = - !bUseRpakJson || (dRpakJson.HasMember("Preload") && dRpakJson["Preload"].IsObject() && - dRpakJson["Preload"].HasMember(pakName) && dRpakJson["Preload"][pakName].IsTrue()); + !bUseRpakJson || (dRpakJson.HasMember("Preload") && dRpakJson["Preload"].IsObject() && + dRpakJson["Preload"].HasMember(pakName) && dRpakJson["Preload"][pakName].IsTrue()); // postload things if (!bUseRpakJson || - (dRpakJson.HasMember("Postload") && dRpakJson["Postload"].IsObject() && dRpakJson["Postload"].HasMember(pakName))) + (dRpakJson.HasMember("Postload") && dRpakJson["Postload"].IsObject() && dRpakJson["Postload"].HasMember(pakName))) modPak.m_sLoadAfterPak = dRpakJson["Postload"][pakName].GetString(); modPak.m_sPakName = pakName; @@ -892,7 +892,7 @@ void ModManager::LoadMods() if (fs::is_regular_file(file)) { std::string kvStr = - g_pModManager->NormaliseModFilePath(file.path().lexically_relative(mod.m_ModDirectory / "keyvalues")); + g_pModManager->NormaliseModFilePath(file.path().lexically_relative(mod.m_ModDirectory / "keyvalues")); mod.KeyValues.emplace(STR_HASH(kvStr), kvStr); } } @@ -951,7 +951,7 @@ void ModManager::LoadMods() for (fs::directory_entry file : fs::recursive_directory_iterator(m_LoadedMods[i].m_ModDirectory / MOD_OVERRIDE_DIR)) { std::string path = - g_pModManager->NormaliseModFilePath(file.path().lexically_relative(m_LoadedMods[i].m_ModDirectory / MOD_OVERRIDE_DIR)); + g_pModManager->NormaliseModFilePath(file.path().lexically_relative(m_LoadedMods[i].m_ModDirectory / MOD_OVERRIDE_DIR)); if (file.is_regular_file() && m_ModFiles.find(path) == m_ModFiles.end()) { ModOverrideFile modFile; diff --git a/NorthstarDLL/mods/modmanager.h b/NorthstarDLL/mods/modmanager.h index 15367e4d..e684034b 100644 --- a/NorthstarDLL/mods/modmanager.h +++ b/NorthstarDLL/mods/modmanager.h @@ -118,7 +118,7 @@ class Mod std::vector<ModRpakEntry> Rpaks; std::unordered_map<std::string, std::string> - RpakAliases; // paks we alias to other rpaks, e.g. to load sp_crashsite paks on the map mp_crashsite + RpakAliases; // paks we alias to other rpaks, e.g. to load sp_crashsite paks on the map mp_crashsite std::vector<size_t> StarpakPaths; // starpaks that this mod contains // there seems to be no nice way to get the rpak that is causing the load of a starpak? // hashed with STR_HASH diff --git a/NorthstarDLL/mods/modsavefiles.cpp b/NorthstarDLL/mods/modsavefiles.cpp index f8e5848c..e8bc3de0 100644 --- a/NorthstarDLL/mods/modsavefiles.cpp +++ b/NorthstarDLL/mods/modsavefiles.cpp @@ -72,47 +72,47 @@ template <ScriptContext context> void SaveFileManager::SaveFileAsync(fs::path fi { auto mutex = std::ref(fileMutex); std::thread writeThread( - [mutex, file, contents]() - { - try - { - mutex.get().lock(); - - fs::path dir = file.parent_path(); - // this actually allows mods to go over the limit, but not by much - // the limit is to prevent mods from taking gigabytes of space, - // we don't need to be particularly strict. - if (GetSizeOfFolderContentsMinusFile(dir, file.filename().string()) + contents.length() > MAX_FOLDER_SIZE) - { - // tbh, you're either trying to fill the hard drive or use so much data, you SHOULD be congratulated. - spdlog::error(fmt::format("Mod spamming save requests? Folder limit bypassed despite previous checks. Not saving.")); - mutex.get().unlock(); - return; - } - - std::ofstream fileStr(file); - if (fileStr.fail()) - { - mutex.get().unlock(); - return; - } - - fileStr.write(contents.c_str(), contents.length()); - fileStr.close(); - - mutex.get().unlock(); - // side-note: this causes a leak? - // when a file is added to the map, it's never removed. - // no idea how to fix this - because we have no way to check if there are other threads waiting to use this file(?) - // tried to use m.try_lock(), but it's unreliable, it seems. - } - catch (std::exception ex) - { - spdlog::error("SAVE FAILED!"); - mutex.get().unlock(); - spdlog::error(ex.what()); - } - }); + [mutex, file, contents]() + { + try + { + mutex.get().lock(); + + fs::path dir = file.parent_path(); + // this actually allows mods to go over the limit, but not by much + // the limit is to prevent mods from taking gigabytes of space, + // we don't need to be particularly strict. + if (GetSizeOfFolderContentsMinusFile(dir, file.filename().string()) + contents.length() > MAX_FOLDER_SIZE) + { + // tbh, you're either trying to fill the hard drive or use so much data, you SHOULD be congratulated. + spdlog::error(fmt::format("Mod spamming save requests? Folder limit bypassed despite previous checks. Not saving.")); + mutex.get().unlock(); + return; + } + + std::ofstream fileStr(file); + if (fileStr.fail()) + { + mutex.get().unlock(); + return; + } + + fileStr.write(contents.c_str(), contents.length()); + fileStr.close(); + + mutex.get().unlock(); + // side-note: this causes a leak? + // when a file is added to the map, it's never removed. + // no idea how to fix this - because we have no way to check if there are other threads waiting to use this file(?) + // tried to use m.try_lock(), but it's unreliable, it seems. + } + catch (std::exception ex) + { + spdlog::error("SAVE FAILED!"); + mutex.get().unlock(); + spdlog::error(ex.what()); + } + }); writeThread.detach(); } @@ -123,42 +123,42 @@ template <ScriptContext context> int SaveFileManager::LoadFileAsync(fs::path fil int handle = ++m_iLastRequestHandle; auto mutex = std::ref(fileMutex); std::thread readThread( - [mutex, file, handle]() - { - try - { - mutex.get().lock(); - - std::ifstream fileStr(file); - if (fileStr.fail()) - { - spdlog::error("A file was supposed to be loaded but we can't access it?!"); - - g_pSquirrel<context>->AsyncCall("NSHandleLoadResult", handle, false, ""); - mutex.get().unlock(); - return; - } - - std::stringstream stringStream; - stringStream << fileStr.rdbuf(); - - g_pSquirrel<context>->AsyncCall("NSHandleLoadResult", handle, true, stringStream.str()); - - fileStr.close(); - mutex.get().unlock(); - // side-note: this causes a leak? - // when a file is added to the map, it's never removed. - // no idea how to fix this - because we have no way to check if there are other threads waiting to use this file(?) - // tried to use m.try_lock(), but it's unreliable, it seems. - } - catch (std::exception ex) - { - spdlog::error("LOAD FAILED!"); - g_pSquirrel<context>->AsyncCall("NSHandleLoadResult", handle, false, ""); - mutex.get().unlock(); - spdlog::error(ex.what()); - } - }); + [mutex, file, handle]() + { + try + { + mutex.get().lock(); + + std::ifstream fileStr(file); + if (fileStr.fail()) + { + spdlog::error("A file was supposed to be loaded but we can't access it?!"); + + g_pSquirrel<context>->AsyncCall("NSHandleLoadResult", handle, false, ""); + mutex.get().unlock(); + return; + } + + std::stringstream stringStream; + stringStream << fileStr.rdbuf(); + + g_pSquirrel<context>->AsyncCall("NSHandleLoadResult", handle, true, stringStream.str()); + + fileStr.close(); + mutex.get().unlock(); + // side-note: this causes a leak? + // when a file is added to the map, it's never removed. + // no idea how to fix this - because we have no way to check if there are other threads waiting to use this file(?) + // tried to use m.try_lock(), but it's unreliable, it seems. + } + catch (std::exception ex) + { + spdlog::error("LOAD FAILED!"); + g_pSquirrel<context>->AsyncCall("NSHandleLoadResult", handle, false, ""); + mutex.get().unlock(); + spdlog::error(ex.what()); + } + }); readThread.detach(); return handle; @@ -170,27 +170,27 @@ template <ScriptContext context> void SaveFileManager::DeleteFileAsync(fs::path // P.S. I don't like how we have to async delete calls but we do. auto m = std::ref(fileMutex); std::thread deleteThread( - [m, file]() - { - try - { - m.get().lock(); - - fs::remove(file); - - m.get().unlock(); - // side-note: this causes a leak? - // when a file is added to the map, it's never removed. - // no idea how to fix this - because we have no way to check if there are other threads waiting to use this file(?) - // tried to use m.try_lock(), but it's unreliable, it seems. - } - catch (std::exception ex) - { - spdlog::error("DELETE FAILED!"); - m.get().unlock(); - spdlog::error(ex.what()); - } - }); + [m, file]() + { + try + { + m.get().lock(); + + fs::remove(file); + + m.get().unlock(); + // side-note: this causes a leak? + // when a file is added to the map, it's never removed. + // no idea how to fix this - because we have no way to check if there are other threads waiting to use this file(?) + // tried to use m.try_lock(), but it's unreliable, it seems. + } + catch (std::exception ex) + { + spdlog::error("DELETE FAILED!"); + m.get().unlock(); + spdlog::error(ex.what()); + } + }); deleteThread.detach(); } @@ -215,13 +215,13 @@ bool IsPathSafe(const std::string param, fs::path dir) auto itr = std::search(normChild.begin(), normChild.end(), normRoot.begin(), normRoot.end()); // we return if the file is safe (inside the directory) and uses only ASCII chars in the path. return itr == normChild.begin() && std::none_of( - param.begin(), - param.end(), - [](char c) - { - unsigned char unsignedC = static_cast<unsigned char>(c); - return unsignedC > 127 || unsignedC < 0; - }); + param.begin(), + param.end(), + [](char c) + { + unsigned char unsignedC = static_cast<unsigned char>(c); + return unsignedC > 127 || unsignedC < 0; + }); } catch (fs::filesystem_error err) { @@ -244,13 +244,13 @@ ADD_SQFUNC("void", NSSaveFile, "string file, string data", "", ScriptContext::SE if (!IsPathSafe(fileName, dir)) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " - "save folder.", - fileName, - mod->Name) - .c_str()); + sqvm, + fmt::format( + "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " + "save folder.", + fileName, + mod->Name) + .c_str()); return SQRESULT_ERROR; } @@ -258,7 +258,7 @@ ADD_SQFUNC("void", NSSaveFile, "string file, string data", "", ScriptContext::SE if (ContainsInvalidChars(content)) { g_pSquirrel<context>->raiseerror( - sqvm, fmt::format("File contents may not contain NUL/\\0 characters! Make sure your strings are valid!", mod->Name).c_str()); + sqvm, fmt::format("File contents may not contain NUL/\\0 characters! Make sure your strings are valid!", mod->Name).c_str()); return SQRESULT_ERROR; } @@ -269,12 +269,12 @@ ADD_SQFUNC("void", NSSaveFile, "string file, string data", "", ScriptContext::SE if (GetSizeOfFolderContentsMinusFile(dir, fileName) + content.length() > MAX_FOLDER_SIZE) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "The mod {} has reached the maximum folder size.\n\nAsk the mod developer to optimize their data usage," - "or increase the maximum folder size using the -maxfoldersize launch parameter.", - mod->Name) - .c_str()); + sqvm, + fmt::format( + "The mod {} has reached the maximum folder size.\n\nAsk the mod developer to optimize their data usage," + "or increase the maximum folder size using the -maxfoldersize launch parameter.", + mod->Name) + .c_str()); return SQRESULT_ERROR; } @@ -298,13 +298,13 @@ ADD_SQFUNC("void", NSSaveJSONFile, "string file, table data", "", ScriptContext: if (!IsPathSafe(fileName, dir)) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " - "save folder.", - fileName, - mod->Name) - .c_str()); + sqvm, + fmt::format( + "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " + "save folder.", + fileName, + mod->Name) + .c_str()); return SQRESULT_ERROR; } @@ -314,7 +314,7 @@ ADD_SQFUNC("void", NSSaveJSONFile, "string file, table data", "", ScriptContext: if (ContainsInvalidChars(content)) { g_pSquirrel<context>->raiseerror( - sqvm, fmt::format("File contents may not contain NUL/\\0 characters! Make sure your strings are valid!", mod->Name).c_str()); + sqvm, fmt::format("File contents may not contain NUL/\\0 characters! Make sure your strings are valid!", mod->Name).c_str()); return SQRESULT_ERROR; } @@ -325,12 +325,12 @@ ADD_SQFUNC("void", NSSaveJSONFile, "string file, table data", "", ScriptContext: if (GetSizeOfFolderContentsMinusFile(dir, fileName) + content.length() > MAX_FOLDER_SIZE) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "The mod {} has reached the maximum folder size.\n\nAsk the mod developer to optimize their data usage," - "or increase the maximum folder size using the -maxfoldersize launch parameter.", - mod->Name) - .c_str()); + sqvm, + fmt::format( + "The mod {} has reached the maximum folder size.\n\nAsk the mod developer to optimize their data usage," + "or increase the maximum folder size using the -maxfoldersize launch parameter.", + mod->Name) + .c_str()); return SQRESULT_ERROR; } @@ -354,13 +354,13 @@ ADD_SQFUNC("int", NS_InternalLoadFile, "string file", "", ScriptContext::SERVER if (!IsPathSafe(fileName, dir)) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " - "save folder.", - fileName, - mod->Name) - .c_str()); + sqvm, + fmt::format( + "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " + "save folder.", + fileName, + mod->Name) + .c_str()); return SQRESULT_ERROR; } @@ -379,13 +379,13 @@ ADD_SQFUNC("bool", NSDoesFileExist, "string file", "", ScriptContext::SERVER | S if (!IsPathSafe(fileName, dir)) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " - "save folder.", - fileName, - mod->Name) - .c_str()); + sqvm, + fmt::format( + "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " + "save folder.", + fileName, + mod->Name) + .c_str()); return SQRESULT_ERROR; } @@ -403,13 +403,13 @@ ADD_SQFUNC("int", NSGetFileSize, "string file", "", ScriptContext::SERVER | Scri if (!IsPathSafe(fileName, dir)) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " - "save folder.", - fileName, - mod->Name) - .c_str()); + sqvm, + fmt::format( + "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " + "save folder.", + fileName, + mod->Name) + .c_str()); return SQRESULT_ERROR; } try @@ -437,13 +437,13 @@ ADD_SQFUNC("void", NSDeleteFile, "string file", "", ScriptContext::SERVER | Scri if (!IsPathSafe(fileName, dir)) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " - "save folder.", - fileName, - mod->Name) - .c_str()); + sqvm, + fmt::format( + "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " + "save folder.", + fileName, + mod->Name) + .c_str()); return SQRESULT_ERROR; } @@ -464,13 +464,13 @@ ADD_SQFUNC("array<string>", NS_InternalGetAllFiles, "string path", "", ScriptCon if (!IsPathSafe(pathStr, dir)) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " - "save folder.", - pathStr, - mod->Name) - .c_str()); + sqvm, + fmt::format( + "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " + "save folder.", + pathStr, + mod->Name) + .c_str()); return SQRESULT_ERROR; } try @@ -502,13 +502,13 @@ ADD_SQFUNC("bool", NSIsFolder, "string path", "", ScriptContext::CLIENT | Script if (!IsPathSafe(pathStr, dir)) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " - "save folder.", - pathStr, - mod->Name) - .c_str()); + sqvm, + fmt::format( + "File name invalid ({})! Make sure it does not contain any non-ASCII character, and results in a path inside your mod's " + "save folder.", + pathStr, + mod->Name) + .c_str()); return SQRESULT_ERROR; } try diff --git a/NorthstarDLL/plugins/plugins.cpp b/NorthstarDLL/plugins/plugins.cpp index 0c4c7fd6..4776f656 100644 --- a/NorthstarDLL/plugins/plugins.cpp +++ b/NorthstarDLL/plugins/plugins.cpp @@ -129,7 +129,7 @@ std::optional<Plugin> PluginManager::LoadPlugin(fs::path path, PluginInitFuncs* if (strcmp(manifestJSON["api_version"].GetString(), std::to_string(ABI_VERSION).c_str())) { NS::log::PLUGINSYS->error( - "'{}' has an incompatible API version number '{}' in its manifest. Current ABI version is '{}'", pathstring, ABI_VERSION); + "'{}' has an incompatible API version number '{}' in its manifest. Current ABI version is '{}'", pathstring, ABI_VERSION); return std::nullopt; } // Passed all checks, going to actually load it now diff --git a/NorthstarDLL/scripts/client/clientchathooks.cpp b/NorthstarDLL/scripts/client/clientchathooks.cpp index df9497ef..6aff1fc3 100644 --- a/NorthstarDLL/scripts/client/clientchathooks.cpp +++ b/NorthstarDLL/scripts/client/clientchathooks.cpp @@ -33,7 +33,7 @@ void, __fastcall, (void* self, const char* message, int inboxId, bool isTeam, bo NS::Utils::RemoveAsciiControlSequences(const_cast<char*>(message), true); SQRESULT result = g_pSquirrel<ScriptContext::CLIENT>->Call( - "CHudChat_ProcessMessageStartThread", static_cast<int>(senderId) - 1, payload, isTeam, isDead, type); + "CHudChat_ProcessMessageStartThread", static_cast<int>(senderId) - 1, payload, isTeam, isDead, type); if (result == SQRESULT_ERROR) for (CHudChat* hud = *CHudChat::allHuds; hud != NULL; hud = hud->next) CHudChat__AddGameLine(hud, message, inboxId, isTeam, isDead); diff --git a/NorthstarDLL/scripts/client/cursorposition.cpp b/NorthstarDLL/scripts/client/cursorposition.cpp index c0e8623c..c1f0c4c2 100644 --- a/NorthstarDLL/scripts/client/cursorposition.cpp +++ b/NorthstarDLL/scripts/client/cursorposition.cpp @@ -11,10 +11,10 @@ ADD_SQFUNC("vector ornull", NSGetCursorPosition, "", "", ScriptContext::UI) return SQRESULT_NULL; g_pSquirrel<context>->pushvector( - sqvm, - {p.x > 0 ? p.x > rcClient.right ? rcClient.right : (float)p.x : 0, - p.y > 0 ? p.y > rcClient.bottom ? rcClient.bottom : (float)p.y : 0, - 0}); + sqvm, + {p.x > 0 ? p.x > rcClient.right ? rcClient.right : (float)p.x : 0, + p.y > 0 ? p.y > rcClient.bottom ? rcClient.bottom : (float)p.y : 0, + 0}); return SQRESULT_NOTNULL; } g_pSquirrel<context>->raiseerror(sqvm, "Failed retrieving cursor position of game window"); diff --git a/NorthstarDLL/scripts/client/scriptmodmenu.cpp b/NorthstarDLL/scripts/client/scriptmodmenu.cpp index a88478fb..da75c64f 100644 --- a/NorthstarDLL/scripts/client/scriptmodmenu.cpp +++ b/NorthstarDLL/scripts/client/scriptmodmenu.cpp @@ -135,7 +135,7 @@ ADD_SQFUNC("bool", NSIsModRequiredOnClient, "string modName", "", ScriptContext: } ADD_SQFUNC( - "array<string>", NSGetModConvarsByModName, "string modName", "", ScriptContext::SERVER | ScriptContext::CLIENT | ScriptContext::UI) + "array<string>", NSGetModConvarsByModName, "string modName", "", ScriptContext::SERVER | ScriptContext::CLIENT | ScriptContext::UI) { const SQChar* modName = g_pSquirrel<context>->getstring(sqvm, 1); g_pSquirrel<context>->newarray(sqvm, 0); diff --git a/NorthstarDLL/scripts/client/scriptserverbrowser.cpp b/NorthstarDLL/scripts/client/scriptserverbrowser.cpp index ff6da6e2..94d964ed 100644 --- a/NorthstarDLL/scripts/client/scriptserverbrowser.cpp +++ b/NorthstarDLL/scripts/client/scriptserverbrowser.cpp @@ -52,12 +52,12 @@ ADD_SQFUNC("void", NSTryAuthWithServer, "int serverIndex, string password = ''", if (serverIndex >= g_pMasterServerManager->m_vRemoteServers.size()) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "Tried to auth with server index {} when only {} servers are available", - serverIndex, - g_pMasterServerManager->m_vRemoteServers.size()) - .c_str()); + sqvm, + fmt::format( + "Tried to auth with server index {} when only {} servers are available", + serverIndex, + g_pMasterServerManager->m_vRemoteServers.size()) + .c_str()); return SQRESULT_ERROR; } @@ -68,10 +68,10 @@ ADD_SQFUNC("void", NSTryAuthWithServer, "int serverIndex, string password = ''", // do auth g_pMasterServerManager->AuthenticateWithServer( - R2::g_pLocalPlayerUserID, - g_pMasterServerManager->m_sOwnClientAuthToken, - g_pMasterServerManager->m_vRemoteServers[serverIndex], - (char*)password); + R2::g_pLocalPlayerUserID, + g_pMasterServerManager->m_sOwnClientAuthToken, + g_pMasterServerManager->m_vRemoteServers[serverIndex], + (char*)password); return SQRESULT_NULL; } @@ -93,7 +93,7 @@ ADD_SQFUNC("void", NSConnectToAuthedServer, "", "", ScriptContext::UI) if (!g_pMasterServerManager->m_bHasPendingConnectionInfo) { g_pSquirrel<context>->raiseerror( - sqvm, fmt::format("Tried to connect to authed server before any pending connection info was available").c_str()); + sqvm, fmt::format("Tried to connect to authed server before any pending connection info was available").c_str()); return SQRESULT_ERROR; } @@ -103,16 +103,16 @@ ADD_SQFUNC("void", NSConnectToAuthedServer, "", "", ScriptContext::UI) // i'm honestly not entirely sure how silentconnect works regarding ports and encryption so using connect for now R2::g_pCVar->FindVar("serverfilter")->SetValue(info.authToken); R2::Cbuf_AddText( - R2::Cbuf_GetCurrentPlayer(), - fmt::format( - "connect {}.{}.{}.{}:{}", - info.ip.S_un.S_un_b.s_b1, - info.ip.S_un.S_un_b.s_b2, - info.ip.S_un.S_un_b.s_b3, - info.ip.S_un.S_un_b.s_b4, - info.port) - .c_str(), - R2::cmd_source_t::kCommandSrcCode); + R2::Cbuf_GetCurrentPlayer(), + fmt::format( + "connect {}.{}.{}.{}:{}", + info.ip.S_un.S_un_b.s_b1, + info.ip.S_un.S_un_b.s_b2, + info.ip.S_un.S_un_b.s_b3, + info.ip.S_un.S_un_b.s_b4, + info.port) + .c_str(), + R2::cmd_source_t::kCommandSrcCode); g_pMasterServerManager->m_bHasPendingConnectionInfo = false; return SQRESULT_NULL; diff --git a/NorthstarDLL/scripts/client/scriptservertoclientstringcommand.cpp b/NorthstarDLL/scripts/client/scriptservertoclientstringcommand.cpp index a3a81c8a..47e189a4 100644 --- a/NorthstarDLL/scripts/client/scriptservertoclientstringcommand.cpp +++ b/NorthstarDLL/scripts/client/scriptservertoclientstringcommand.cpp @@ -11,8 +11,8 @@ void ConCommand_ns_script_servertoclientstringcommand(const CCommand& arg) ON_DLL_LOAD_CLIENT_RELIESON("client.dll", ScriptServerToClientStringCommand, ClientSquirrel, (CModule module)) { RegisterConCommand( - "ns_script_servertoclientstringcommand", - ConCommand_ns_script_servertoclientstringcommand, - "", - FCVAR_CLIENTDLL | FCVAR_SERVER_CAN_EXECUTE); + "ns_script_servertoclientstringcommand", + ConCommand_ns_script_servertoclientstringcommand, + "", + FCVAR_CLIENTDLL | FCVAR_SERVER_CAN_EXECUTE); } diff --git a/NorthstarDLL/scripts/scriptdatatables.cpp b/NorthstarDLL/scripts/scriptdatatables.cpp index 532624f3..478cacc2 100644 --- a/NorthstarDLL/scripts/scriptdatatables.cpp +++ b/NorthstarDLL/scripts/scriptdatatables.cpp @@ -328,10 +328,10 @@ REPLACE_SQFUNC(GetDataTableString, (ScriptContext::UI | ScriptContext::CLIENT | if (nRow >= csv->dataPointers.size() || nCol >= csv->dataPointers[nRow].size()) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) - .c_str()); + sqvm, + fmt::format( + "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) + .c_str()); return SQRESULT_ERROR; } @@ -355,10 +355,10 @@ REPLACE_SQFUNC(GetDataTableAsset, (ScriptContext::UI | ScriptContext::CLIENT | S if (nRow >= csv->dataPointers.size() || nCol >= csv->dataPointers[nRow].size()) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) - .c_str()); + sqvm, + fmt::format( + "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) + .c_str()); return SQRESULT_ERROR; } @@ -382,10 +382,10 @@ REPLACE_SQFUNC(GetDataTableInt, (ScriptContext::UI | ScriptContext::CLIENT | Scr if (nRow >= csv->dataPointers.size() || nCol >= csv->dataPointers[nRow].size()) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) - .c_str()); + sqvm, + fmt::format( + "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) + .c_str()); return SQRESULT_ERROR; } @@ -409,10 +409,10 @@ REPLACE_SQFUNC(GetDataTableFloat, (ScriptContext::UI | ScriptContext::CLIENT | S if (nRow >= csv->dataPointers.size() || nCol >= csv->dataPointers[nRow].size()) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) - .c_str()); + sqvm, + fmt::format( + "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) + .c_str()); return SQRESULT_ERROR; } @@ -436,10 +436,10 @@ REPLACE_SQFUNC(GetDataTableBool, (ScriptContext::UI | ScriptContext::CLIENT | Sc if (nRow >= csv->dataPointers.size() || nCol >= csv->dataPointers[nRow].size()) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) - .c_str()); + sqvm, + fmt::format( + "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) + .c_str()); return SQRESULT_ERROR; } @@ -463,10 +463,10 @@ REPLACE_SQFUNC(GetDataTableVector, (ScriptContext::UI | ScriptContext::CLIENT | if (nRow >= csv->dataPointers.size() || nCol >= csv->dataPointers[nRow].size()) { g_pSquirrel<context>->raiseerror( - sqvm, - fmt::format( - "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) - .c_str()); + sqvm, + fmt::format( + "row {} and col {} are outside of range row {} and col {}", nRow, nCol, csv->dataPointers.size(), csv->columns.size()) + .c_str()); return SQRESULT_ERROR; } @@ -819,67 +819,67 @@ void ConCommand_dump_datatables(const CCommand& args) { // likely not a comprehensive list, might be missing a couple? static const std::vector<const char*> VANILLA_DATATABLE_PATHS = { - "datatable/burn_meter_rewards.rpak", - "datatable/burn_meter_store.rpak", - "datatable/calling_cards.rpak", - "datatable/callsign_icons.rpak", - "datatable/camo_skins.rpak", - "datatable/default_pilot_loadouts.rpak", - "datatable/default_titan_loadouts.rpak", - "datatable/faction_leaders.rpak", - "datatable/fd_awards.rpak", - "datatable/features_mp.rpak", - "datatable/non_loadout_weapons.rpak", - "datatable/pilot_abilities.rpak", - "datatable/pilot_executions.rpak", - "datatable/pilot_passives.rpak", - "datatable/pilot_properties.rpak", - "datatable/pilot_weapons.rpak", - "datatable/pilot_weapon_features.rpak", - "datatable/pilot_weapon_mods.rpak", - "datatable/pilot_weapon_mods_common.rpak", - "datatable/playlist_items.rpak", - "datatable/titans_mp.rpak", - "datatable/titan_abilities.rpak", - "datatable/titan_executions.rpak", - "datatable/titan_fd_upgrades.rpak", - "datatable/titan_nose_art.rpak", - "datatable/titan_passives.rpak", - "datatable/titan_primary_mods.rpak", - "datatable/titan_primary_mods_common.rpak", - "datatable/titan_primary_weapons.rpak", - "datatable/titan_properties.rpak", - "datatable/titan_skins.rpak", - "datatable/titan_voices.rpak", - "datatable/unlocks_faction_level.rpak", - "datatable/unlocks_fd_titan_level.rpak", - "datatable/unlocks_player_level.rpak", - "datatable/unlocks_random.rpak", - "datatable/unlocks_titan_level.rpak", - "datatable/unlocks_weapon_level_pilot.rpak", - "datatable/weapon_skins.rpak", - "datatable/xp_per_faction_level.rpak", - "datatable/xp_per_fd_titan_level.rpak", - "datatable/xp_per_player_level.rpak", - "datatable/xp_per_titan_level.rpak", - "datatable/xp_per_weapon_level.rpak", - "datatable/faction_leaders_dropship_anims.rpak", - "datatable/score_events.rpak", - "datatable/startpoints.rpak", - "datatable/sp_levels.rpak", - "datatable/community_entries.rpak", - "datatable/spotlight_images.rpak", - "datatable/death_hints_mp.rpak", - "datatable/flightpath_assets.rpak", - "datatable/earn_meter_mp.rpak", - "datatable/battle_chatter_voices.rpak", - "datatable/battle_chatter.rpak", - "datatable/titan_os_conversations.rpak", - "datatable/faction_dialogue.rpak", - "datatable/grunt_chatter_mp.rpak", - "datatable/spectre_chatter_mp.rpak", - "datatable/pain_death_sounds.rpak", - "datatable/caller_ids_mp.rpak"}; + "datatable/burn_meter_rewards.rpak", + "datatable/burn_meter_store.rpak", + "datatable/calling_cards.rpak", + "datatable/callsign_icons.rpak", + "datatable/camo_skins.rpak", + "datatable/default_pilot_loadouts.rpak", + "datatable/default_titan_loadouts.rpak", + "datatable/faction_leaders.rpak", + "datatable/fd_awards.rpak", + "datatable/features_mp.rpak", + "datatable/non_loadout_weapons.rpak", + "datatable/pilot_abilities.rpak", + "datatable/pilot_executions.rpak", + "datatable/pilot_passives.rpak", + "datatable/pilot_properties.rpak", + "datatable/pilot_weapons.rpak", + "datatable/pilot_weapon_features.rpak", + "datatable/pilot_weapon_mods.rpak", + "datatable/pilot_weapon_mods_common.rpak", + "datatable/playlist_items.rpak", + "datatable/titans_mp.rpak", + "datatable/titan_abilities.rpak", + "datatable/titan_executions.rpak", + "datatable/titan_fd_upgrades.rpak", + "datatable/titan_nose_art.rpak", + "datatable/titan_passives.rpak", + "datatable/titan_primary_mods.rpak", + "datatable/titan_primary_mods_common.rpak", + "datatable/titan_primary_weapons.rpak", + "datatable/titan_properties.rpak", + "datatable/titan_skins.rpak", + "datatable/titan_voices.rpak", + "datatable/unlocks_faction_level.rpak", + "datatable/unlocks_fd_titan_level.rpak", + "datatable/unlocks_player_level.rpak", + "datatable/unlocks_random.rpak", + "datatable/unlocks_titan_level.rpak", + "datatable/unlocks_weapon_level_pilot.rpak", + "datatable/weapon_skins.rpak", + "datatable/xp_per_faction_level.rpak", + "datatable/xp_per_fd_titan_level.rpak", + "datatable/xp_per_player_level.rpak", + "datatable/xp_per_titan_level.rpak", + "datatable/xp_per_weapon_level.rpak", + "datatable/faction_leaders_dropship_anims.rpak", + "datatable/score_events.rpak", + "datatable/startpoints.rpak", + "datatable/sp_levels.rpak", + "datatable/community_entries.rpak", + "datatable/spotlight_images.rpak", + "datatable/death_hints_mp.rpak", + "datatable/flightpath_assets.rpak", + "datatable/earn_meter_mp.rpak", + "datatable/battle_chatter_voices.rpak", + "datatable/battle_chatter.rpak", + "datatable/titan_os_conversations.rpak", + "datatable/faction_dialogue.rpak", + "datatable/grunt_chatter_mp.rpak", + "datatable/spectre_chatter_mp.rpak", + "datatable/pain_death_sounds.rpak", + "datatable/caller_ids_mp.rpak"}; for (const char* datatable : VANILLA_DATATABLE_PATHS) DumpDatatable(datatable); @@ -899,10 +899,10 @@ ON_DLL_LOAD_RELIESON("client.dll", ClientScriptDatatables, ClientSquirrel, (CMod ON_DLL_LOAD_RELIESON("engine.dll", SharedScriptDataTables, ConVar, (CModule module)) { Cvar_ns_prefer_datatable_from_disk = new ConVar( - "ns_prefer_datatable_from_disk", - IsDedicatedServer() && Tier0::CommandLine()->CheckParm("-nopakdedi") ? "1" : "0", - FCVAR_NONE, - "whether to prefer loading datatables from disk, rather than rpak"); + "ns_prefer_datatable_from_disk", + IsDedicatedServer() && Tier0::CommandLine()->CheckParm("-nopakdedi") ? "1" : "0", + FCVAR_NONE, + "whether to prefer loading datatables from disk, rather than rpak"); RegisterConCommand("dump_datatables", ConCommand_dump_datatables, "dumps all datatables from a hardcoded list", FCVAR_NONE); RegisterConCommand("dump_datatable", ConCommand_dump_datatable, "dump a datatable", FCVAR_NONE); diff --git a/NorthstarDLL/scripts/scripthttprequesthandler.cpp b/NorthstarDLL/scripts/scripthttprequesthandler.cpp index 813bd50e..8fddaeff 100644 --- a/NorthstarDLL/scripts/scripthttprequesthandler.cpp +++ b/NorthstarDLL/scripts/scripthttprequesthandler.cpp @@ -220,7 +220,7 @@ template <ScriptContext context> int HttpRequestHandler::MakeHttpRequest(const H if (IsHttpDisabled()) { spdlog::warn("NS_InternalMakeHttpRequest called while the game is running with -disablehttprequests." - " Please check if requests are allowed using NSIsHttpEnabled() first."); + " Please check if requests are allowed using NSIsHttpEnabled() first."); return -1; } @@ -230,219 +230,219 @@ template <ScriptContext context> int HttpRequestHandler::MakeHttpRequest(const H int handle = ++m_iLastRequestHandle; std::thread requestThread( - [this, handle, requestParameters, bAllowLocalHttp]() - { - std::string hostname, resolvedAddress, resolvedPort; - - if (!bAllowLocalHttp) - { - if (!IsHttpDestinationHostAllowed(requestParameters.baseUrl, hostname, resolvedAddress, resolvedPort)) - { - spdlog::warn( - "HttpRequestHandler::MakeHttpRequest attempted to make a request to a private network. This is only allowed when " - "running the game with -allowlocalhttp."); - g_pSquirrel<context>->AsyncCall( - "NSHandleFailedHttpRequest", - handle, - (int)0, - "Cannot make HTTP requests to private network hosts without -allowlocalhttp. Check your console for more " - "information."); - return; - } - } - - CURL* curl = curl_easy_init(); - if (!curl) - { - spdlog::error("HttpRequestHandler::MakeHttpRequest failed to init libcurl for request."); - g_pSquirrel<context>->AsyncCall( - "NSHandleFailedHttpRequest", handle, static_cast<int>(CURLE_FAILED_INIT), curl_easy_strerror(CURLE_FAILED_INIT)); - return; - } - - // HEAD has no body. - if (requestParameters.method == HttpRequestMethod::HRM_HEAD) - { - curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); - } - - curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, HttpRequestMethod::ToString(requestParameters.method).c_str()); - - // Only resolve to IPv4 if we don't allow private network requests. - curl_slist* host = nullptr; - if (!bAllowLocalHttp) - { - curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); - host = curl_slist_append(host, fmt::format("{}:{}:{}", hostname, resolvedPort, resolvedAddress).c_str()); - curl_easy_setopt(curl, CURLOPT_RESOLVE, host); - } - - // Ensure we only allow HTTP or HTTPS. - curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); - - // Allow redirects - curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); - curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L); - - // Check if the url already contains a query. - // If so, we'll know to append with & instead of start with ? - std::string queryUrl = requestParameters.baseUrl; - bool bUrlContainsQuery = false; - - // If this fails, just ignore the parsing and trust what the user wants to query. - // Probably will fail but handling it here would be annoying. - CURLU* curlUrl = curl_url(); - if (curlUrl) - { - if (curl_url_set(curlUrl, CURLUPART_URL, queryUrl.c_str(), CURLU_DEFAULT_SCHEME) == CURLUE_OK) - { - char* currentQuery; - if (curl_url_get(curlUrl, CURLUPART_QUERY, ¤tQuery, 0) == CURLUE_OK) - { - if (currentQuery && std::strlen(currentQuery) != 0) - { - bUrlContainsQuery = true; - } - } - - curl_free(currentQuery); - } - - curl_url_cleanup(curlUrl); - } - - // GET requests, or POST-like requests with an empty body, can have query parameters. - // Append them to the base url. - if (HttpRequestMethod::CanHaveQueryParameters(requestParameters.method) && - !HttpRequestMethod::UsesCurlPostOptions(requestParameters.method) || - requestParameters.body.empty()) - { - bool isFirstValue = true; - for (const auto& kv : requestParameters.queryParameters) - { - char* key = curl_easy_escape(curl, kv.first.c_str(), kv.first.length()); - - for (const std::string& queryValue : kv.second) - { - char* value = curl_easy_escape(curl, queryValue.c_str(), queryValue.length()); - - if (isFirstValue && !bUrlContainsQuery) - { - queryUrl.append(fmt::format("?{}={}", key, value)); - isFirstValue = false; - } - else - { - queryUrl.append(fmt::format("&{}={}", key, value)); - } - - curl_free(value); - } - - curl_free(key); - } - } - - // If this method uses POST-like curl options, set those and set the body. - // The body won't be sent if it's empty anyway, meaning the query parameters above, if any, would be. - if (HttpRequestMethod::UsesCurlPostOptions(requestParameters.method)) - { - // Grab the body and set it as a POST field - curl_easy_setopt(curl, CURLOPT_POST, 1L); - - curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, requestParameters.body.length()); - curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, requestParameters.body.c_str()); - } - - // Set the full URL for this http request. - curl_easy_setopt(curl, CURLOPT_URL, queryUrl.c_str()); - - std::string bodyBuffer; - std::string headerBuffer; - - // Set up buffers to write the response headers and body. - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HttpCurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bodyBuffer); - curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, HttpCurlWriteToStringBufferCallback); - curl_easy_setopt(curl, CURLOPT_HEADERDATA, &headerBuffer); - - // Add all the headers for the request. - curl_slist* headers = nullptr; - - // Content-Type header for POST-like requests. - if (HttpRequestMethod::UsesCurlPostOptions(requestParameters.method) && !requestParameters.body.empty()) - { - headers = curl_slist_append(headers, fmt::format("Content-Type: {}", requestParameters.contentType).c_str()); - } - - for (const auto& kv : requestParameters.headers) - { - for (const std::string& headerValue : kv.second) - { - headers = curl_slist_append(headers, fmt::format("{}: {}", kv.first, headerValue).c_str()); - } - } - - if (headers != nullptr) - { - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); - } - - // Disable SSL checks if requested by the user. - if (DisableHttpSsl()) - { - curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); - curl_easy_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 0L); - } - - // Enforce the Northstar user agent, unless an override was specified. - if (requestParameters.userAgent.empty()) - { - curl_easy_setopt(curl, CURLOPT_USERAGENT, &NSUserAgent); - } - else - { - curl_easy_setopt(curl, CURLOPT_USERAGENT, requestParameters.userAgent.c_str()); - } - - // Set the timeout for this request. Max 60 seconds so mods can't just spin up native threads all the time. - curl_easy_setopt(curl, CURLOPT_TIMEOUT, std::clamp<long>(requestParameters.timeout, 1, 60)); - - CURLcode result = curl_easy_perform(curl); - if (IsRunning()) - { - if (result == CURLE_OK) - { - // While the curl request is OK, it could return a non success code. - // Squirrel side will handle firing the correct callback. - long httpCode = 0; - curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode); - g_pSquirrel<context>->AsyncCall( - "NSHandleSuccessfulHttpRequest", handle, static_cast<int>(httpCode), bodyBuffer, headerBuffer); - } - else - { - // Pass CURL result code & error. - spdlog::error( - "curl_easy_perform() failed with code {}, error: {}", static_cast<int>(result), curl_easy_strerror(result)); - - // If it's an SSL issue, tell the user they may disable SSL checks using -disablehttpssl. - if (result == CURLE_PEER_FAILED_VERIFICATION || result == CURLE_SSL_CERTPROBLEM || - result == CURLE_SSL_INVALIDCERTSTATUS) - { - spdlog::error("You can try disabling SSL verifications for this issue using the -disablehttpssl launch argument. " - "Keep in mind this is potentially dangerous!"); - } - - g_pSquirrel<context>->AsyncCall( - "NSHandleFailedHttpRequest", handle, static_cast<int>(result), curl_easy_strerror(result)); - } - } - - curl_easy_cleanup(curl); - curl_slist_free_all(headers); - curl_slist_free_all(host); - }); + [this, handle, requestParameters, bAllowLocalHttp]() + { + std::string hostname, resolvedAddress, resolvedPort; + + if (!bAllowLocalHttp) + { + if (!IsHttpDestinationHostAllowed(requestParameters.baseUrl, hostname, resolvedAddress, resolvedPort)) + { + spdlog::warn( + "HttpRequestHandler::MakeHttpRequest attempted to make a request to a private network. This is only allowed when " + "running the game with -allowlocalhttp."); + g_pSquirrel<context>->AsyncCall( + "NSHandleFailedHttpRequest", + handle, + (int)0, + "Cannot make HTTP requests to private network hosts without -allowlocalhttp. Check your console for more " + "information."); + return; + } + } + + CURL* curl = curl_easy_init(); + if (!curl) + { + spdlog::error("HttpRequestHandler::MakeHttpRequest failed to init libcurl for request."); + g_pSquirrel<context>->AsyncCall( + "NSHandleFailedHttpRequest", handle, static_cast<int>(CURLE_FAILED_INIT), curl_easy_strerror(CURLE_FAILED_INIT)); + return; + } + + // HEAD has no body. + if (requestParameters.method == HttpRequestMethod::HRM_HEAD) + { + curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); + } + + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, HttpRequestMethod::ToString(requestParameters.method).c_str()); + + // Only resolve to IPv4 if we don't allow private network requests. + curl_slist* host = nullptr; + if (!bAllowLocalHttp) + { + curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); + host = curl_slist_append(host, fmt::format("{}:{}:{}", hostname, resolvedPort, resolvedAddress).c_str()); + curl_easy_setopt(curl, CURLOPT_RESOLVE, host); + } + + // Ensure we only allow HTTP or HTTPS. + curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); + + // Allow redirects + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L); + + // Check if the url already contains a query. + // If so, we'll know to append with & instead of start with ? + std::string queryUrl = requestParameters.baseUrl; + bool bUrlContainsQuery = false; + + // If this fails, just ignore the parsing and trust what the user wants to query. + // Probably will fail but handling it here would be annoying. + CURLU* curlUrl = curl_url(); + if (curlUrl) + { + if (curl_url_set(curlUrl, CURLUPART_URL, queryUrl.c_str(), CURLU_DEFAULT_SCHEME) == CURLUE_OK) + { + char* currentQuery; + if (curl_url_get(curlUrl, CURLUPART_QUERY, ¤tQuery, 0) == CURLUE_OK) + { + if (currentQuery && std::strlen(currentQuery) != 0) + { + bUrlContainsQuery = true; + } + } + + curl_free(currentQuery); + } + + curl_url_cleanup(curlUrl); + } + + // GET requests, or POST-like requests with an empty body, can have query parameters. + // Append them to the base url. + if (HttpRequestMethod::CanHaveQueryParameters(requestParameters.method) && + !HttpRequestMethod::UsesCurlPostOptions(requestParameters.method) || + requestParameters.body.empty()) + { + bool isFirstValue = true; + for (const auto& kv : requestParameters.queryParameters) + { + char* key = curl_easy_escape(curl, kv.first.c_str(), kv.first.length()); + + for (const std::string& queryValue : kv.second) + { + char* value = curl_easy_escape(curl, queryValue.c_str(), queryValue.length()); + + if (isFirstValue && !bUrlContainsQuery) + { + queryUrl.append(fmt::format("?{}={}", key, value)); + isFirstValue = false; + } + else + { + queryUrl.append(fmt::format("&{}={}", key, value)); + } + + curl_free(value); + } + + curl_free(key); + } + } + + // If this method uses POST-like curl options, set those and set the body. + // The body won't be sent if it's empty anyway, meaning the query parameters above, if any, would be. + if (HttpRequestMethod::UsesCurlPostOptions(requestParameters.method)) + { + // Grab the body and set it as a POST field + curl_easy_setopt(curl, CURLOPT_POST, 1L); + + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, requestParameters.body.length()); + curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, requestParameters.body.c_str()); + } + + // Set the full URL for this http request. + curl_easy_setopt(curl, CURLOPT_URL, queryUrl.c_str()); + + std::string bodyBuffer; + std::string headerBuffer; + + // Set up buffers to write the response headers and body. + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HttpCurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bodyBuffer); + curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, HttpCurlWriteToStringBufferCallback); + curl_easy_setopt(curl, CURLOPT_HEADERDATA, &headerBuffer); + + // Add all the headers for the request. + curl_slist* headers = nullptr; + + // Content-Type header for POST-like requests. + if (HttpRequestMethod::UsesCurlPostOptions(requestParameters.method) && !requestParameters.body.empty()) + { + headers = curl_slist_append(headers, fmt::format("Content-Type: {}", requestParameters.contentType).c_str()); + } + + for (const auto& kv : requestParameters.headers) + { + for (const std::string& headerValue : kv.second) + { + headers = curl_slist_append(headers, fmt::format("{}: {}", kv.first, headerValue).c_str()); + } + } + + if (headers != nullptr) + { + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); + } + + // Disable SSL checks if requested by the user. + if (DisableHttpSsl()) + { + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 0L); + } + + // Enforce the Northstar user agent, unless an override was specified. + if (requestParameters.userAgent.empty()) + { + curl_easy_setopt(curl, CURLOPT_USERAGENT, &NSUserAgent); + } + else + { + curl_easy_setopt(curl, CURLOPT_USERAGENT, requestParameters.userAgent.c_str()); + } + + // Set the timeout for this request. Max 60 seconds so mods can't just spin up native threads all the time. + curl_easy_setopt(curl, CURLOPT_TIMEOUT, std::clamp<long>(requestParameters.timeout, 1, 60)); + + CURLcode result = curl_easy_perform(curl); + if (IsRunning()) + { + if (result == CURLE_OK) + { + // While the curl request is OK, it could return a non success code. + // Squirrel side will handle firing the correct callback. + long httpCode = 0; + curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode); + g_pSquirrel<context>->AsyncCall( + "NSHandleSuccessfulHttpRequest", handle, static_cast<int>(httpCode), bodyBuffer, headerBuffer); + } + else + { + // Pass CURL result code & error. + spdlog::error( + "curl_easy_perform() failed with code {}, error: {}", static_cast<int>(result), curl_easy_strerror(result)); + + // If it's an SSL issue, tell the user they may disable SSL checks using -disablehttpssl. + if (result == CURLE_PEER_FAILED_VERIFICATION || result == CURLE_SSL_CERTPROBLEM || + result == CURLE_SSL_INVALIDCERTSTATUS) + { + spdlog::error("You can try disabling SSL verifications for this issue using the -disablehttpssl launch argument. " + "Keep in mind this is potentially dangerous!"); + } + + g_pSquirrel<context>->AsyncCall( + "NSHandleFailedHttpRequest", handle, static_cast<int>(result), curl_easy_strerror(result)); + } + } + + curl_easy_cleanup(curl); + curl_slist_free_all(headers); + curl_slist_free_all(host); + }); requestThread.detach(); return handle; @@ -462,7 +462,7 @@ template <ScriptContext context> SQRESULT SQ_InternalMakeHttpRequest(HSquirrelVM if (IsHttpDisabled()) { spdlog::warn("NS_InternalMakeHttpRequest called while the game is running with -disablehttprequests." - " Please check if requests are allowed using NSIsHttpEnabled() first."); + " Please check if requests are allowed using NSIsHttpEnabled() first."); g_pSquirrel<context>->pushinteger(sqvm, -1); return SQRESULT_NOTNULL; } @@ -543,28 +543,28 @@ template <ScriptContext context> SQRESULT SQ_IsLocalHttpAllowed(HSquirrelVM* sqv template <ScriptContext context> void HttpRequestHandler::RegisterSQFuncs() { g_pSquirrel<context>->AddFuncRegistration( - "int", - "NS_InternalMakeHttpRequest", - "int method, string baseUrl, table<string, array<string> > headers, table<string, array<string> > queryParams, string contentType, " - "string body, " - "int timeout, string userAgent", - "[Internal use only] Passes the HttpRequest struct fields to be reconstructed in native and used for an http request", - SQ_InternalMakeHttpRequest<context>); + "int", + "NS_InternalMakeHttpRequest", + "int method, string baseUrl, table<string, array<string> > headers, table<string, array<string> > queryParams, string contentType, " + "string body, " + "int timeout, string userAgent", + "[Internal use only] Passes the HttpRequest struct fields to be reconstructed in native and used for an http request", + SQ_InternalMakeHttpRequest<context>); g_pSquirrel<context>->AddFuncRegistration( - "bool", - "NSIsHttpEnabled", - "", - "Whether or not HTTP requests are enabled. You can opt-out by starting the game with -disablehttprequests.", - SQ_IsHttpEnabled<context>); + "bool", + "NSIsHttpEnabled", + "", + "Whether or not HTTP requests are enabled. You can opt-out by starting the game with -disablehttprequests.", + SQ_IsHttpEnabled<context>); g_pSquirrel<context>->AddFuncRegistration( - "bool", - "NSIsLocalHttpAllowed", - "", - "Whether or not HTTP requests can be made to a private network address. You can enable this by starting the game with " - "-allowlocalhttp.", - SQ_IsLocalHttpAllowed<context>); + "bool", + "NSIsLocalHttpAllowed", + "", + "Whether or not HTTP requests can be made to a private network address. You can enable this by starting the game with " + "-allowlocalhttp.", + SQ_IsLocalHttpAllowed<context>); } ON_DLL_LOAD_RELIESON("client.dll", HttpRequestHandler_ClientInit, ClientSquirrel, (CModule module)) diff --git a/NorthstarDLL/scripts/scriptjson.cpp b/NorthstarDLL/scripts/scriptjson.cpp index 06bda6f4..4e13e994 100644 --- a/NorthstarDLL/scripts/scriptjson.cpp +++ b/NorthstarDLL/scripts/scriptjson.cpp @@ -58,13 +58,13 @@ DecodeJsonTable(HSquirrelVM* sqvm, rapidjson::GenericValue<rapidjson::UTF8<char> case rapidjson::kObjectType: g_pSquirrel<context>->pushstring(sqvm, itr->name.GetString(), -1); DecodeJsonTable<context>( - sqvm, (rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>*)&itr->value); + sqvm, (rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>*)&itr->value); g_pSquirrel<context>->newslot(sqvm, -3, false); break; case rapidjson::kArrayType: g_pSquirrel<context>->pushstring(sqvm, itr->name.GetString(), -1); DecodeJsonArray<context>( - sqvm, (rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>*)&itr->value); + sqvm, (rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>*)&itr->value); g_pSquirrel<context>->newslot(sqvm, -3, false); break; case rapidjson::kStringType: @@ -97,9 +97,9 @@ DecodeJsonTable(HSquirrelVM* sqvm, rapidjson::GenericValue<rapidjson::UTF8<char> } template <ScriptContext context> void EncodeJSONTable( - SQTable* table, - rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>* obj, - rapidjson::MemoryPoolAllocator<SourceAllocator>& allocator) + SQTable* table, + rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>* obj, + rapidjson::MemoryPoolAllocator<SourceAllocator>& allocator) { for (int i = 0; i < table->_numOfNodes; i++) { @@ -113,7 +113,7 @@ template <ScriptContext context> void EncodeJSONTable( { case OT_STRING: obj->AddMember( - rapidjson::StringRef(node->key._VAL.asString->_val), rapidjson::StringRef(node->val._VAL.asString->_val), allocator); + rapidjson::StringRef(node->key._VAL.asString->_val), rapidjson::StringRef(node->val._VAL.asString->_val), allocator); break; case OT_INTEGER: obj->AddMember(rapidjson::StringRef(node->key._VAL.asString->_val), node->val._VAL.asInteger, allocator); @@ -148,9 +148,9 @@ template <ScriptContext context> void EncodeJSONTable( } template <ScriptContext context> void EncodeJSONArray( - SQArray* arr, - rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>* obj, - rapidjson::MemoryPoolAllocator<SourceAllocator>& allocator) + SQArray* arr, + rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>* obj, + rapidjson::MemoryPoolAllocator<SourceAllocator>& allocator) { for (int i = 0; i < arr->_usedSlots; i++) { @@ -191,11 +191,11 @@ template <ScriptContext context> void EncodeJSONArray( } ADD_SQFUNC( - "table", - DecodeJSON, - "string json, bool fatalParseErrors = false", - "converts a json string to a squirrel table", - ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) + "table", + DecodeJSON, + "string json, bool fatalParseErrors = false", + "converts a json string to a squirrel table", + ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) { const char* pJson = g_pSquirrel<context>->getstring(sqvm, 1); const bool bFatalParseErrors = g_pSquirrel<context>->getbool(sqvm, 2); @@ -207,9 +207,9 @@ ADD_SQFUNC( g_pSquirrel<context>->newtable(sqvm); std::string sErrorString = fmt::format( - "Failed parsing json file: encountered parse error \"{}\" at offset {}", - GetParseError_En(doc.GetParseError()), - doc.GetErrorOffset()); + "Failed parsing json file: encountered parse error \"{}\" at offset {}", + GetParseError_En(doc.GetParseError()), + doc.GetErrorOffset()); if (bFatalParseErrors) { @@ -226,11 +226,11 @@ ADD_SQFUNC( } ADD_SQFUNC( - "string", - EncodeJSON, - "table data", - "converts a squirrel table to a json string", - ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) + "string", + EncodeJSON, + "table data", + "converts a squirrel table to a json string", + ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) { rapidjson_document doc; doc.SetObject(); diff --git a/NorthstarDLL/scripts/scriptjson.h b/NorthstarDLL/scripts/scriptjson.h index b747106b..ed53236d 100644 --- a/NorthstarDLL/scripts/scriptjson.h +++ b/NorthstarDLL/scripts/scriptjson.h @@ -5,9 +5,9 @@ #include "rapidjson/stringbuffer.h" template <ScriptContext context> void EncodeJSONTable( - SQTable* table, - rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>* obj, - rapidjson::MemoryPoolAllocator<SourceAllocator>& allocator); + SQTable* table, + rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>* obj, + rapidjson::MemoryPoolAllocator<SourceAllocator>& allocator); template <ScriptContext context> void DecodeJsonTable(HSquirrelVM* sqvm, rapidjson::GenericValue<rapidjson::UTF8<char>, rapidjson::MemoryPoolAllocator<SourceAllocator>>* obj); diff --git a/NorthstarDLL/scripts/scriptutility.cpp b/NorthstarDLL/scripts/scriptutility.cpp index 054836ca..0b22d315 100644 --- a/NorthstarDLL/scripts/scriptutility.cpp +++ b/NorthstarDLL/scripts/scriptutility.cpp @@ -4,11 +4,11 @@ // asset function StringToAsset( string assetName ) ADD_SQFUNC( - "asset", - StringToAsset, - "string assetName", - "converts a given string to an asset", - ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) + "asset", + StringToAsset, + "string assetName", + "converts a given string to an asset", + ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) { g_pSquirrel<context>->pushasset(sqvm, g_pSquirrel<context>->getstring(sqvm, 1), -1); return SQRESULT_NOTNULL; @@ -16,7 +16,7 @@ ADD_SQFUNC( // string function NSGetLocalPlayerUID() ADD_SQFUNC( - "string", NSGetLocalPlayerUID, "", "Returns the local player's uid.", ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) + "string", NSGetLocalPlayerUID, "", "Returns the local player's uid.", ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) { if (R2::g_pLocalPlayerUserID) { diff --git a/NorthstarDLL/scripts/server/miscserverscript.cpp b/NorthstarDLL/scripts/server/miscserverscript.cpp index 3ea44ceb..090bdc4c 100644 --- a/NorthstarDLL/scripts/server/miscserverscript.cpp +++ b/NorthstarDLL/scripts/server/miscserverscript.cpp @@ -59,11 +59,11 @@ ADD_SQFUNC("bool", NSIsDedicated, "", "", ScriptContext::SERVER) } ADD_SQFUNC( - "bool", - NSDisconnectPlayer, - "entity player, string reason", - "Disconnects the player from the server with the given reason", - ScriptContext::SERVER) + "bool", + NSDisconnectPlayer, + "entity player, string reason", + "Disconnects the player from the server with the given reason", + ScriptContext::SERVER) { const R2::CBasePlayer* pPlayer = g_pSquirrel<context>->template getentity<R2::CBasePlayer>(sqvm, 1); const char* reason = g_pSquirrel<context>->getstring(sqvm, 2); diff --git a/NorthstarDLL/server/auth/serverauthentication.cpp b/NorthstarDLL/server/auth/serverauthentication.cpp index d5653dcc..56ecbc8e 100644 --- a/NorthstarDLL/server/auth/serverauthentication.cpp +++ b/NorthstarDLL/server/auth/serverauthentication.cpp @@ -192,7 +192,7 @@ void ServerAuthenticationManager::WritePersistentData(R2::CBaseClient* pPlayer) if (pPlayer->m_iPersistenceReady == R2::ePersistenceReady::READY_REMOTE) { g_pMasterServerManager->WritePlayerPersistentData( - pPlayer->m_UID, (const char*)pPlayer->m_PersistenceBuffer, m_PlayerAuthenticationData[pPlayer].pdataSize); + pPlayer->m_UID, (const char*)pPlayer->m_PersistenceBuffer, m_PlayerAuthenticationData[pPlayer].pdataSize); } else if (Cvar_ns_auth_allow_insecure_write->GetBool()) { @@ -350,17 +350,17 @@ ON_DLL_LOAD_RELIESON("engine.dll", ServerAuthentication, (ConCommand, ConVar), ( g_pServerAuthentication = new ServerAuthenticationManager; g_pServerAuthentication->Cvar_ns_erase_auth_info = - new ConVar("ns_erase_auth_info", "1", FCVAR_GAMEDLL, "Whether auth info should be erased from this server on disconnect or crash"); + new ConVar("ns_erase_auth_info", "1", FCVAR_GAMEDLL, "Whether auth info should be erased from this server on disconnect or crash"); g_pServerAuthentication->Cvar_ns_auth_allow_insecure = - new ConVar("ns_auth_allow_insecure", "0", FCVAR_GAMEDLL, "Whether this server will allow unauthenicated players to connect"); + new ConVar("ns_auth_allow_insecure", "0", FCVAR_GAMEDLL, "Whether this server will allow unauthenicated players to connect"); g_pServerAuthentication->Cvar_ns_auth_allow_insecure_write = new ConVar( - "ns_auth_allow_insecure_write", - "0", - FCVAR_GAMEDLL, - "Whether the pdata of unauthenticated clients will be written to disk when changed"); + "ns_auth_allow_insecure_write", + "0", + FCVAR_GAMEDLL, + "Whether the pdata of unauthenticated clients will be written to disk when changed"); RegisterConCommand( - "ns_resetpersistence", ConCommand_ns_resetpersistence, "resets your pdata when you next enter the lobby", FCVAR_NONE); + "ns_resetpersistence", ConCommand_ns_resetpersistence, "resets your pdata when you next enter the lobby", FCVAR_NONE); // patch to disable kicking based on incorrect serverfilter in connectclient, since we repurpose it for use as an auth token module.Offset(0x114655).Patch("EB"); diff --git a/NorthstarDLL/server/buildainfile.cpp b/NorthstarDLL/server/buildainfile.cpp index d0143295..e6bd157a 100644 --- a/NorthstarDLL/server/buildainfile.cpp +++ b/NorthstarDLL/server/buildainfile.cpp @@ -226,7 +226,7 @@ void DumpAINInfo(CAI_Network* aiNetwork) memcpy(diskNode.unk3, aiNetwork->nodes[i]->unk3, sizeof(diskNode.unk3)); diskNode.unk4 = aiNetwork->nodes[i]->unk6; diskNode.unk5 = - -1; // aiNetwork->nodes[i]->unk8; // this field is wrong, however, it's always -1 in vanilla navmeshes anyway, so no biggie + -1; // aiNetwork->nodes[i]->unk8; // this field is wrong, however, it's always -1 in vanilla navmeshes anyway, so no biggie memcpy(diskNode.unk6, aiNetwork->nodes[i]->unk10, sizeof(diskNode.unk6)); spdlog::info("writing node {} from {} to {:x}", aiNetwork->nodes[i]->index, (void*)aiNetwork->nodes[i], writeStream.tellp()); @@ -386,7 +386,7 @@ ON_DLL_LOAD("server.dll", BuildAINFile, (CModule module)) AUTOHOOK_DISPATCH() Cvar_ns_ai_dumpAINfileFromLoad = new ConVar( - "ns_ai_dumpAINfileFromLoad", "0", FCVAR_NONE, "For debugging: whether we should dump ain data for ains loaded from disk"); + "ns_ai_dumpAINfileFromLoad", "0", FCVAR_NONE, "For debugging: whether we should dump ain data for ains loaded from disk"); pUnkStruct0Count = module.Offset(0x1063BF8).RCast<int*>(); pppUnkNodeStruct0s = module.Offset(0x1063BE0).RCast<UnkNodeStruct0***>(); diff --git a/NorthstarDLL/server/serverchathooks.cpp b/NorthstarDLL/server/serverchathooks.cpp index cb3af244..fff3c1d9 100644 --- a/NorthstarDLL/server/serverchathooks.cpp +++ b/NorthstarDLL/server/serverchathooks.cpp @@ -20,7 +20,7 @@ class CRecipientFilter CServerGameDLL* g_pServerGameDLL; void(__fastcall* CServerGameDLL__OnReceivedSayTextMessage)( - CServerGameDLL* self, unsigned int senderPlayerId, const char* text, int channelId); + CServerGameDLL* self, unsigned int senderPlayerId, const char* text, int channelId); void(__fastcall* CRecipientFilter__Construct)(CRecipientFilter* self); void(__fastcall* CRecipientFilter__Destruct)(CRecipientFilter* self); @@ -56,7 +56,7 @@ void, __fastcall, (CServerGameDLL* self, unsigned int senderPlayerId, const char return; SQRESULT result = g_pSquirrel<ScriptContext::SERVER>->Call( - "CServerGameDLL_ProcessMessageStartThread", static_cast<int>(senderPlayerId) - 1, text, isTeam); + "CServerGameDLL_ProcessMessageStartThread", static_cast<int>(senderPlayerId) - 1, text, isTeam); if (result == SQRESULT_ERROR) _CServerGameDLL__OnReceivedSayTextMessage(self, senderPlayerId, text, isTeam); @@ -66,11 +66,11 @@ void ChatSendMessage(unsigned int playerIndex, const char* text, bool isTeam) { bShouldCallSayTextHook = true; CServerGameDLL__OnReceivedSayTextMessage( - g_pServerGameDLL, - // Ensure the first bit isn't set, since this indicates a custom message - (playerIndex + 1) & CUSTOM_MESSAGE_INDEX_MASK, - text, - isTeam); + g_pServerGameDLL, + // Ensure the first bit isn't set, since this indicates a custom message + (playerIndex + 1) & CUSTOM_MESSAGE_INDEX_MASK, + text, + isTeam); } void ChatBroadcastMessage(int fromPlayerIndex, int toPlayerIndex, const char* text, bool isTeam, bool isDead, CustomMessageType messageType) @@ -125,11 +125,11 @@ ADD_SQFUNC("void", NSSendMessage, "int playerIndex, string text, bool isTeam", " } ADD_SQFUNC( - "void", - NSBroadcastMessage, - "int fromPlayerIndex, int toPlayerIndex, string text, bool isTeam, bool isDead, int messageType", - "", - ScriptContext::SERVER) + "void", + NSBroadcastMessage, + "int fromPlayerIndex, int toPlayerIndex, string text, bool isTeam, bool isDead, int messageType", + "", + ScriptContext::SERVER) { int fromPlayerIndex = g_pSquirrel<ScriptContext::SERVER>->getinteger(sqvm, 1); int toPlayerIndex = g_pSquirrel<ScriptContext::SERVER>->getinteger(sqvm, 2); @@ -159,7 +159,7 @@ ON_DLL_LOAD_RELIESON("server.dll", ServerChatHooks, ServerSquirrel, (CModule mod AUTOHOOK_DISPATCH_MODULE(server.dll) CServerGameDLL__OnReceivedSayTextMessage = - module.Offset(0x1595C0).RCast<void(__fastcall*)(CServerGameDLL*, unsigned int, const char*, int)>(); + module.Offset(0x1595C0).RCast<void(__fastcall*)(CServerGameDLL*, unsigned int, const char*, int)>(); CRecipientFilter__Construct = module.Offset(0x1E9440).RCast<void(__fastcall*)(CRecipientFilter*)>(); CRecipientFilter__Destruct = module.Offset(0x1E9700).RCast<void(__fastcall*)(CRecipientFilter*)>(); CRecipientFilter__AddAllPlayers = module.Offset(0x1E9940).RCast<void(__fastcall*)(CRecipientFilter*)>(); diff --git a/NorthstarDLL/server/serverchathooks.h b/NorthstarDLL/server/serverchathooks.h index d033e769..e5d63313 100644 --- a/NorthstarDLL/server/serverchathooks.h +++ b/NorthstarDLL/server/serverchathooks.h @@ -21,4 +21,4 @@ void ChatSendMessage(unsigned int playerIndex, const char* text, bool isteam); // isDead: display a [DEAD] badge // messageType: send a specific message type void ChatBroadcastMessage( - int fromPlayerIndex, int toPlayerIndex, const char* text, bool isTeam, bool isDead, CustomMessageType messageType); + int fromPlayerIndex, int toPlayerIndex, const char* text, bool isTeam, bool isDead, CustomMessageType messageType); diff --git a/NorthstarDLL/server/servernethooks.cpp b/NorthstarDLL/server/servernethooks.cpp index f74f2d38..1b923bd7 100644 --- a/NorthstarDLL/server/servernethooks.cpp +++ b/NorthstarDLL/server/servernethooks.cpp @@ -101,10 +101,10 @@ static void ProcessAtlasConnectionlessPacketSigreq1(R2::netpacket_t* packet, boo { if (dbg) spdlog::warn( - "ignoring Atlas connectionless packet (size={} type={}): invalid (data={}): no masterserver token yet", - packet->size, - pType, - pData); + "ignoring Atlas connectionless packet (size={} type={}): invalid (data={}): no masterserver token yet", + packet->size, + pType, + pData); return; } @@ -114,16 +114,16 @@ static void ProcessAtlasConnectionlessPacketSigreq1(R2::netpacket_t* packet, boo { if (dbg) spdlog::warn( - "ignoring Atlas connectionless packet (size={} type={}): invalid: invalid signature (key={})", - packet->size, - pType, - std::string(g_pMasterServerManager->m_sOwnServerAuthToken)); + "ignoring Atlas connectionless packet (size={} type={}): invalid: invalid signature (key={})", + packet->size, + pType, + std::string(g_pMasterServerManager->m_sOwnServerAuthToken)); return; } spdlog::warn( - "processing Atlas connectionless packet (size={} type={}) with invalid signature due to net_debug_atlas_packet_insecure", - packet->size, - pType); + "processing Atlas connectionless packet (size={} type={}) with invalid signature due to net_debug_atlas_packet_insecure", + packet->size, + pType); } if (dbg) @@ -197,22 +197,22 @@ ON_DLL_LOAD_RELIESON("engine.dll", ServerNetHooks, ConVar, (CModule module)) throw std::runtime_error("failed to initialize bcrypt"); if (!VerifyHMACSHA256( - "test", - "\x88\xcd\x21\x08\xb5\x34\x7d\x97\x3c\xf3\x9c\xdf\x90\x53\xd7\xdd\x42\x70\x48\x76\xd8\xc9\xa9\xbd\x8e\x2d\x16\x82\x59\xd3\xdd" - "\xf7", - "test")) + "test", + "\x88\xcd\x21\x08\xb5\x34\x7d\x97\x3c\xf3\x9c\xdf\x90\x53\xd7\xdd\x42\x70\x48\x76\xd8\xc9\xa9\xbd\x8e\x2d\x16\x82\x59\xd3\xdd" + "\xf7", + "test")) throw std::runtime_error("bcrypt HMAC-SHA256 is broken"); Cvar_net_debug_atlas_packet = new ConVar( - "net_debug_atlas_packet", - "0", - FCVAR_NONE, - "Whether to log detailed debugging information for Atlas connectionless packets (warning: this allows unlimited amounts of " - "arbitrary data to be logged)"); + "net_debug_atlas_packet", + "0", + FCVAR_NONE, + "Whether to log detailed debugging information for Atlas connectionless packets (warning: this allows unlimited amounts of " + "arbitrary data to be logged)"); Cvar_net_debug_atlas_packet_insecure = new ConVar( - "net_debug_atlas_packet_insecure", - "0", - FCVAR_NONE, - "Whether to disable signature verification for Atlas connectionless packets (DANGEROUS: this allows anyone to impersonate Atlas)"); + "net_debug_atlas_packet_insecure", + "0", + FCVAR_NONE, + "Whether to disable signature verification for Atlas connectionless packets (DANGEROUS: this allows anyone to impersonate Atlas)"); } diff --git a/NorthstarDLL/server/serverpresence.cpp b/NorthstarDLL/server/serverpresence.cpp index ed9185c1..158d9abd 100644 --- a/NorthstarDLL/server/serverpresence.cpp +++ b/NorthstarDLL/server/serverpresence.cpp @@ -201,10 +201,10 @@ void ServerPresenceManager::SetPlaylist(const char* pPlaylistName) { // update playlist strncpy_s( - m_ServerPresence.m_PlaylistName, - sizeof(m_ServerPresence.m_PlaylistName), - pPlaylistName, - sizeof(m_ServerPresence.m_PlaylistName) - 1); + m_ServerPresence.m_PlaylistName, + sizeof(m_ServerPresence.m_PlaylistName), + pPlaylistName, + sizeof(m_ServerPresence.m_PlaylistName) - 1); // update maxplayers const char* pMaxPlayers = R2::GetCurrentPlaylistVar("max_players", true); diff --git a/NorthstarDLL/shared/exploit_fixes/exploitfixes.cpp b/NorthstarDLL/shared/exploit_fixes/exploitfixes.cpp index 2a0a9c2c..a85e05c4 100644 --- a/NorthstarDLL/shared/exploit_fixes/exploitfixes.cpp +++ b/NorthstarDLL/shared/exploit_fixes/exploitfixes.cpp @@ -15,16 +15,16 @@ ConVar* Cvar_sv_cheats; #define BLOCKED_INFO(s) \ ( \ - [=]() -> bool \ - { \ - if (Cvar_ns_exploitfixes_log->GetBool()) \ - { \ - std::stringstream stream; \ - stream << "ExploitFixes.cpp: " << BLOCK_PREFIX << s; \ - spdlog::error(stream.str()); \ - } \ - return false; \ - }()) + [=]() -> bool \ + { \ + if (Cvar_ns_exploitfixes_log->GetBool()) \ + { \ + std::stringstream stream; \ + stream << "ExploitFixes.cpp: " << BLOCK_PREFIX << s; \ + spdlog::error(stream.str()); \ + } \ + return false; \ + }()) // block bad netmessages // Servers can literally request a screenshot from any client, yeah no @@ -82,7 +82,7 @@ bool, __fastcall, (void* pMsg)) // 48 8B D1 48 8B 49 18 48 8B 01 48 FF 60 10 bool bIsServerFrame = Tier0::ThreadInServerFrameThread(); std::string BLOCK_PREFIX = - std::string {"NET_SetConVar ("} + (bIsServerFrame ? "server" : "client") + "): Blocked dangerous/invalid msg: "; + std::string {"NET_SetConVar ("} + (bIsServerFrame ? "server" : "client") + "): Blocked dangerous/invalid msg: "; if (bIsServerFrame) { @@ -118,14 +118,14 @@ bool, __fastcall, (void* pMsg)) // 48 8B D1 48 8B 49 18 48 8B 01 48 FF 60 10 if (pVar) { memcpy( - entry->name, - pVar->m_ConCommandBase.m_pszName, - strlen(pVar->m_ConCommandBase.m_pszName) + 1); // Force name to match case + entry->name, + pVar->m_ConCommandBase.m_pszName, + strlen(pVar->m_ConCommandBase.m_pszName) + 1); // Force name to match case int iFlags = bIsServerFrame ? FCVAR_USERINFO : FCVAR_REPLICATED; if (!pVar->IsFlagSet(iFlags)) return BLOCKED_INFO( - "Invalid flags (" << std::hex << "0x" << pVar->m_ConCommandBase.m_nFlags << "), var is " << entry->name); + "Invalid flags (" << std::hex << "0x" << pVar->m_ConCommandBase.m_nFlags << "), var is " << entry->name); } } else @@ -214,7 +214,7 @@ void, __fastcall, (void* buf, void* pCmd_move, void* pCmd_from)) // 4C 89 44 24 auto fromCmd = (SV_CUserCmd*)pCmd_from; std::string BLOCK_PREFIX = - "ReadUsercmd (command_number delta: " + std::to_string(cmd->command_number - fromCmd->command_number) + "): "; + "ReadUsercmd (command_number delta: " + std::to_string(cmd->command_number - fromCmd->command_number) + "): "; // fix invalid player angles cmd->worldViewAngles.MakeValid(); @@ -231,8 +231,8 @@ void, __fastcall, (void* buf, void* pCmd_move, void* pCmd_from)) // 4C 89 44 24 if (cmd->frameTime <= 0 || cmd->tick_count == 0 || cmd->command_time <= 0) { BLOCKED_INFO( - "Bogus cmd timing (tick_count: " << cmd->tick_count << ", frameTime: " << cmd->frameTime - << ", commandTime : " << cmd->command_time << ")"); + "Bogus cmd timing (tick_count: " << cmd->tick_count << ", frameTime: " << cmd->frameTime + << ", commandTime : " << cmd->command_time << ")"); goto INVALID_CMD; // No simulation of bogus-timed cmds } @@ -305,14 +305,14 @@ bool, __fastcall, (R2::CBaseClient* self, uint32_t unknown, const char* pCommand if (!Cvar_sv_cheats->GetBool()) { constexpr const char* blockedCommands[] = { - "emit", // Sound-playing exploit (likely for Portal 2 coop devs testing splitscreen sound or something) + "emit", // Sound-playing exploit (likely for Portal 2 coop devs testing splitscreen sound or something) - // These both execute a command for every single entity for some reason, nice one valve - "pre_go_to_hub", - "pre_go_to_calibration", + // These both execute a command for every single entity for some reason, nice one valve + "pre_go_to_hub", + "pre_go_to_calibration", - "end_movie", // Calls "__MovieFinished" script function, not sure exactly what this does but it certainly isn't needed - "load_recent_checkpoint" // This is the instant-respawn exploit, literally just calls RespawnPlayer() + "end_movie", // Calls "__MovieFinished" script function, not sure exactly what this does but it certainly isn't needed + "load_recent_checkpoint" // This is the instant-respawn exploit, literally just calls RespawnPlayer() }; int iCmdLength = strlen(tempCommand.Arg(0)); @@ -348,7 +348,7 @@ void, __fastcall, (void* self)) CBaseClient__SendServerInfo(self); if (!bWasWritingStringTableSuccessful) R2::CBaseClient__Disconnect( - self, 1, "Overflowed CNetworkStringTableContainer::WriteBaselines, try restarting your client and reconnecting"); + self, 1, "Overflowed CNetworkStringTableContainer::WriteBaselines, try restarting your client and reconnecting"); } // return null when GetEntByIndex is passed an index >= 0x4000 @@ -427,9 +427,9 @@ ON_DLL_LOAD_RELIESON("server.dll", ServerExploitFixes, ConVar, (CModule module)) // Dumb ANTITAMPER patches (they negatively impact performance and security) constexpr const char* ANTITAMPER_EXPORTS[] = { - "ANTITAMPER_SPOTCHECK_CODEMARKER", - "ANTITAMPER_TESTVALUE_CODEMARKER", - "ANTITAMPER_TRIGGER_CODEMARKER", + "ANTITAMPER_SPOTCHECK_CODEMARKER", + "ANTITAMPER_TESTVALUE_CODEMARKER", + "ANTITAMPER_TRIGGER_CODEMARKER", }; // Prevent these from actually doing anything @@ -445,9 +445,9 @@ ON_DLL_LOAD_RELIESON("server.dll", ServerExploitFixes, ConVar, (CModule module)) } Cvar_ns_exploitfixes_log = - new ConVar("ns_exploitfixes_log", "1", FCVAR_GAMEDLL, "Whether to log whenever ExploitFixes.cpp blocks/corrects something"); + new ConVar("ns_exploitfixes_log", "1", FCVAR_GAMEDLL, "Whether to log whenever ExploitFixes.cpp blocks/corrects something"); Cvar_ns_should_log_all_clientcommands = - new ConVar("ns_should_log_all_clientcommands", "0", FCVAR_NONE, "Whether to log all clientcommands"); + new ConVar("ns_should_log_all_clientcommands", "0", FCVAR_NONE, "Whether to log all clientcommands"); Cvar_sv_cheats = R2::g_pCVar->FindVar("sv_cheats"); } diff --git a/NorthstarDLL/shared/exploit_fixes/exploitfixes_utf8parser.cpp b/NorthstarDLL/shared/exploit_fixes/exploitfixes_utf8parser.cpp index 3d97f750..d7210bb3 100644 --- a/NorthstarDLL/shared/exploit_fixes/exploitfixes_utf8parser.cpp +++ b/NorthstarDLL/shared/exploit_fixes/exploitfixes_utf8parser.cpp @@ -179,11 +179,11 @@ bool, __fastcall, (INT64* a1, DWORD* a2, char* strData)) // 48 89 5C 24 ? 48 89 // only call if we're parsing utf8 data from the network (i.e. communities), otherwise we get perf issues void* pReturnAddress = #ifdef _MSC_VER - _ReturnAddress() + _ReturnAddress() #else - __builtin_return_address(0) + __builtin_return_address(0) #endif - ; + ; if (pReturnAddress == targetRetAddr && !CheckUTF8Valid(a1, a2, strData)) return false; diff --git a/NorthstarDLL/shared/exploit_fixes/ns_limits.cpp b/NorthstarDLL/shared/exploit_fixes/ns_limits.cpp index c9085cb0..8c169b2a 100644 --- a/NorthstarDLL/shared/exploit_fixes/ns_limits.cpp +++ b/NorthstarDLL/shared/exploit_fixes/ns_limits.cpp @@ -29,7 +29,7 @@ void ServerLimitsManager::RunFrame(double flCurrentTime, float flFrameTime) if (pLimitData->flFrameUserCmdBudget < R2::g_pGlobals->m_flTickInterval * Cvar_sv_antispeedhack_maxtickbudget->GetFloat()) { pLimitData->flFrameUserCmdBudget += g_pServerLimits->Cvar_sv_antispeedhack_budgetincreasemultiplier->GetFloat() * - fmax(flFrameTime, R2::g_pGlobals->m_flFrameTime * CEngineServer__GetTimescale()); + fmax(flFrameTime, R2::g_pGlobals->m_flFrameTime * CEngineServer__GetTimescale()); } } } @@ -40,7 +40,7 @@ void ServerLimitsManager::AddPlayer(R2::CBaseClient* player) { PlayerLimitData limitData; limitData.flFrameUserCmdBudget = - R2::g_pGlobals->m_flTickInterval * CEngineServer__GetTimescale() * Cvar_sv_antispeedhack_maxtickbudget->GetFloat(); + R2::g_pGlobals->m_flTickInterval * CEngineServer__GetTimescale() * Cvar_sv_antispeedhack_maxtickbudget->GetFloat(); m_PlayerLimitData.insert(std::make_pair(player, limitData)); } @@ -116,7 +116,7 @@ char, __fastcall, (void* self, void* buf)) // reset every second if (startTime - g_pServerLimits->m_PlayerLimitData[sender].lastNetChanProcessingLimitStart >= 1.0 || - g_pServerLimits->m_PlayerLimitData[sender].lastNetChanProcessingLimitStart == -1.0) + g_pServerLimits->m_PlayerLimitData[sender].lastNetChanProcessingLimitStart == -1.0) { g_pServerLimits->m_PlayerLimitData[sender].lastNetChanProcessingLimitStart = startTime; g_pServerLimits->m_PlayerLimitData[sender].netChanProcessingLimitTime = 0.0; @@ -124,13 +124,13 @@ char, __fastcall, (void* self, void* buf)) g_pServerLimits->m_PlayerLimitData[sender].netChanProcessingLimitTime += (Tier0::Plat_FloatTime() * 1000) - (startTime * 1000); if (g_pServerLimits->m_PlayerLimitData[sender].netChanProcessingLimitTime >= - g_pServerLimits->Cvar_net_chan_limit_msec_per_sec->GetInt()) + g_pServerLimits->Cvar_net_chan_limit_msec_per_sec->GetInt()) { spdlog::warn( - "Client {} hit netchan processing limit with {}ms of processing time this second (max is {})", - (char*)sender + 0x16, - g_pServerLimits->m_PlayerLimitData[sender].netChanProcessingLimitTime, - g_pServerLimits->Cvar_net_chan_limit_msec_per_sec->GetInt()); + "Client {} hit netchan processing limit with {}ms of processing time this second (max is {})", + (char*)sender + 0x16, + g_pServerLimits->m_PlayerLimitData[sender].netChanProcessingLimitTime, + g_pServerLimits->Cvar_net_chan_limit_msec_per_sec->GetInt()); // never kick local player if (g_pServerLimits->Cvar_net_chan_limit_mode->GetInt() != NETCHANLIMIT_WARN && strcmp(R2::g_pLocalPlayerUserID, sender->m_UID)) @@ -150,7 +150,7 @@ bool ServerLimitsManager::CheckConnectionlessPacketLimits(R2::netpacket_t* packe // don't ratelimit datablock packets as long as datablock is enabled if (packet->adr.type == R2::NA_IP && - (!(packet->data[4] == 'N' && Cvar_net_data_block_enabled->GetBool()) || !Cvar_net_data_block_enabled->GetBool())) + (!(packet->data[4] == 'N' && Cvar_net_data_block_enabled->GetBool()) || !Cvar_net_data_block_enabled->GetBool())) { // bad lookup: optimise later tm UnconnectedPlayerLimitData* sendData = nullptr; @@ -183,9 +183,9 @@ bool ServerLimitsManager::CheckConnectionlessPacketLimits(R2::netpacket_t* packe if (sendData->packetCount >= g_pServerLimits->Cvar_sv_querylimit_per_sec->GetInt()) { spdlog::warn( - "Client went over connectionless ratelimit of {} per sec with packet of type {}", - g_pServerLimits->Cvar_sv_querylimit_per_sec->GetInt(), - packet->data[4]); + "Client went over connectionless ratelimit of {} per sec with packet of type {}", + g_pServerLimits->Cvar_sv_querylimit_per_sec->GetInt(), + packet->data[4]); // timeout for a minute sendData->timeoutEnd = Tier0::Plat_FloatTime() + 60.0; @@ -199,8 +199,8 @@ bool ServerLimitsManager::CheckConnectionlessPacketLimits(R2::netpacket_t* packe // this is weird and i'm not sure if it's correct, so not using for now /*AUTOHOOK(CBasePlayer__PhysicsSimulate, server.dll + 0x5A6E50, bool, __fastcall, (void* self, int a2, char a3)) { - spdlog::info("CBasePlayer::PhysicsSimulate"); - return CBasePlayer__PhysicsSimulate(self, a2, a3); + spdlog::info("CBasePlayer::PhysicsSimulate"); + return CBasePlayer__PhysicsSimulate(self, a2, a3); }*/ struct alignas(4) SV_CUserCmd @@ -263,31 +263,31 @@ ON_DLL_LOAD_RELIESON("engine.dll", ServerLimits, ConVar, (CModule module)) g_pServerLimits = new ServerLimitsManager; g_pServerLimits->CVar_sv_quota_stringcmdspersecond = new ConVar( - "sv_quota_stringcmdspersecond", - "60", - FCVAR_GAMEDLL, - "How many string commands per second clients are allowed to submit, 0 to disallow all string commands, -1 to disable"); + "sv_quota_stringcmdspersecond", + "60", + FCVAR_GAMEDLL, + "How many string commands per second clients are allowed to submit, 0 to disallow all string commands, -1 to disable"); g_pServerLimits->Cvar_net_chan_limit_mode = - new ConVar("net_chan_limit_mode", "0", FCVAR_GAMEDLL, "The mode for netchan processing limits: 0 = warn, 1 = kick"); + new ConVar("net_chan_limit_mode", "0", FCVAR_GAMEDLL, "The mode for netchan processing limits: 0 = warn, 1 = kick"); g_pServerLimits->Cvar_net_chan_limit_msec_per_sec = new ConVar( - "net_chan_limit_msec_per_sec", - "100", - FCVAR_GAMEDLL, - "Netchannel processing is limited to so many milliseconds, abort connection if exceeding budget"); + "net_chan_limit_msec_per_sec", + "100", + FCVAR_GAMEDLL, + "Netchannel processing is limited to so many milliseconds, abort connection if exceeding budget"); g_pServerLimits->Cvar_sv_querylimit_per_sec = new ConVar("sv_querylimit_per_sec", "15", FCVAR_GAMEDLL, ""); g_pServerLimits->Cvar_sv_max_chat_messages_per_sec = new ConVar("sv_max_chat_messages_per_sec", "5", FCVAR_GAMEDLL, ""); g_pServerLimits->Cvar_sv_antispeedhack_enable = - new ConVar("sv_antispeedhack_enable", "0", FCVAR_NONE, "whether to enable antispeedhack protections"); + new ConVar("sv_antispeedhack_enable", "0", FCVAR_NONE, "whether to enable antispeedhack protections"); g_pServerLimits->Cvar_sv_antispeedhack_maxtickbudget = new ConVar( - "sv_antispeedhack_maxtickbudget", - "64", - FCVAR_GAMEDLL, - "Maximum number of client-issued usercmd ticks that can be replayed in packet loss conditions"); + "sv_antispeedhack_maxtickbudget", + "64", + FCVAR_GAMEDLL, + "Maximum number of client-issued usercmd ticks that can be replayed in packet loss conditions"); g_pServerLimits->Cvar_sv_antispeedhack_budgetincreasemultiplier = new ConVar( - "sv_antispeedhack_budgetincreasemultiplier", - "1", - FCVAR_GAMEDLL, - "Increase usercmd processing budget by tickinterval * value per tick"); + "sv_antispeedhack_budgetincreasemultiplier", + "1", + FCVAR_GAMEDLL, + "Increase usercmd processing budget by tickinterval * value per tick"); CEngineServer__GetTimescale = module.Offset(0x240840).RCast<float (*)()>(); } diff --git a/NorthstarDLL/shared/keyvalues.cpp b/NorthstarDLL/shared/keyvalues.cpp index aa22ca65..da180ce2 100644 --- a/NorthstarDLL/shared/keyvalues.cpp +++ b/NorthstarDLL/shared/keyvalues.cpp @@ -25,7 +25,7 @@ struct CKeyValuesSystem const char* (*GetStringForSymbol)(CKeyValuesSystem* self, HKeySymbol symbol); char pad1[8 * 5]; HKeySymbol (*GetSymbolForStringCaseSensitive)( - CKeyValuesSystem* self, HKeySymbol& hCaseInsensitiveSymbol, const char* name, bool bCreate); + CKeyValuesSystem* self, HKeySymbol& hCaseInsensitiveSymbol, const char* name, bool bCreate); }; const __VTable* m_pVtable; @@ -95,7 +95,7 @@ KeyValues::KeyValues(const char* pszSetName, const char* pszFirstKey, int iFirst // *pszSecondValue - //----------------------------------------------------------------------------- KeyValues::KeyValues( - const char* pszSetName, const char* pszFirstKey, const char* pszFirstValue, const char* pszSecondKey, const char* pszSecondValue) + const char* pszSetName, const char* pszFirstKey, const char* pszFirstValue, const char* pszSecondKey, const char* pszSecondValue) { Init(); SetName(pszSetName); @@ -585,7 +585,7 @@ KeyValues* KeyValues::GetNextKey() const const char* KeyValues::GetName(void) const { return KeyValuesSystem()->m_pVtable->GetStringForSymbol( - KeyValuesSystem(), MAKE_3_BYTES_FROM_1_AND_2(m_iKeyNameCaseSensitive1, m_iKeyNameCaseSensitive2)); + KeyValuesSystem(), MAKE_3_BYTES_FROM_1_AND_2(m_iKeyNameCaseSensitive1, m_iKeyNameCaseSensitive2)); } //----------------------------------------------------------------------------- @@ -974,7 +974,7 @@ void KeyValues::SetName(const char* pszSetName) { HKeySymbol hCaseSensitiveKeyName = INVALID_KEY_SYMBOL, hCaseInsensitiveKeyName = INVALID_KEY_SYMBOL; hCaseSensitiveKeyName = - KeyValuesSystem()->m_pVtable->GetSymbolForStringCaseSensitive(KeyValuesSystem(), hCaseInsensitiveKeyName, pszSetName, false); + KeyValuesSystem()->m_pVtable->GetSymbolForStringCaseSensitive(KeyValuesSystem(), hCaseInsensitiveKeyName, pszSetName, false); m_iKeyName = hCaseInsensitiveKeyName; SPLIT_3_BYTES_INTO_1_AND_2(m_iKeyNameCaseSensitive1, m_iKeyNameCaseSensitive2, hCaseSensitiveKeyName); diff --git a/NorthstarDLL/shared/keyvalues.h b/NorthstarDLL/shared/keyvalues.h index 64ca0cc7..e40e8cfa 100644 --- a/NorthstarDLL/shared/keyvalues.h +++ b/NorthstarDLL/shared/keyvalues.h @@ -58,7 +58,7 @@ class KeyValues KeyValues(const char* pszSetName, const char* pszFirstKey, const wchar_t* pwszFirstValue); KeyValues(const char* pszSetName, const char* pszFirstKey, int iFirstValue); KeyValues( - const char* pszSetName, const char* pszFirstKey, const char* pszFirstValue, const char* pszSecondKey, const char* pszSecondValue); + const char* pszSetName, const char* pszFirstKey, const char* pszFirstValue, const char* pszSecondKey, const char* pszSecondValue); KeyValues(const char* pszSetName, const char* pszFirstKey, int iFirstValue, const char* pszSecondKey, int iSecondValue); ~KeyValues(void); diff --git a/NorthstarDLL/shared/maxplayers.cpp b/NorthstarDLL/shared/maxplayers.cpp index b2a09578..4bab54cc 100644 --- a/NorthstarDLL/shared/maxplayers.cpp +++ b/NorthstarDLL/shared/maxplayers.cpp @@ -114,10 +114,10 @@ ON_DLL_LOAD("engine.dll", MaxPlayersOverride_Engine, (CModule module)) // patch max players in userinfo stringtable creation /*{ - int maxPlayersPowerOf2 = 1; - while (maxPlayersPowerOf2 < NEW_MAX_PLAYERS) - maxPlayersPowerOf2 <<= 1; - ChangeOffset<unsigned char>((char*)baseAddress + 0x114B79 + 3, maxPlayersPowerOf2); // original: 32 + int maxPlayersPowerOf2 = 1; + while (maxPlayersPowerOf2 < NEW_MAX_PLAYERS) + maxPlayersPowerOf2 <<= 1; + ChangeOffset<unsigned char>((char*)baseAddress + 0x114B79 + 3, maxPlayersPowerOf2); // original: 32 }*/ // this is not supposed to work at all but it does on 64 players (how) // proper fix below @@ -184,9 +184,9 @@ void,, (bool a1, float a2)) v3 = *(unsigned char*)(g_pGlobals + 73); if (*(DWORD*)(qword_1814D9648 + 92) && - ((*(unsigned __int8(__fastcall**)(__int64))(*(__int64*)g_pEngineServer + 32))(g_pEngineServer) || - !*(DWORD*)(qword_1814DA408 + 92)) && - v3) + ((*(unsigned __int8(__fastcall**)(__int64))(*(__int64*)g_pEngineServer + 32))(g_pEngineServer) || + !*(DWORD*)(qword_1814DA408 + 92)) && + v3) { globals = g_pGlobals; v5 = 1; @@ -482,11 +482,11 @@ ON_DLL_LOAD("client.dll", MaxPlayersOverride_Client, (CModule module)) // C_PlayerResource::C_PlayerResource - change m_szName address ChangeOffset<unsigned int>( - module.Offset(0x1640D0 + 3), C_PlayerResource_OriginalSize + PlayerResource_Name_Start); // appended to the end of the class + module.Offset(0x1640D0 + 3), C_PlayerResource_OriginalSize + PlayerResource_Name_Start); // appended to the end of the class // C_PlayerResource::C_PlayerResource - change m_szName address ChangeOffset<unsigned int>( - module.Offset(0x1640D0 + 3), C_PlayerResource_OriginalSize + PlayerResource_Name_Start); // appended to the end of the class + module.Offset(0x1640D0 + 3), C_PlayerResource_OriginalSize + PlayerResource_Name_Start); // appended to the end of the class // C_PlayerResource::C_PlayerResource - increase memset length to clean newly allocated data ChangeOffset<unsigned int>(module.Offset(0x1640D0 + 3), 2244 + C_PlayerResource_AddedSize); diff --git a/NorthstarDLL/shared/misccommands.cpp b/NorthstarDLL/shared/misccommands.cpp index 5d9ced99..ae3903bd 100644 --- a/NorthstarDLL/shared/misccommands.cpp +++ b/NorthstarDLL/shared/misccommands.cpp @@ -113,30 +113,30 @@ void ConCommand_cvar_reset(const CCommand& arg) void AddMiscConCommands() { RegisterConCommand( - "force_newgame", - ConCommand_force_newgame, - "forces a map load through directly setting g_pHostState->m_iNextState to HS_NEW_GAME", - FCVAR_NONE); + "force_newgame", + ConCommand_force_newgame, + "forces a map load through directly setting g_pHostState->m_iNextState to HS_NEW_GAME", + FCVAR_NONE); RegisterConCommand( - "ns_start_reauth_and_leave_to_lobby", - ConCommand_ns_start_reauth_and_leave_to_lobby, - "called by the server, used to reauth and return the player to lobby when leaving a game", - FCVAR_SERVER_CAN_EXECUTE); + "ns_start_reauth_and_leave_to_lobby", + ConCommand_ns_start_reauth_and_leave_to_lobby, + "called by the server, used to reauth and return the player to lobby when leaving a game", + FCVAR_SERVER_CAN_EXECUTE); // this is a concommand because we make a deferred call to it from another thread RegisterConCommand("ns_end_reauth_and_leave_to_lobby", ConCommand_ns_end_reauth_and_leave_to_lobby, "", FCVAR_NONE); RegisterConCommand( - "cvar_setdefaultvalue", - ConCommand_cvar_setdefaultvalue, - "overwrites the default value of a cvar, for use with script and cvar_reset", - FCVAR_NONE); + "cvar_setdefaultvalue", + ConCommand_cvar_setdefaultvalue, + "overwrites the default value of a cvar, for use with script and cvar_reset", + FCVAR_NONE); RegisterConCommand( - "cvar_setvalueanddefaultvalue", - ConCommand_cvar_setvalueanddefaultvalue, - "overwrites the current value and default value of a cvar, for use with script and cvar_reset", - FCVAR_NONE); + "cvar_setvalueanddefaultvalue", + ConCommand_cvar_setvalueanddefaultvalue, + "overwrites the current value and default value of a cvar, for use with script and cvar_reset", + FCVAR_NONE); RegisterConCommand("cvar_reset", ConCommand_cvar_reset, "resets a cvar's value to its default value", FCVAR_NONE); } @@ -184,185 +184,185 @@ void FixupCvarFlags() // array of cvars and the flags we want to add to them const std::vector<std::tuple<const char*, uint32_t>> CVAR_FIXUP_ADD_FLAGS = { - // system commands (i.e. necessary for proper functionality) - // servers need to be able to disconnect - {"disconnect", FCVAR_SERVER_CAN_EXECUTE}, - - // cheat commands - {"give", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"give_server", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"givecurrentammo", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"takecurrentammo", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - - {"switchclass", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"set", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"_setClassVarServer", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - - {"ent_create", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"ent_throw", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"ent_setname", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"ent_teleport", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"ent_remove", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"ent_remove_all", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"ent_fire", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - - {"particle_create", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"particle_recreate", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"particle_kill", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - - {"test_setteam", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"melee_lunge_ent", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - - // fcvars that should be cheats - {"net_ignoreAllSnapshots", FCVAR_CHEAT}, - {"highlight_draw", FCVAR_CHEAT}, - // these should potentially be replicated rather than cheat, like sv_footsteps is - // however they're defined on client, so can't make replicated atm sadly - {"cl_footstep_event_max_dist", FCVAR_CHEAT}, - {"cl_footstep_event_max_dist_titan", FCVAR_CHEAT}, + // system commands (i.e. necessary for proper functionality) + // servers need to be able to disconnect + {"disconnect", FCVAR_SERVER_CAN_EXECUTE}, + + // cheat commands + {"give", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"give_server", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"givecurrentammo", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"takecurrentammo", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + + {"switchclass", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"set", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"_setClassVarServer", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + + {"ent_create", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"ent_throw", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"ent_setname", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"ent_teleport", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"ent_remove", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"ent_remove_all", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"ent_fire", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + + {"particle_create", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"particle_recreate", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"particle_kill", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + + {"test_setteam", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"melee_lunge_ent", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + + // fcvars that should be cheats + {"net_ignoreAllSnapshots", FCVAR_CHEAT}, + {"highlight_draw", FCVAR_CHEAT}, + // these should potentially be replicated rather than cheat, like sv_footsteps is + // however they're defined on client, so can't make replicated atm sadly + {"cl_footstep_event_max_dist", FCVAR_CHEAT}, + {"cl_footstep_event_max_dist_titan", FCVAR_CHEAT}, }; // array of cvars and the flags we want to remove from them const std::vector<std::tuple<const char*, uint32_t>> CVAR_FIXUP_REMOVE_FLAGS = { - // unsure how this command works, not even sure it's used on retail servers, deffo shouldn't be used on northstar - {"migrateme", FCVAR_SERVER_CAN_EXECUTE | FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"recheck", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, // we don't need this on northstar servers, it's for communities - - // unsure how these work exactly (rpt system likely somewhat stripped?), removing anyway since they won't be used - {"rpt_client_enable", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - {"rpt_password", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, - - // these are devonly by default but should be modifyable - // NOTE: not all of these may actually do anything or work properly in practice - // network settings - {"cl_updaterate_mp", FCVAR_DEVELOPMENTONLY}, - {"cl_updaterate_sp", FCVAR_DEVELOPMENTONLY}, - {"clock_bias_sp", FCVAR_DEVELOPMENTONLY}, - {"clock_bias_mp", FCVAR_DEVELOPMENTONLY}, - {"cl_interpolate", FCVAR_DEVELOPMENTONLY}, // super duper ultra fucks anims if changed - {"cl_interpolateSoAllAnimsLoop", FCVAR_DEVELOPMENTONLY}, - {"cl_cmdrate", FCVAR_DEVELOPMENTONLY}, - {"cl_cmdbackup", FCVAR_DEVELOPMENTONLY}, - {"rate", FCVAR_DEVELOPMENTONLY}, - {"net_minroutable", FCVAR_DEVELOPMENTONLY}, - {"net_maxroutable", FCVAR_DEVELOPMENTONLY}, - {"net_lerpFields", FCVAR_DEVELOPMENTONLY}, - {"net_ignoreAllSnapshots", FCVAR_DEVELOPMENTONLY}, - {"net_chokeloop", FCVAR_DEVELOPMENTONLY}, - {"sv_unlag", FCVAR_DEVELOPMENTONLY}, - {"sv_maxunlag", FCVAR_DEVELOPMENTONLY}, - {"sv_lagpushticks", FCVAR_DEVELOPMENTONLY}, - {"sv_instancebaselines", FCVAR_DEVELOPMENTONLY}, - {"sv_voiceEcho", FCVAR_DEVELOPMENTONLY}, - {"net_compresspackets", FCVAR_DEVELOPMENTONLY}, - {"net_compresspackets_minsize", FCVAR_DEVELOPMENTONLY}, - {"net_verifyEncryption", FCVAR_DEVELOPMENTONLY}, // unsure if functional in retail - - // gameplay settings - {"vel_samples", FCVAR_DEVELOPMENTONLY}, - {"vel_sampleFrequency", FCVAR_DEVELOPMENTONLY}, - {"sv_friction", FCVAR_DEVELOPMENTONLY}, - {"sv_stopspeed", FCVAR_DEVELOPMENTONLY}, - {"sv_airaccelerate", FCVAR_DEVELOPMENTONLY}, - {"sv_forceGrapplesToFail", FCVAR_DEVELOPMENTONLY}, - {"sv_maxvelocity", FCVAR_DEVELOPMENTONLY}, - {"sv_footsteps", FCVAR_DEVELOPMENTONLY}, - // these 2 are flagged as CHEAT above, could be made REPLICATED later potentially - {"cl_footstep_event_max_dist", FCVAR_DEVELOPMENTONLY}, - {"cl_footstep_event_max_dist_titan", FCVAR_DEVELOPMENTONLY}, - {"sv_balanceTeams", FCVAR_DEVELOPMENTONLY}, - {"rodeo_enable", FCVAR_DEVELOPMENTONLY}, - {"sv_forceRodeoToFail", FCVAR_DEVELOPMENTONLY}, - {"player_find_rodeo_target_per_cmd", FCVAR_DEVELOPMENTONLY}, // todo test before merge - {"hud_takesshots", FCVAR_DEVELOPMENTONLY}, // very likely does not work but would be cool if it did - - {"cam_collision", FCVAR_DEVELOPMENTONLY}, - {"cam_idealdelta", FCVAR_DEVELOPMENTONLY}, - {"cam_ideallag", FCVAR_DEVELOPMENTONLY}, - - // graphics/visual settings - {"mat_colorcorrection", FCVAR_DEVELOPMENTONLY}, - {"r_hbaoRadius", FCVAR_DEVELOPMENTONLY}, - {"r_hbaoDepthMax", FCVAR_DEVELOPMENTONLY}, - {"r_hbaoBlurSharpness", FCVAR_DEVELOPMENTONLY}, - {"r_hbaoIntensity", FCVAR_DEVELOPMENTONLY}, - {"r_hbaoBias", FCVAR_DEVELOPMENTONLY}, - {"r_hbaoDistanceLerp", FCVAR_DEVELOPMENTONLY}, - {"r_hbaoBlurRadius", FCVAR_DEVELOPMENTONLY}, - {"r_hbaoExponent", FCVAR_DEVELOPMENTONLY}, - {"r_hbaoDepthFadePctDefault", FCVAR_DEVELOPMENTONLY}, - {"r_drawscreenspaceparticles", FCVAR_DEVELOPMENTONLY}, - {"ui_loadingscreen_fadeout_time", FCVAR_DEVELOPMENTONLY}, - {"ui_loadingscreen_fadein_time", FCVAR_DEVELOPMENTONLY}, - {"ui_loadingscreen_transition_time", FCVAR_DEVELOPMENTONLY}, - {"ui_loadingscreen_mintransition_time", FCVAR_DEVELOPMENTONLY}, - // these 2 could be FCVAR_CHEAT, i guess? - {"cl_draw_player_model", FCVAR_DEVELOPMENTONLY}, - {"cl_always_draw_3p_player", FCVAR_DEVELOPMENTONLY}, - {"idcolor_neutral", FCVAR_DEVELOPMENTONLY}, - {"idcolor_ally", FCVAR_DEVELOPMENTONLY}, - {"idcolor_ally_cb1", FCVAR_DEVELOPMENTONLY}, - {"idcolor_ally_cb2", FCVAR_DEVELOPMENTONLY}, - {"idcolor_ally_cb3", FCVAR_DEVELOPMENTONLY}, - {"idcolor_enemy", FCVAR_DEVELOPMENTONLY}, - {"idcolor_enemy_cb1", FCVAR_DEVELOPMENTONLY}, - {"idcolor_enemy_cb2", FCVAR_DEVELOPMENTONLY}, - {"idcolor_enemy_cb3", FCVAR_DEVELOPMENTONLY}, - {"playerListPartyColorR", FCVAR_DEVELOPMENTONLY}, - {"playerListPartyColorG", FCVAR_DEVELOPMENTONLY}, - {"playerListPartyColorB", FCVAR_DEVELOPMENTONLY}, - {"playerListUseFriendColor", FCVAR_DEVELOPMENTONLY}, - {"fx_impact_neutral", FCVAR_DEVELOPMENTONLY}, - {"fx_impact_ally", FCVAR_DEVELOPMENTONLY}, - {"fx_impact_enemy", FCVAR_DEVELOPMENTONLY}, - {"hitch_alert_color", FCVAR_DEVELOPMENTONLY}, - {"particles_cull_all", FCVAR_DEVELOPMENTONLY}, - {"particles_cull_dlights", FCVAR_DEVELOPMENTONLY}, - {"map_settings_override", FCVAR_DEVELOPMENTONLY}, - {"highlight_draw", FCVAR_DEVELOPMENTONLY}, - - // sys/engine settings - {"sleep_when_meeting_framerate", FCVAR_DEVELOPMENTONLY}, - {"sleep_when_meeting_framerate_headroom_ms", FCVAR_DEVELOPMENTONLY}, - {"not_focus_sleep", FCVAR_DEVELOPMENTONLY}, - {"sp_not_focus_pause", FCVAR_DEVELOPMENTONLY}, - {"joy_requireFocus", FCVAR_DEVELOPMENTONLY}, - - {"host_thread_mode", FCVAR_DEVELOPMENTONLY}, - {"phys_enable_simd_optimizations", FCVAR_DEVELOPMENTONLY}, - {"phys_enable_experimental_optimizations", FCVAR_DEVELOPMENTONLY}, - - {"community_frame_run", FCVAR_DEVELOPMENTONLY}, - {"sv_single_core_dedi", FCVAR_DEVELOPMENTONLY}, - {"sv_stressbots", FCVAR_DEVELOPMENTONLY}, - - {"fatal_script_errors", FCVAR_DEVELOPMENTONLY}, - {"fatal_script_errors_client", FCVAR_DEVELOPMENTONLY}, - {"fatal_script_errors_server", FCVAR_DEVELOPMENTONLY}, - {"script_error_on_midgame_load", FCVAR_DEVELOPMENTONLY}, // idk what this is - - {"ai_ainRebuildOnMapStart", FCVAR_DEVELOPMENTONLY}, - - {"save_enable", FCVAR_DEVELOPMENTONLY}, - - // cheat commands - {"switchclass", FCVAR_DEVELOPMENTONLY}, - {"set", FCVAR_DEVELOPMENTONLY}, - {"_setClassVarServer", FCVAR_DEVELOPMENTONLY}, - - // reparse commands - {"aisettings_reparse", FCVAR_DEVELOPMENTONLY}, - {"aisettings_reparse_client", FCVAR_DEVELOPMENTONLY}, - {"damagedefs_reparse", FCVAR_DEVELOPMENTONLY}, - {"damagedefs_reparse_client", FCVAR_DEVELOPMENTONLY}, - {"playerSettings_reparse", FCVAR_DEVELOPMENTONLY}, - {"_playerSettings_reparse_Server", FCVAR_DEVELOPMENTONLY}, + // unsure how this command works, not even sure it's used on retail servers, deffo shouldn't be used on northstar + {"migrateme", FCVAR_SERVER_CAN_EXECUTE | FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"recheck", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, // we don't need this on northstar servers, it's for communities + + // unsure how these work exactly (rpt system likely somewhat stripped?), removing anyway since they won't be used + {"rpt_client_enable", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + {"rpt_password", FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS}, + + // these are devonly by default but should be modifyable + // NOTE: not all of these may actually do anything or work properly in practice + // network settings + {"cl_updaterate_mp", FCVAR_DEVELOPMENTONLY}, + {"cl_updaterate_sp", FCVAR_DEVELOPMENTONLY}, + {"clock_bias_sp", FCVAR_DEVELOPMENTONLY}, + {"clock_bias_mp", FCVAR_DEVELOPMENTONLY}, + {"cl_interpolate", FCVAR_DEVELOPMENTONLY}, // super duper ultra fucks anims if changed + {"cl_interpolateSoAllAnimsLoop", FCVAR_DEVELOPMENTONLY}, + {"cl_cmdrate", FCVAR_DEVELOPMENTONLY}, + {"cl_cmdbackup", FCVAR_DEVELOPMENTONLY}, + {"rate", FCVAR_DEVELOPMENTONLY}, + {"net_minroutable", FCVAR_DEVELOPMENTONLY}, + {"net_maxroutable", FCVAR_DEVELOPMENTONLY}, + {"net_lerpFields", FCVAR_DEVELOPMENTONLY}, + {"net_ignoreAllSnapshots", FCVAR_DEVELOPMENTONLY}, + {"net_chokeloop", FCVAR_DEVELOPMENTONLY}, + {"sv_unlag", FCVAR_DEVELOPMENTONLY}, + {"sv_maxunlag", FCVAR_DEVELOPMENTONLY}, + {"sv_lagpushticks", FCVAR_DEVELOPMENTONLY}, + {"sv_instancebaselines", FCVAR_DEVELOPMENTONLY}, + {"sv_voiceEcho", FCVAR_DEVELOPMENTONLY}, + {"net_compresspackets", FCVAR_DEVELOPMENTONLY}, + {"net_compresspackets_minsize", FCVAR_DEVELOPMENTONLY}, + {"net_verifyEncryption", FCVAR_DEVELOPMENTONLY}, // unsure if functional in retail + + // gameplay settings + {"vel_samples", FCVAR_DEVELOPMENTONLY}, + {"vel_sampleFrequency", FCVAR_DEVELOPMENTONLY}, + {"sv_friction", FCVAR_DEVELOPMENTONLY}, + {"sv_stopspeed", FCVAR_DEVELOPMENTONLY}, + {"sv_airaccelerate", FCVAR_DEVELOPMENTONLY}, + {"sv_forceGrapplesToFail", FCVAR_DEVELOPMENTONLY}, + {"sv_maxvelocity", FCVAR_DEVELOPMENTONLY}, + {"sv_footsteps", FCVAR_DEVELOPMENTONLY}, + // these 2 are flagged as CHEAT above, could be made REPLICATED later potentially + {"cl_footstep_event_max_dist", FCVAR_DEVELOPMENTONLY}, + {"cl_footstep_event_max_dist_titan", FCVAR_DEVELOPMENTONLY}, + {"sv_balanceTeams", FCVAR_DEVELOPMENTONLY}, + {"rodeo_enable", FCVAR_DEVELOPMENTONLY}, + {"sv_forceRodeoToFail", FCVAR_DEVELOPMENTONLY}, + {"player_find_rodeo_target_per_cmd", FCVAR_DEVELOPMENTONLY}, // todo test before merge + {"hud_takesshots", FCVAR_DEVELOPMENTONLY}, // very likely does not work but would be cool if it did + + {"cam_collision", FCVAR_DEVELOPMENTONLY}, + {"cam_idealdelta", FCVAR_DEVELOPMENTONLY}, + {"cam_ideallag", FCVAR_DEVELOPMENTONLY}, + + // graphics/visual settings + {"mat_colorcorrection", FCVAR_DEVELOPMENTONLY}, + {"r_hbaoRadius", FCVAR_DEVELOPMENTONLY}, + {"r_hbaoDepthMax", FCVAR_DEVELOPMENTONLY}, + {"r_hbaoBlurSharpness", FCVAR_DEVELOPMENTONLY}, + {"r_hbaoIntensity", FCVAR_DEVELOPMENTONLY}, + {"r_hbaoBias", FCVAR_DEVELOPMENTONLY}, + {"r_hbaoDistanceLerp", FCVAR_DEVELOPMENTONLY}, + {"r_hbaoBlurRadius", FCVAR_DEVELOPMENTONLY}, + {"r_hbaoExponent", FCVAR_DEVELOPMENTONLY}, + {"r_hbaoDepthFadePctDefault", FCVAR_DEVELOPMENTONLY}, + {"r_drawscreenspaceparticles", FCVAR_DEVELOPMENTONLY}, + {"ui_loadingscreen_fadeout_time", FCVAR_DEVELOPMENTONLY}, + {"ui_loadingscreen_fadein_time", FCVAR_DEVELOPMENTONLY}, + {"ui_loadingscreen_transition_time", FCVAR_DEVELOPMENTONLY}, + {"ui_loadingscreen_mintransition_time", FCVAR_DEVELOPMENTONLY}, + // these 2 could be FCVAR_CHEAT, i guess? + {"cl_draw_player_model", FCVAR_DEVELOPMENTONLY}, + {"cl_always_draw_3p_player", FCVAR_DEVELOPMENTONLY}, + {"idcolor_neutral", FCVAR_DEVELOPMENTONLY}, + {"idcolor_ally", FCVAR_DEVELOPMENTONLY}, + {"idcolor_ally_cb1", FCVAR_DEVELOPMENTONLY}, + {"idcolor_ally_cb2", FCVAR_DEVELOPMENTONLY}, + {"idcolor_ally_cb3", FCVAR_DEVELOPMENTONLY}, + {"idcolor_enemy", FCVAR_DEVELOPMENTONLY}, + {"idcolor_enemy_cb1", FCVAR_DEVELOPMENTONLY}, + {"idcolor_enemy_cb2", FCVAR_DEVELOPMENTONLY}, + {"idcolor_enemy_cb3", FCVAR_DEVELOPMENTONLY}, + {"playerListPartyColorR", FCVAR_DEVELOPMENTONLY}, + {"playerListPartyColorG", FCVAR_DEVELOPMENTONLY}, + {"playerListPartyColorB", FCVAR_DEVELOPMENTONLY}, + {"playerListUseFriendColor", FCVAR_DEVELOPMENTONLY}, + {"fx_impact_neutral", FCVAR_DEVELOPMENTONLY}, + {"fx_impact_ally", FCVAR_DEVELOPMENTONLY}, + {"fx_impact_enemy", FCVAR_DEVELOPMENTONLY}, + {"hitch_alert_color", FCVAR_DEVELOPMENTONLY}, + {"particles_cull_all", FCVAR_DEVELOPMENTONLY}, + {"particles_cull_dlights", FCVAR_DEVELOPMENTONLY}, + {"map_settings_override", FCVAR_DEVELOPMENTONLY}, + {"highlight_draw", FCVAR_DEVELOPMENTONLY}, + + // sys/engine settings + {"sleep_when_meeting_framerate", FCVAR_DEVELOPMENTONLY}, + {"sleep_when_meeting_framerate_headroom_ms", FCVAR_DEVELOPMENTONLY}, + {"not_focus_sleep", FCVAR_DEVELOPMENTONLY}, + {"sp_not_focus_pause", FCVAR_DEVELOPMENTONLY}, + {"joy_requireFocus", FCVAR_DEVELOPMENTONLY}, + + {"host_thread_mode", FCVAR_DEVELOPMENTONLY}, + {"phys_enable_simd_optimizations", FCVAR_DEVELOPMENTONLY}, + {"phys_enable_experimental_optimizations", FCVAR_DEVELOPMENTONLY}, + + {"community_frame_run", FCVAR_DEVELOPMENTONLY}, + {"sv_single_core_dedi", FCVAR_DEVELOPMENTONLY}, + {"sv_stressbots", FCVAR_DEVELOPMENTONLY}, + + {"fatal_script_errors", FCVAR_DEVELOPMENTONLY}, + {"fatal_script_errors_client", FCVAR_DEVELOPMENTONLY}, + {"fatal_script_errors_server", FCVAR_DEVELOPMENTONLY}, + {"script_error_on_midgame_load", FCVAR_DEVELOPMENTONLY}, // idk what this is + + {"ai_ainRebuildOnMapStart", FCVAR_DEVELOPMENTONLY}, + + {"save_enable", FCVAR_DEVELOPMENTONLY}, + + // cheat commands + {"switchclass", FCVAR_DEVELOPMENTONLY}, + {"set", FCVAR_DEVELOPMENTONLY}, + {"_setClassVarServer", FCVAR_DEVELOPMENTONLY}, + + // reparse commands + {"aisettings_reparse", FCVAR_DEVELOPMENTONLY}, + {"aisettings_reparse_client", FCVAR_DEVELOPMENTONLY}, + {"damagedefs_reparse", FCVAR_DEVELOPMENTONLY}, + {"damagedefs_reparse_client", FCVAR_DEVELOPMENTONLY}, + {"playerSettings_reparse", FCVAR_DEVELOPMENTONLY}, + {"_playerSettings_reparse_Server", FCVAR_DEVELOPMENTONLY}, }; const std::vector<std::tuple<const char*, const char*>> CVAR_FIXUP_DEFAULT_VALUES = { - {"sv_stressbots", "0"}, // not currently used but this is probably a bad default if we get bots working - {"cl_pred_optimize", "0"} // fixes issues with animation prediction in thirdperson + {"sv_stressbots", "0"}, // not currently used but this is probably a bad default if we get bots working + {"cl_pred_optimize", "0"} // fixes issues with animation prediction in thirdperson }; for (auto& fixup : CVAR_FIXUP_ADD_FLAGS) diff --git a/NorthstarDLL/shared/playlist.cpp b/NorthstarDLL/shared/playlist.cpp index ab7aab22..8967cae3 100644 --- a/NorthstarDLL/shared/playlist.cpp +++ b/NorthstarDLL/shared/playlist.cpp @@ -26,7 +26,7 @@ char, __fastcall, (void* a1, void* a2)) { // the private_match playlist on mp_lobby is the only situation where there should be any legitimate sending of this netmessage if (!Cvar_ns_use_clc_SetPlaylistVarOverride->GetBool() || strcmp(R2::GetCurrentPlaylistName(), "private_match") || - strcmp(R2::g_pGlobals->m_pMapName, "mp_lobby")) + strcmp(R2::g_pGlobals->m_pMapName, "mp_lobby")) return 1; return clc_SetPlaylistVarOverride__Process(a1, a2); @@ -114,7 +114,7 @@ ON_DLL_LOAD_RELIESON("engine.dll", PlaylistHooks, (ConCommand, ConVar), (CModule // disabled altogether, since the custom menus won't use it anyway this should only really be accepted if you want vanilla client // compatibility Cvar_ns_use_clc_SetPlaylistVarOverride = new ConVar( - "ns_use_clc_SetPlaylistVarOverride", "0", FCVAR_GAMEDLL, "Whether the server should accept clc_SetPlaylistVarOverride messages"); + "ns_use_clc_SetPlaylistVarOverride", "0", FCVAR_GAMEDLL, "Whether the server should accept clc_SetPlaylistVarOverride messages"); // patch to prevent clc_SetPlaylistVarOverride from being able to crash servers if we reach max overrides due to a call to Error (why is // this possible respawn, wtf) todo: add a warning for this diff --git a/NorthstarDLL/squirrel/squirrel.cpp b/NorthstarDLL/squirrel/squirrel.cpp index 0ee04508..cc1b53a4 100644 --- a/NorthstarDLL/squirrel/squirrel.cpp +++ b/NorthstarDLL/squirrel/squirrel.cpp @@ -75,15 +75,15 @@ const char* GetContextName_Short(ScriptContext context) eSQReturnType SQReturnTypeFromString(const char* pReturnType) { static const std::map<std::string, eSQReturnType> sqReturnTypeNameToString = { - {"bool", eSQReturnType::Boolean}, - {"float", eSQReturnType::Float}, - {"vector", eSQReturnType::Vector}, - {"int", eSQReturnType::Integer}, - {"entity", eSQReturnType::Entity}, - {"string", eSQReturnType::String}, - {"array", eSQReturnType::Arrays}, - {"asset", eSQReturnType::Asset}, - {"table", eSQReturnType::Table}}; + {"bool", eSQReturnType::Boolean}, + {"float", eSQReturnType::Float}, + {"vector", eSQReturnType::Vector}, + {"int", eSQReturnType::Integer}, + {"entity", eSQReturnType::Entity}, + {"string", eSQReturnType::String}, + {"array", eSQReturnType::Arrays}, + {"asset", eSQReturnType::Asset}, + {"table", eSQReturnType::Table}}; if (sqReturnTypeNameToString.find(pReturnType) != sqReturnTypeNameToString.end()) return sqReturnTypeNameToString.at(pReturnType); @@ -320,7 +320,7 @@ template <ScriptContext context> void SquirrelManager<context>::ExecuteCode(cons } template <ScriptContext context> void SquirrelManager<context>::AddFuncRegistration( - std::string returnType, std::string name, std::string argTypes, std::string helpText, SQFunction func) + std::string returnType, std::string name, std::string argTypes, std::string helpText, SQFunction func) { SQFuncRegistration* reg = new SQFuncRegistration; @@ -480,10 +480,10 @@ void __fastcall ScriptCompileErrorHook(HSquirrelVM* sqvm, const char* error, con else { R2::Cbuf_AddText( - R2::Cbuf_GetCurrentPlayer(), - fmt::format("disconnect \"Encountered {} script compilation error, see console for details.\"", GetContextName(realContext)) - .c_str(), - R2::cmd_source_t::kCommandSrcCode); + R2::Cbuf_GetCurrentPlayer(), + fmt::format("disconnect \"Encountered {} script compilation error, see console for details.\"", GetContextName(realContext)) + .c_str(), + R2::cmd_source_t::kCommandSrcCode); // likely temp: show console so user can see any errors, as error message wont display if ui is dead // maybe we could disable all mods other than the coremods and try a reload before doing this? @@ -636,7 +636,7 @@ template <ScriptContext context> void SquirrelManager<context>::ProcessMessageBu if (result != 0) // This func returns 0 on success for some reason { NS::log::squirrel_logger<context>()->error( - "ProcessMessageBuffer was unable to find function with name '{}'. Is it global?", message.functionName); + "ProcessMessageBuffer was unable to find function with name '{}'. Is it global?", message.functionName); continue; } @@ -661,11 +661,11 @@ template <ScriptContext context> void SquirrelManager<context>::ProcessMessageBu } ADD_SQFUNC( - "string", - NSGetCurrentModName, - "", - "Returns the mod name of the script running this function", - ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) + "string", + NSGetCurrentModName, + "", + "Returns the mod name of the script running this function", + ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) { int depth = g_pSquirrel<context>->getinteger(sqvm, 1); if (auto mod = g_pSquirrel<context>->getcallingmod(sqvm, depth); mod == nullptr) @@ -681,11 +681,11 @@ ADD_SQFUNC( } ADD_SQFUNC( - "string", - NSGetCallingModName, - "int depth = 0", - "Returns the mod name of the script running this function", - ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) + "string", + NSGetCallingModName, + "int depth = 0", + "Returns the mod name of the script running this function", + ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) { int depth = g_pSquirrel<context>->getinteger(sqvm, 1); if (auto mod = g_pSquirrel<context>->getcallingmod(sqvm, depth); mod == nullptr) @@ -772,7 +772,7 @@ ON_DLL_LOAD_RELIESON("client.dll", ClientSquirrel, ConCommand, (CModule module)) g_pSquirrel<ScriptContext::CLIENT>->__sq_GetEntityConstant_CBaseEntity = module.Offset(0x3E49B0).RCast<sq_GetEntityConstantType>(); g_pSquirrel<ScriptContext::CLIENT>->__sq_getentityfrominstance = module.Offset(0x114F0).RCast<sq_getentityfrominstanceType>(); g_pSquirrel<ScriptContext::UI>->__sq_GetEntityConstant_CBaseEntity = - g_pSquirrel<ScriptContext::CLIENT>->__sq_GetEntityConstant_CBaseEntity; + g_pSquirrel<ScriptContext::CLIENT>->__sq_GetEntityConstant_CBaseEntity; g_pSquirrel<ScriptContext::UI>->__sq_getentityfrominstance = g_pSquirrel<ScriptContext::CLIENT>->__sq_getentityfrominstance; // Message buffer stuff @@ -789,9 +789,9 @@ ON_DLL_LOAD_RELIESON("client.dll", ClientSquirrel, ConCommand, (CModule module)) g_pSquirrel<ScriptContext::UI>->__sq_sealstructslot = g_pSquirrel<ScriptContext::CLIENT>->__sq_sealstructslot; MAKEHOOK( - module.Offset(0x108E0), - &RegisterSquirrelFunctionHook<ScriptContext::CLIENT>, - &g_pSquirrel<ScriptContext::CLIENT>->RegisterSquirrelFunc); + module.Offset(0x108E0), + &RegisterSquirrelFunctionHook<ScriptContext::CLIENT>, + &g_pSquirrel<ScriptContext::CLIENT>->RegisterSquirrelFunc); g_pSquirrel<ScriptContext::UI>->RegisterSquirrelFunc = g_pSquirrel<ScriptContext::CLIENT>->RegisterSquirrelFunc; g_pSquirrel<ScriptContext::CLIENT>->logger = NS::log::SCRIPT_CL; @@ -882,9 +882,9 @@ ON_DLL_LOAD_RELIESON("server.dll", ServerSquirrel, ConCommand, (CModule module)) g_pSquirrel<ScriptContext::SERVER>->__sq_sealstructslot = module.Offset(0x5510).RCast<sq_sealstructslotType>(); MAKEHOOK( - module.Offset(0x1DD10), - &RegisterSquirrelFunctionHook<ScriptContext::SERVER>, - &g_pSquirrel<ScriptContext::SERVER>->RegisterSquirrelFunc); + module.Offset(0x1DD10), + &RegisterSquirrelFunctionHook<ScriptContext::SERVER>, + &g_pSquirrel<ScriptContext::SERVER>->RegisterSquirrelFunc); MAKEHOOK(module.Offset(0x8AA0), &sq_compiler_createHook<ScriptContext::SERVER>, &sq_compiler_create<ScriptContext::SERVER>); @@ -897,10 +897,10 @@ ON_DLL_LOAD_RELIESON("server.dll", ServerSquirrel, ConCommand, (CModule module)) // FCVAR_CHEAT and FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS allows clients to execute this, but since it's unsafe we only allow it when cheats // are enabled for script_client and script_ui, we don't use cheats, so clients can execute them on themselves all they want RegisterConCommand( - "script", - ConCommand_script<ScriptContext::SERVER>, - "Executes script code on the server vm", - FCVAR_GAMEDLL | FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS | FCVAR_CHEAT); + "script", + ConCommand_script<ScriptContext::SERVER>, + "Executes script code on the server vm", + FCVAR_GAMEDLL | FCVAR_GAMEDLL_FOR_REMOTE_CLIENTS | FCVAR_CHEAT); StubUnsafeSQFuncs<ScriptContext::SERVER>(); diff --git a/NorthstarDLL/squirrel/squirrel.h b/NorthstarDLL/squirrel/squirrel.h index 427eb03c..743d84ed 100644 --- a/NorthstarDLL/squirrel/squirrel.h +++ b/NorthstarDLL/squirrel/squirrel.h @@ -7,8 +7,8 @@ #include "mods/modmanager.h" /* - definitions from hell - required to function + definitions from hell + required to function */ template <ScriptContext context, typename T> inline void SqRecurseArgs(FunctionVector& v, T& arg); @@ -16,7 +16,7 @@ template <ScriptContext context, typename T> inline void SqRecurseArgs(FunctionV template <ScriptContext context, typename T, typename... Args> inline void SqRecurseArgs(FunctionVector& v, T& arg, Args... args); /* - sanity below + sanity below */ // stolen from ttf2sdk: sqvm types @@ -354,7 +354,7 @@ template <ScriptContext context> class SquirrelManager : public virtual Squirrel if (!m_pSQVM || !m_pSQVM->sqvm) { spdlog::error( - "{} was called on context {} while VM was not initialized. This will crash", __FUNCTION__, GetContextName(context)); + "{} was called on context {} while VM was not initialized. This will crash", __FUNCTION__, GetContextName(context)); } SQObject functionobj {}; @@ -378,7 +378,7 @@ template <ScriptContext context> class SquirrelManager : public virtual Squirrel if (!m_pSQVM || !m_pSQVM->sqvm) { spdlog::error( - "{} was called on context {} while VM was not initialized. This will crash", __FUNCTION__, GetContextName(context)); + "{} was called on context {} while VM was not initialized. This will crash", __FUNCTION__, GetContextName(context)); } SQObject functionobj {}; int result = sq_getfunction(m_pSQVM->sqvm, funcname, &functionobj, 0); @@ -425,9 +425,9 @@ template <ScriptContext context> SquirrelManager<context>* g_pSquirrel; void InitialiseSquirrelManagers(); /* - Beware all ye who enter below. - This place is not a place of honor... no highly esteemed deed is commemorated here... nothing valued is here. - What is here was dangerous and repulsive to us. This message is a warning about danger. + Beware all ye who enter below. + This place is not a place of honor... no highly esteemed deed is commemorated here... nothing valued is here. + What is here was dangerous and repulsive to us. This message is a warning about danger. */ #pragma region MessageBuffer templates diff --git a/NorthstarDLL/squirrel/squirrelautobind.h b/NorthstarDLL/squirrel/squirrelautobind.h index 865479a1..4d5e8649 100644 --- a/NorthstarDLL/squirrel/squirrelautobind.h +++ b/NorthstarDLL/squirrel/squirrelautobind.h @@ -19,21 +19,21 @@ class __squirrelautobind; namespace \ { \ __squirrelautobind CONCAT2(__squirrelautobind, __LINE__)( \ - []() \ - { \ - if constexpr (runOnContext & ScriptContext::UI) \ - g_pSquirrel<ScriptContext::UI>->AddFuncRegistration( \ - returnType, __STR(funcName), argTypes, helpText, CONCAT2(Script_, funcName) < ScriptContext::UI >); \ - if constexpr (runOnContext & ScriptContext::CLIENT) \ - g_pSquirrel<ScriptContext::CLIENT>->AddFuncRegistration( \ - returnType, __STR(funcName), argTypes, helpText, CONCAT2(Script_, funcName) < ScriptContext::CLIENT >); \ - }, \ - []() \ - { \ - if constexpr (runOnContext & ScriptContext::SERVER) \ - g_pSquirrel<ScriptContext::SERVER>->AddFuncRegistration( \ - returnType, __STR(funcName), argTypes, helpText, CONCAT2(Script_, funcName) < ScriptContext::SERVER >); \ - }); \ + []() \ + { \ + if constexpr (runOnContext & ScriptContext::UI) \ + g_pSquirrel<ScriptContext::UI>->AddFuncRegistration( \ + returnType, __STR(funcName), argTypes, helpText, CONCAT2(Script_, funcName) < ScriptContext::UI >); \ + if constexpr (runOnContext & ScriptContext::CLIENT) \ + g_pSquirrel<ScriptContext::CLIENT>->AddFuncRegistration( \ + returnType, __STR(funcName), argTypes, helpText, CONCAT2(Script_, funcName) < ScriptContext::CLIENT >); \ + }, \ + []() \ + { \ + if constexpr (runOnContext & ScriptContext::SERVER) \ + g_pSquirrel<ScriptContext::SERVER>->AddFuncRegistration( \ + returnType, __STR(funcName), argTypes, helpText, CONCAT2(Script_, funcName) < ScriptContext::SERVER >); \ + }); \ } \ template <ScriptContext context> SQRESULT CONCAT2(Script_, funcName)(HSquirrelVM * sqvm) @@ -42,20 +42,20 @@ class __squirrelautobind; namespace \ { \ __squirrelautobind CONCAT2(__squirrelautobind, __LINE__)( \ - []() \ - { \ - if constexpr (runOnContext & ScriptContext::UI) \ - g_pSquirrel<ScriptContext::UI>->AddFuncOverride(__STR(funcName), CONCAT2(Script_, funcName) < ScriptContext::UI >); \ - if constexpr (runOnContext & ScriptContext::CLIENT) \ - g_pSquirrel<ScriptContext::CLIENT>->AddFuncOverride( \ - __STR(funcName), CONCAT2(Script_, funcName) < ScriptContext::CLIENT >); \ - }, \ - []() \ - { \ - if constexpr (runOnContext & ScriptContext::SERVER) \ - g_pSquirrel<ScriptContext::SERVER>->AddFuncOverride( \ - __STR(funcName), CONCAT2(Script_, funcName) < ScriptContext::SERVER >); \ - }); \ + []() \ + { \ + if constexpr (runOnContext & ScriptContext::UI) \ + g_pSquirrel<ScriptContext::UI>->AddFuncOverride(__STR(funcName), CONCAT2(Script_, funcName) < ScriptContext::UI >); \ + if constexpr (runOnContext & ScriptContext::CLIENT) \ + g_pSquirrel<ScriptContext::CLIENT>->AddFuncOverride( \ + __STR(funcName), CONCAT2(Script_, funcName) < ScriptContext::CLIENT >); \ + }, \ + []() \ + { \ + if constexpr (runOnContext & ScriptContext::SERVER) \ + g_pSquirrel<ScriptContext::SERVER>->AddFuncOverride( \ + __STR(funcName), CONCAT2(Script_, funcName) < ScriptContext::SERVER >); \ + }); \ } \ template <ScriptContext context> SQRESULT CONCAT2(Script_, funcName)(HSquirrelVM * sqvm) diff --git a/NorthstarDLL/squirrel/squirrelclasstypes.h b/NorthstarDLL/squirrel/squirrelclasstypes.h index ac813334..f0d338fe 100644 --- a/NorthstarDLL/squirrel/squirrelclasstypes.h +++ b/NorthstarDLL/squirrel/squirrelclasstypes.h @@ -27,9 +27,9 @@ enum class eSQReturnType }; const std::map<SQRESULT, const char*> PrintSQRESULT = { - {SQRESULT::SQRESULT_ERROR, "SQRESULT_ERROR"}, - {SQRESULT::SQRESULT_NULL, "SQRESULT_NULL"}, - {SQRESULT::SQRESULT_NOTNULL, "SQRESULT_NOTNULL"}}; + {SQRESULT::SQRESULT_ERROR, "SQRESULT_ERROR"}, + {SQRESULT::SQRESULT_NULL, "SQRESULT_NULL"}, + {SQRESULT::SQRESULT_NOTNULL, "SQRESULT_NOTNULL"}}; struct CompileBufferState { @@ -189,7 +189,7 @@ typedef int64_t (*RegisterSquirrelFuncType)(CSquirrelVM* sqvm, SQFuncRegistratio typedef void (*sq_defconstType)(CSquirrelVM* sqvm, const SQChar* name, int value); typedef SQRESULT (*sq_compilebufferType)( - HSquirrelVM* sqvm, CompileBufferState* compileBuffer, const char* file, int a1, SQBool bShouldThrowError); + HSquirrelVM* sqvm, CompileBufferState* compileBuffer, const char* file, int a1, SQBool bShouldThrowError); typedef SQRESULT (*sq_callType)(HSquirrelVM* sqvm, SQInteger iArgs, SQBool bShouldReturn, SQBool bThrowError); typedef SQInteger (*sq_raiseerrorType)(HSquirrelVM* sqvm, const SQChar* pError); typedef bool (*sq_compilefileType)(CSquirrelVM* sqvm, const char* path, const char* name, int a4); diff --git a/NorthstarDLL/util/printmaps.cpp b/NorthstarDLL/util/printmaps.cpp index dd825bff..c4e30886 100644 --- a/NorthstarDLL/util/printmaps.cpp +++ b/NorthstarDLL/util/printmaps.cpp @@ -19,7 +19,7 @@ enum class MapSource_t }; const std::unordered_map<MapSource_t, const char*> PrintMapSource = { - {MapSource_t::VPK, "VPK"}, {MapSource_t::MOD, "MOD"}, {MapSource_t::GAMEDIR, "R2"}}; + {MapSource_t::VPK, "VPK"}, {MapSource_t::MOD, "MOD"}, {MapSource_t::GAMEDIR, "R2"}}; struct MapVPKInfo { @@ -62,7 +62,7 @@ void RefreshMapList() { const int iNumRetailNonMapVpks = 1; static const char* const ppRetailNonMapVpks[] = { - "englishclient_frontend.bsp.pak000_dir.vpk"}; // don't include mp_common here as it contains mp_lobby + "englishclient_frontend.bsp.pak000_dir.vpk"}; // don't include mp_common here as it contains mp_lobby // matches directory vpks, and captures their map name in the first group static const std::regex rVpkMapRegex("englishclient_([a-zA-Z0-9_]+)\\.bsp\\.pak000_dir\\.vpk", std::regex::icase); @@ -135,10 +135,10 @@ int, __fastcall, (const char *const cmdname, const char *const partial, char com { strcpy(commands[numMaps], cmdname); strncpy_s( - commands[numMaps++] + cmdLength, - COMMAND_COMPLETION_ITEM_LENGTH, - &vMapList[i].name[0], - COMMAND_COMPLETION_ITEM_LENGTH - cmdLength); + commands[numMaps++] + cmdLength, + COMMAND_COMPLETION_ITEM_LENGTH, + &vMapList[i].name[0], + COMMAND_COMPLETION_ITEM_LENGTH - cmdLength); } } @@ -146,11 +146,11 @@ int, __fastcall, (const char *const cmdname, const char *const partial, char com } ADD_SQFUNC( - "array<string>", - NSGetLoadedMapNames, - "", - "Returns a string array of loaded map file names", - ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) + "array<string>", + NSGetLoadedMapNames, + "", + "Returns a string array of loaded map file names", + ScriptContext::UI | ScriptContext::CLIENT | ScriptContext::SERVER) { // Maybe we should call this on mods reload instead RefreshMapList(); diff --git a/NorthstarDLL/util/version.cpp b/NorthstarDLL/util/version.cpp index 1ad62438..d81f0e23 100644 --- a/NorthstarDLL/util/version.cpp +++ b/NorthstarDLL/util/version.cpp @@ -17,23 +17,23 @@ void InitialiseVersion() { sprintf(version, "%d.%d.%d.%d+dev", northstar_version[0], northstar_version[1], northstar_version[2], northstar_version[3]); ua_len += snprintf( - NSUserAgent + ua_len, - sizeof(NSUserAgent) - ua_len, - "R2Northstar/%d.%d.%d+dev", - northstar_version[0], - northstar_version[1], - northstar_version[2]); + NSUserAgent + ua_len, + sizeof(NSUserAgent) - ua_len, + "R2Northstar/%d.%d.%d+dev", + northstar_version[0], + northstar_version[1], + northstar_version[2]); } else { sprintf(version, "%d.%d.%d.%d", northstar_version[0], northstar_version[1], northstar_version[2], northstar_version[3]); ua_len += snprintf( - NSUserAgent + ua_len, - sizeof(NSUserAgent) - ua_len, - "R2Northstar/%d.%d.%d", - northstar_version[0], - northstar_version[1], - northstar_version[2]); + NSUserAgent + ua_len, + sizeof(NSUserAgent) - ua_len, + "R2Northstar/%d.%d.%d", + northstar_version[0], + northstar_version[1], + northstar_version[2]); } if (IsDedicatedServer()) @@ -75,12 +75,12 @@ void InitialiseVersion() // windows version if (osvi.dwMajorVersion) ua_len += snprintf( - NSUserAgent + ua_len, - sizeof(NSUserAgent) - ua_len, - " Windows/%d.%d.%d", - osvi.dwMajorVersion, - osvi.dwMinorVersion, - osvi.dwBuildNumber); + NSUserAgent + ua_len, + sizeof(NSUserAgent) - ua_len, + " Windows/%d.%d.%d", + osvi.dwMajorVersion, + osvi.dwMinorVersion, + osvi.dwBuildNumber); // wine version if (wine_version && wine_build_id) diff --git a/NorthstarLauncher/main.cpp b/NorthstarLauncher/main.cpp index ecc18c45..5795584d 100644 --- a/NorthstarLauncher/main.cpp +++ b/NorthstarLauncher/main.cpp @@ -78,51 +78,51 @@ void LibraryLoadError(DWORD dwMessageId, const wchar_t* libName, const wchar_t* std::string message = std::system_category().message(dwMessageId); sprintf_s( - text, - "Failed to load the %ls at \"%ls\" (%lu):\n\n%hs\n\nMake sure you followed the Northstar installation instructions carefully " - "before reaching out for help.", - libName, - location, - dwMessageId, - message.c_str()); + text, + "Failed to load the %ls at \"%ls\" (%lu):\n\n%hs\n\nMake sure you followed the Northstar installation instructions carefully " + "before reaching out for help.", + libName, + location, + dwMessageId, + message.c_str()); if (dwMessageId == 126 && std::filesystem::exists(location)) { sprintf_s( - text, - "%s\n\nThe file at the specified location DOES exist, so this error indicates that one of its *dependencies* failed to be " - "found.\n\nTry the following steps:\n1. Install Visual C++ 2022 Redistributable: " - "https://aka.ms/vs/17/release/vc_redist.x64.exe\n2. Repair game files", - text); + text, + "%s\n\nThe file at the specified location DOES exist, so this error indicates that one of its *dependencies* failed to be " + "found.\n\nTry the following steps:\n1. Install Visual C++ 2022 Redistributable: " + "https://aka.ms/vs/17/release/vc_redist.x64.exe\n2. Repair game files", + text); } else if (!fs::exists("Titanfall2.exe") && (fs::exists("..\\Titanfall2.exe") || fs::exists("..\\..\\Titanfall2.exe"))) { auto curDir = std::filesystem::current_path().filename().string(); auto aboveDir = std::filesystem::current_path().parent_path().filename().string(); sprintf_s( - text, - "%s\n\nWe detected that in your case you have extracted the files into a *subdirectory* of your Titanfall 2 " - "installation.\nPlease move all the files and folders from current folder (\"%s\") into the Titanfall 2 installation directory " - "just above (\"%s\").\n\nPlease try out the above steps by yourself before reaching out to the community for support.", - text, - curDir.c_str(), - aboveDir.c_str()); + text, + "%s\n\nWe detected that in your case you have extracted the files into a *subdirectory* of your Titanfall 2 " + "installation.\nPlease move all the files and folders from current folder (\"%s\") into the Titanfall 2 installation directory " + "just above (\"%s\").\n\nPlease try out the above steps by yourself before reaching out to the community for support.", + text, + curDir.c_str(), + aboveDir.c_str()); } else if (!fs::exists("Titanfall2.exe")) { sprintf_s( - text, - "%s\n\nRemember: you need to unpack the contents of this archive into your Titanfall 2 game installation directory, not just " - "to any random folder.", - text); + text, + "%s\n\nRemember: you need to unpack the contents of this archive into your Titanfall 2 game installation directory, not just " + "to any random folder.", + text); } else if (fs::exists("Titanfall2.exe")) { sprintf_s( - text, - "%s\n\nTitanfall2.exe has been found in the current directory: is the game installation corrupted or did you not unpack all " - "Northstar files here?", - text); + text, + "%s\n\nTitanfall2.exe has been found in the current directory: is the game installation corrupted or did you not unpack all " + "Northstar files here?", + text); } MessageBoxA(GetForegroundWindow(), text, "Northstar Launcher Error", 0); @@ -195,16 +195,16 @@ void EnsureOriginStarted() si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_MINIMIZE; CreateProcessA( - originPath, - (char*)"", - NULL, - NULL, - false, - CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_PROCESS_GROUP, - NULL, - NULL, - (LPSTARTUPINFOA)&si, - &pi); + originPath, + (char*)"", + NULL, + NULL, + false, + CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_PROCESS_GROUP, + NULL, + NULL, + (LPSTARTUPINFOA)&si, + &pi); std::cout << "[*] Waiting for Origin..." << std::endl; @@ -233,22 +233,22 @@ void PrependPath() if (result == -1) { MessageBoxW( - GetForegroundWindow(), - L"Warning: could not prepend the current directory to app's PATH environment variable. Something may break because of " - L"that.", - L"Northstar Launcher Warning", - 0); + GetForegroundWindow(), + L"Warning: could not prepend the current directory to app's PATH environment variable. Something may break because of " + L"that.", + L"Northstar Launcher Warning", + 0); } free(pPath); } else { MessageBoxW( - GetForegroundWindow(), - L"Warning: could not get current PATH environment variable in order to prepend the current directory to it. Something may " - L"break because of that.", - L"Northstar Launcher Warning", - 0); + GetForegroundWindow(), + L"Warning: could not get current PATH environment variable in order to prepend the current directory to it. Something may " + L"break because of that.", + L"Northstar Launcher Warning", + 0); } } @@ -352,10 +352,10 @@ int main(int argc, char* argv[]) if (!GetExePathWide(exePath, sizeof(exePath))) { MessageBoxA( - GetForegroundWindow(), - "Failed getting game directory.\nThe game cannot continue and has to exit.", - "Northstar Launcher Error", - 0); + GetForegroundWindow(), + "Failed getting game directory.\nThe game cannot continue and has to exit.", + "Northstar Launcher Error", + 0); return 1; } @@ -383,26 +383,26 @@ int main(int argc, char* argv[]) std::cout << "[*] Loading stubs" << std::endl; HMODULE gssao, gtxaa, d3d11; if (!(gssao = GetModuleHandleA("GFSDK_SSAO.win64.dll")) && !(gtxaa = GetModuleHandleA("GFSDK_TXAA.win64.dll")) && - !(d3d11 = GetModuleHandleA("d3d11.dll"))) + !(d3d11 = GetModuleHandleA("d3d11.dll"))) { if (!(gssao = LoadDediStub("GFSDK_SSAO.win64.dll")) || !(gtxaa = LoadDediStub("GFSDK_TXAA.win64.dll")) || - !(d3d11 = LoadDediStub("d3d11.dll"))) + !(d3d11 = LoadDediStub("d3d11.dll"))) { if ((!gssao || FreeLibrary(gssao)) && (!gtxaa || FreeLibrary(gtxaa)) && (!d3d11 || FreeLibrary(d3d11))) { std::cout << "[*] WARNING: Failed to load d3d11/gfsdk stubs from bin/x64_dedi. " - "The stubs have been unloaded and the original libraries will be used instead" - << std::endl; + "The stubs have been unloaded and the original libraries will be used instead" + << std::endl; } else { // this is highly unlikely MessageBoxA( - GetForegroundWindow(), - "Failed to load one or more stubs, but could not unload them either.\n" - "The game cannot continue and has to exit.", - "Northstar Launcher Error", - 0); + GetForegroundWindow(), + "Failed to load one or more stubs, but could not unload them either.\n" + "The game cannot continue and has to exit.", + "Northstar Launcher Error", + 0); return 1; } } @@ -411,8 +411,8 @@ int main(int argc, char* argv[]) { // this should never happen std::cout << "[*] WARNING: Failed to load stubs because conflicting modules are already loaded, so those will be used instead " - "(did Northstar initialize too late?)." - << std::endl; + "(did Northstar initialize too late?)." + << std::endl; } } @@ -467,12 +467,12 @@ int main(int argc, char* argv[]) auto LauncherMain = GetLauncherMain(); if (!LauncherMain) MessageBoxA( - GetForegroundWindow(), - "Failed loading launcher.dll.\nThe game cannot continue and has to exit.", - "Northstar Launcher Error", - 0); + GetForegroundWindow(), + "Failed loading launcher.dll.\nThe game cannot continue and has to exit.", + "Northstar Launcher Error", + 0); std::cout.flush(); return ((int(/*__fastcall*/*)(HINSTANCE, HINSTANCE, LPSTR, int))LauncherMain)( - NULL, NULL, NULL, 0); // the parameters aren't really used anyways + NULL, NULL, NULL, 0); // the parameters aren't really used anyways } diff --git a/loader_wsock32_proxy/dllmain.cpp b/loader_wsock32_proxy/dllmain.cpp index 4cc4f26e..9425ddcc 100644 --- a/loader_wsock32_proxy/dllmain.cpp +++ b/loader_wsock32_proxy/dllmain.cpp @@ -31,10 +31,10 @@ BOOL WINAPI DllMain(HINSTANCE hInst, DWORD reason, LPVOID) if (!GetExePathWide(exePath, 4096)) { MessageBoxA( - GetForegroundWindow(), - "Failed getting game directory.\nThe game cannot continue and has to exit.", - "Northstar Wsock32 Proxy Error", - 0); + GetForegroundWindow(), + "Failed getting game directory.\nThe game cannot continue and has to exit.", + "Northstar Wsock32 Proxy Error", + 0); return true; } @@ -67,13 +67,13 @@ BOOL WINAPI DllMain(HINSTANCE hInst, DWORD reason, LPVOID) if (!std::filesystem::exists(temp_dir)) { swprintf_s( - buffer2, - L"Failed copying wsock32.dll from system32 to \"%s\"\n\n%S\n\nFurthermore, we failed copying wsock32.dll into " - L"temporary directory at \"%s\"\n\n%S", - buffer1, - e1.what(), - temp_dir.c_str(), - e2.what()); + buffer2, + L"Failed copying wsock32.dll from system32 to \"%s\"\n\n%S\n\nFurthermore, we failed copying wsock32.dll into " + L"temporary directory at \"%s\"\n\n%S", + buffer1, + e1.what(), + temp_dir.c_str(), + e2.what()); MessageBoxW(GetForegroundWindow(), buffer2, L"Northstar Wsock32 Proxy Error", 0); return false; } diff --git a/loader_wsock32_proxy/loader.cpp b/loader_wsock32_proxy/loader.cpp index 3e46c1a6..3b8ea95a 100644 --- a/loader_wsock32_proxy/loader.cpp +++ b/loader_wsock32_proxy/loader.cpp @@ -16,10 +16,10 @@ void LibraryLoadError(DWORD dwMessageId, const wchar_t* libName, const wchar_t* if (dwMessageId == 126 && std::filesystem::exists(location)) { sprintf_s( - text, - "%s\n\nThe file at the specified location DOES exist, so this error indicates that one of its *dependencies* failed to be " - "found.", - text); + text, + "%s\n\nThe file at the specified location DOES exist, so this error indicates that one of its *dependencies* failed to be " + "found.", + text); } MessageBoxA(GetForegroundWindow(), text, "Northstar Wsock32 Proxy Error", 0); } @@ -117,7 +117,7 @@ bool ProvisionNorthstar() if (MH_Initialize() != MH_OK) { MessageBoxA( - GetForegroundWindow(), "MH_Initialize failed\nThe game cannot continue and has to exit.", "Northstar Wsock32 Proxy Error", 0); + GetForegroundWindow(), "MH_Initialize failed\nThe game cannot continue and has to exit.", "Northstar Wsock32 Proxy Error", 0); return false; } @@ -125,16 +125,16 @@ bool ProvisionNorthstar() if (!launcherHandle) { MessageBoxA( - GetForegroundWindow(), - "Launcher isn't loaded yet.\nThe game cannot continue and has to exit.", - "Northstar Wsock32 Proxy Error", - 0); + GetForegroundWindow(), + "Launcher isn't loaded yet.\nThe game cannot continue and has to exit.", + "Northstar Wsock32 Proxy Error", + 0); return false; } LPVOID pTarget = (LPVOID)GetProcAddress(launcherHandle, "LauncherMain"); if (MH_CreateHook(pTarget, (LPVOID)&LauncherMainHook, reinterpret_cast<LPVOID*>(&LauncherMainOriginal)) != MH_OK || - MH_EnableHook(pTarget) != MH_OK) + MH_EnableHook(pTarget) != MH_OK) MessageBoxA(GetForegroundWindow(), "Hook creation failed for function LauncherMain.", "Northstar Wsock32 Proxy Error", 0); return true; |