diff --git a/.clang-format b/.clang-format index fce858d1..0828fb5c 100644 --- a/.clang-format +++ b/.clang-format @@ -38,7 +38,7 @@ BraceWrapping: SplitEmptyNamespace: true PointerAlignment: Left -SortIncludes: CaseSensitive +SortIncludes: Never IncludeBlocks: Regroup IncludeCategories: # External headers in <> with extension or / diff --git a/.devcontainer/linux/devcontainer.json b/.devcontainer/linux/devcontainer.json index e0c201dd..aafc31ec 100644 --- a/.devcontainer/linux/devcontainer.json +++ b/.devcontainer/linux/devcontainer.json @@ -1,11 +1,18 @@ { "name": "SteamRT Sniper SDK", "image": "registry.gitlab.steamos.cloud/steamrt/sniper/sdk:latest", - "customizations": { + "updateContentCommand": "git submodule update --init --recursive", + "customizations": { "vscode": { "extensions": [ - "ms-vscode.cpptools" + "ms-vscode.cpptools", + "ms-vscode.cpptools-extension-pack", + "GitHub.copilot", + "jeff-hykin.better-cpp-syntax" ] } + }, + "features": { + "ghcr.io/devcontainers/features/dotnet": "8.0" } } \ No newline at end of file diff --git a/.github/workflows/lint-code.yaml b/.github/workflows/lint-code.yaml new file mode 100644 index 00000000..4e036e38 --- /dev/null +++ b/.github/workflows/lint-code.yaml @@ -0,0 +1,25 @@ +name: Code format checks + +on: + pull_request: + paths: + - '.github/workflows/**' + - 'src/**' + - '.clang-format' + push: + paths: + - '.github/workflows/**' + - 'src/**' + - '.clang-format' + +jobs: + lint: + name: Lint code with clang-format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: jidicula/clang-format-action@4726374d1aa3c6aecf132e5197e498979588ebc8 + with: + clang-format-version: '20' + check-path: 'src' + exclude-regex: '(sdk|\.proto)' \ No newline at end of file diff --git a/src/core/UserMessage.cpp b/src/core/UserMessage.cpp index acda7080..0e87e201 100644 --- a/src/core/UserMessage.cpp +++ b/src/core/UserMessage.cpp @@ -1,41 +1,41 @@ -/* - * This file is part of CounterStrikeSharp. - * CounterStrikeSharp is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * CounterStrikeSharp is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with CounterStrikeSharp. If not, see . * - */ -#include "UserMessage.h" - -#include "networksystem/inetworkserializer.h" - -using namespace google; - -namespace counterstrikesharp { -int UserMessage::GetMessageID() { return msgSerializable->GetNetMessageInfo()->m_MessageId; } - -std::string UserMessage::GetMessageName() { return msgSerializable->GetUnscopedName(); } - -bool UserMessage::HasField(std::string fieldName) -{ - const google::protobuf::Descriptor* descriptor = msg->GetDescriptor(); - const google::protobuf::FieldDescriptor* field = descriptor->FindFieldByName(fieldName); - - if (field == nullptr || (field->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED)) - { - return false; - } - - return this->msg->GetReflection()->HasField(*this->msg, field); -} - -const CNetMessagePB* UserMessage::GetProtobufMessage() { return msg; } -} // namespace counterstrikesharp +/* + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ +#include "UserMessage.h" + +#include "networksystem/inetworkserializer.h" + +using namespace google; + +namespace counterstrikesharp { +int UserMessage::GetMessageID() { return msgSerializable->GetNetMessageInfo()->m_MessageId; } + +std::string UserMessage::GetMessageName() { return msgSerializable->GetUnscopedName(); } + +bool UserMessage::HasField(std::string fieldName) +{ + const google::protobuf::Descriptor* descriptor = msg->GetDescriptor(); + const google::protobuf::FieldDescriptor* field = descriptor->FindFieldByName(fieldName); + + if (field == nullptr || (field->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED)) + { + return false; + } + + return this->msg->GetReflection()->HasField(*this->msg, field); +} + +const CNetMessagePB* UserMessage::GetProtobufMessage() { return msg; } +} // namespace counterstrikesharp diff --git a/src/core/cs2_sdk/interfaces/cgameresourceserviceserver.h b/src/core/cs2_sdk/interfaces/cgameresourceserviceserver.h index a3955277..40bad521 100644 --- a/src/core/cs2_sdk/interfaces/cgameresourceserviceserver.h +++ b/src/core/cs2_sdk/interfaces/cgameresourceserviceserver.h @@ -28,8 +28,7 @@ class CGameResourceService public: CGameEntitySystem* GetGameEntitySystem() { - return *reinterpret_cast( - (uintptr_t)(this) + - counterstrikesharp::globals::gameConfig->GetOffset("GameEntitySystem")); + return *reinterpret_cast((uintptr_t)(this) + + counterstrikesharp::globals::gameConfig->GetOffset("GameEntitySystem")); } -}; \ No newline at end of file +}; diff --git a/src/core/cs2_sdk/interfaces/cs2_interfaces.cpp b/src/core/cs2_sdk/interfaces/cs2_interfaces.cpp index 861a45ee..e50730cf 100644 --- a/src/core/cs2_sdk/interfaces/cs2_interfaces.cpp +++ b/src/core/cs2_sdk/interfaces/cs2_interfaces.cpp @@ -26,11 +26,10 @@ #include "tier0/memdbgon.h" namespace counterstrikesharp { -void interfaces::Initialize() { - pGameResourceServiceServer = (CGameResourceService*)modules::engine->FindInterface( - GAMERESOURCESERVICESERVER_INTERFACE_VERSION); +void interfaces::Initialize() +{ + pGameResourceServiceServer = (CGameResourceService*)modules::engine->FindInterface(GAMERESOURCESERVICESERVER_INTERFACE_VERSION); g_pCVar = (ICvar*)modules::tier0->FindInterface(CVAR_INTERFACE_VERSION); - g_pSource2GameEntities = (ISource2GameEntities*)modules::server->FindInterface( - SOURCE2GAMEENTITIES_INTERFACE_VERSION); + g_pSource2GameEntities = (ISource2GameEntities*)modules::server->FindInterface(SOURCE2GAMEENTITIES_INTERFACE_VERSION); } -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/core/cs2_sdk/interfaces/cs2_interfaces.h b/src/core/cs2_sdk/interfaces/cs2_interfaces.h index 23356940..cad67211 100644 --- a/src/core/cs2_sdk/interfaces/cs2_interfaces.h +++ b/src/core/cs2_sdk/interfaces/cs2_interfaces.h @@ -25,6 +25,6 @@ namespace counterstrikesharp { namespace interfaces { void Initialize(); -inline CGameResourceService *pGameResourceServiceServer = nullptr; -} // namespace interfaces -} // namespace counterstrikesharp \ No newline at end of file +inline CGameResourceService* pGameResourceServiceServer = nullptr; +} // namespace interfaces +} // namespace counterstrikesharp diff --git a/src/core/cs2_sdk/schema.cpp b/src/core/cs2_sdk/schema.cpp index f88932b2..a2cea1a1 100644 --- a/src/core/cs2_sdk/schema.cpp +++ b/src/core/cs2_sdk/schema.cpp @@ -33,8 +33,10 @@ using SchemaKeyValueMap_t = CUtlMap; using SchemaTableMap_t = CUtlMap; -bool IsFieldNetworked(SchemaClassFieldData_t& field) { - for (int i = 0; i < field.m_nStaticMetadataCount; i++) { +bool IsFieldNetworked(SchemaClassFieldData_t& field) +{ + for (int i = 0; i < field.m_nStaticMetadataCount; i++) + { static auto networkEnabled = hash_32_fnv1a_const("MNetworkEnable"); if (networkEnabled == hash_32_fnv1a_const(field.m_pStaticMetadata[i].m_pszName)) return true; } @@ -42,16 +44,16 @@ bool IsFieldNetworked(SchemaClassFieldData_t& field) { return false; } -static bool InitSchemaFieldsForClass(SchemaTableMap_t* tableMap, - const char* className, - uint32_t classKey) { +static bool InitSchemaFieldsForClass(SchemaTableMap_t* tableMap, const char* className, uint32_t classKey) +{ CSchemaSystemTypeScope* pType = counterstrikesharp::globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT); if (!pType) return false; SchemaClassInfoData_t* pClassInfo = pType->FindDeclaredClass(className).Get(); - if (!pClassInfo) { + if (!pClassInfo) + { SchemaKeyValueMap_t* map = new SchemaKeyValueMap_t(0, 0, DefLessFunc(uint32_t)); tableMap->Insert(classKey, map); @@ -66,31 +68,34 @@ static bool InitSchemaFieldsForClass(SchemaTableMap_t* tableMap, keyValueMap->EnsureCapacity(fieldsSize); tableMap->Insert(classKey, keyValueMap); - for (int i = 0; i < fieldsSize; ++i) { + for (int i = 0; i < fieldsSize; ++i) + { SchemaClassFieldData_t& field = pFields[i]; - keyValueMap->Insert(hash_32_fnv1a_const(field.m_pszName), - {field.m_nSingleInheritanceOffset, IsFieldNetworked(field)}); + keyValueMap->Insert(hash_32_fnv1a_const(field.m_pszName), { field.m_nSingleInheritanceOffset, IsFieldNetworked(field) }); } return true; } -int16_t schema::FindChainOffset(const char* className) { - CSchemaSystemTypeScope* pType = - counterstrikesharp::globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT); +int16_t schema::FindChainOffset(const char* className) +{ + CSchemaSystemTypeScope* pType = counterstrikesharp::globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT); if (!pType) return false; auto* pClassInfo = pType->FindDeclaredClass(className).Get(); - do { + do + { SchemaClassFieldData_t* pFields = pClassInfo->m_pFields; short fieldsSize = pClassInfo->m_nFieldCount; - for (int i = 0; i < fieldsSize; ++i) { + for (int i = 0; i < fieldsSize; ++i) + { SchemaClassFieldData_t& field = pFields[i]; - if (V_strcmp(field.m_pszName, "__m_pChainEntity") == 0) { + if (V_strcmp(field.m_pszName, "__m_pChainEntity") == 0) + { return field.m_nSingleInheritanceOffset; } } @@ -99,29 +104,29 @@ int16_t schema::FindChainOffset(const char* className) { return 0; } -SchemaKey schema::GetOffset(const char* className, - uint32_t classKey, - const char* memberName, - uint32_t memberKey) { +SchemaKey schema::GetOffset(const char* className, uint32_t classKey, const char* memberName, uint32_t memberKey) +{ static SchemaTableMap_t schemaTableMap(0, 0, DefLessFunc(uint32_t)); int16_t tableMapIndex = schemaTableMap.Find(classKey); - if (!schemaTableMap.IsValidIndex(tableMapIndex)) { - if (InitSchemaFieldsForClass(&schemaTableMap, className, classKey)) - return GetOffset(className, classKey, memberName, memberKey); + if (!schemaTableMap.IsValidIndex(tableMapIndex)) + { + if (InitSchemaFieldsForClass(&schemaTableMap, className, classKey)) return GetOffset(className, classKey, memberName, memberKey); - return {0, 0}; + return { 0, 0 }; } SchemaKeyValueMap_t* tableMap = schemaTableMap[tableMapIndex]; int16_t memberIndex = tableMap->Find(memberKey); - if (!tableMap->IsValidIndex(memberIndex)) { - return {0, 0}; + if (!tableMap->IsValidIndex(memberIndex)) + { + return { 0, 0 }; } return tableMap->Element(memberIndex); } -void SetStateChanged(Z_CBaseEntity* pEntity, int offset) { +void SetStateChanged(Z_CBaseEntity* pEntity, int offset) +{ // addresses::StateChanged(pEntity->m_NetworkTransmitComponent(), pEntity, offset, -1, -1); auto vars = counterstrikesharp::globals::getGlobalVars(); diff --git a/src/core/cs2_sdk/schema.h b/src/core/cs2_sdk/schema.h index 3a51654e..cbbf18ca 100644 --- a/src/core/cs2_sdk/schema.h +++ b/src/core/cs2_sdk/schema.h @@ -30,29 +30,28 @@ #undef schema -struct SchemaKey { +struct SchemaKey +{ int32_t offset; bool networked; }; class Z_CBaseEntity; -void SetStateChanged(Z_CBaseEntity *pEntity, int offset); +void SetStateChanged(Z_CBaseEntity* pEntity, int offset); inline uint32_t val_32_const = 0x811c9dc5; inline uint32_t prime_32_const = 0x1000193; inline uint64_t val_64_const = 0xcbf29ce484222325; inline uint64_t prime_64_const = 0x100000001b3; -inline uint32_t hash_32_fnv1a_const(const char *str, const uint32_t value = val_32_const) noexcept { - return (str[0] == '\0') - ? value - : hash_32_fnv1a_const(&str[1], (value ^ uint32_t(str[0])) * prime_32_const); +inline uint32_t hash_32_fnv1a_const(const char* str, const uint32_t value = val_32_const) noexcept +{ + return (str[0] == '\0') ? value : hash_32_fnv1a_const(&str[1], (value ^ uint32_t(str[0])) * prime_32_const); } -inline uint64_t hash_64_fnv1a_const(const char *str, const uint64_t value = val_64_const) noexcept { - return (str[0] == '\0') - ? value - : hash_64_fnv1a_const(&str[1], (value ^ uint64_t(str[0])) * prime_64_const); +inline uint64_t hash_64_fnv1a_const(const char* str, const uint64_t value = val_64_const) noexcept +{ + return (str[0] == '\0') ? value : hash_64_fnv1a_const(&str[1], (value ^ uint64_t(str[0])) * prime_64_const); } namespace schema { @@ -95,6 +94,6 @@ static std::vector CS2BadList = { "m_nMusicID", }; -int16_t FindChainOffset(const char *className); -SchemaKey GetOffset(const char *className, uint32_t classKey, const char *memberName, uint32_t memberKey); -} // namespace schema +int16_t FindChainOffset(const char* className); +SchemaKey GetOffset(const char* className, uint32_t classKey, const char* memberName, uint32_t memberKey); +} // namespace schema diff --git a/src/core/function.cpp b/src/core/function.cpp index 58c990f2..c61335de 100644 --- a/src/core/function.cpp +++ b/src/core/function.cpp @@ -52,30 +52,30 @@ std::map g_HookMap; // ============================================================================ int GetDynCallConvention(Convention_t eConv) { - switch (eConv) { - case CONV_CUSTOM: - return -1; - case CONV_CDECL: - return DC_CALL_C_DEFAULT; - case CONV_THISCALL: + switch (eConv) + { + case CONV_CUSTOM: + return -1; + case CONV_CDECL: + return DC_CALL_C_DEFAULT; + case CONV_THISCALL: #ifdef _WIN32 - return DC_CALL_C_X86_WIN32_THIS_MS; + return DC_CALL_C_X86_WIN32_THIS_MS; #else - return DC_CALL_C_X86_WIN32_THIS_GNU; + return DC_CALL_C_X86_WIN32_THIS_GNU; #endif #ifdef _WIN32 - case CONV_STDCALL: - return DC_CALL_C_X86_WIN32_STD; - case CONV_FASTCALL: - return DC_CALL_C_X86_WIN32_FAST_MS; + case CONV_STDCALL: + return DC_CALL_C_X86_WIN32_STD; + case CONV_FASTCALL: + return DC_CALL_C_X86_WIN32_FAST_MS; #endif } return -1; } -ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, - std::vector args, DataType_t returnType) +ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, std::vector args, DataType_t returnType) : m_ulAddr(ulAddr) { m_Args = args; @@ -87,8 +87,7 @@ ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, m_iCallingConvention = GetDynCallConvention(m_eCallingConvention); } -ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, DataType_t* args, - int argCount, DataType_t returnType) +ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, DataType_t* args, int argCount, DataType_t returnType) : m_ulAddr(ulAddr) { @@ -101,13 +100,9 @@ ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, DataT ValveFunction::~ValveFunction() {} -bool ValveFunction::IsCallable() -{ - return (m_eCallingConvention != CONV_CUSTOM) && (m_iCallingConvention != -1); -} +bool ValveFunction::IsCallable() { return (m_eCallingConvention != CONV_CUSTOM) && (m_iCallingConvention != -1); } -template -ReturnType CallHelper(Function func, DCCallVM* vm, void* addr) +template ReturnType CallHelper(Function func, DCCallVM* vm, void* addr) { ReturnType result; result = (ReturnType)func(vm, (void*)addr); @@ -118,119 +113,120 @@ void CallHelperVoid(DCCallVM* vm, void* addr) { dcCallVoid(vm, (void*)addr); } void ValveFunction::Call(ScriptContext& script_context, int offset) { - if (!IsCallable()) - return; + if (!IsCallable()) return; dcReset(g_pCallVM); dcMode(g_pCallVM, m_iCallingConvention); - for (size_t i = 0; i < m_Args.size(); i++) { + for (size_t i = 0; i < m_Args.size(); i++) + { int contextIndex = i + offset; - switch (m_Args[i]) { - case DATA_TYPE_BOOL: - dcArgBool(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_CHAR: - dcArgChar(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_UCHAR: - dcArgChar(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_SHORT: - dcArgShort(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_USHORT: - dcArgShort(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_INT: - dcArgInt(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_UINT: - dcArgInt(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_LONG: - dcArgLong(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_ULONG: - dcArgLong(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_LONG_LONG: - dcArgLongLong(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_ULONG_LONG: - dcArgLongLong(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_FLOAT: - dcArgFloat(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_DOUBLE: - dcArgDouble(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_POINTER: - dcArgPointer(g_pCallVM, script_context.GetArgument(contextIndex)); - break; - case DATA_TYPE_STRING: - dcArgPointer(g_pCallVM, (void*)script_context.GetArgument(contextIndex)); - break; - default: - assert(!"Unknown function parameter type!"); - break; + switch (m_Args[i]) + { + case DATA_TYPE_BOOL: + dcArgBool(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_CHAR: + dcArgChar(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_UCHAR: + dcArgChar(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_SHORT: + dcArgShort(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_USHORT: + dcArgShort(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_INT: + dcArgInt(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_UINT: + dcArgInt(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_LONG: + dcArgLong(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_ULONG: + dcArgLong(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_LONG_LONG: + dcArgLongLong(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_ULONG_LONG: + dcArgLongLong(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_FLOAT: + dcArgFloat(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_DOUBLE: + dcArgDouble(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_POINTER: + dcArgPointer(g_pCallVM, script_context.GetArgument(contextIndex)); + break; + case DATA_TYPE_STRING: + dcArgPointer(g_pCallVM, (void*)script_context.GetArgument(contextIndex)); + break; + default: + assert(!"Unknown function parameter type!"); + break; } } - switch (m_eReturnType) { - case DATA_TYPE_VOID: - CallHelperVoid(g_pCallVM, m_ulAddr); - break; - case DATA_TYPE_BOOL: - script_context.SetResult(CallHelper(dcCallBool, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_CHAR: - script_context.SetResult(CallHelper(dcCallChar, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_UCHAR: - script_context.SetResult(CallHelper(dcCallChar, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_SHORT: - script_context.SetResult(CallHelper(dcCallShort, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_USHORT: - script_context.SetResult(CallHelper(dcCallShort, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_INT: - script_context.SetResult(CallHelper(dcCallInt, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_UINT: - script_context.SetResult(CallHelper(dcCallInt, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_LONG: - script_context.SetResult(CallHelper(dcCallLong, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_ULONG: - script_context.SetResult(CallHelper(dcCallLong, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_LONG_LONG: - script_context.SetResult(CallHelper(dcCallLongLong, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_ULONG_LONG: - script_context.SetResult( - CallHelper(dcCallLongLong, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_FLOAT: - script_context.SetResult(CallHelper(dcCallFloat, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_DOUBLE: - script_context.SetResult(CallHelper(dcCallDouble, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_POINTER: - script_context.SetResult(CallHelper(dcCallPointer, g_pCallVM, m_ulAddr)); - break; - case DATA_TYPE_STRING: - script_context.SetResult(CallHelper(dcCallPointer, g_pCallVM, m_ulAddr)); - break; - default: - assert(!"Unknown function return type!"); - break; + switch (m_eReturnType) + { + case DATA_TYPE_VOID: + CallHelperVoid(g_pCallVM, m_ulAddr); + break; + case DATA_TYPE_BOOL: + script_context.SetResult(CallHelper(dcCallBool, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_CHAR: + script_context.SetResult(CallHelper(dcCallChar, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_UCHAR: + script_context.SetResult(CallHelper(dcCallChar, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_SHORT: + script_context.SetResult(CallHelper(dcCallShort, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_USHORT: + script_context.SetResult(CallHelper(dcCallShort, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_INT: + script_context.SetResult(CallHelper(dcCallInt, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_UINT: + script_context.SetResult(CallHelper(dcCallInt, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_LONG: + script_context.SetResult(CallHelper(dcCallLong, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_ULONG: + script_context.SetResult(CallHelper(dcCallLong, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_LONG_LONG: + script_context.SetResult(CallHelper(dcCallLongLong, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_ULONG_LONG: + script_context.SetResult(CallHelper(dcCallLongLong, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_FLOAT: + script_context.SetResult(CallHelper(dcCallFloat, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_DOUBLE: + script_context.SetResult(CallHelper(dcCallDouble, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_POINTER: + script_context.SetResult(CallHelper(dcCallPointer, g_pCallVM, m_ulAddr)); + break; + case DATA_TYPE_STRING: + script_context.SetResult(CallHelper(dcCallPointer, g_pCallVM, m_ulAddr)); + break; + default: + assert(!"Unknown function return type!"); + break; } } @@ -240,23 +236,24 @@ dyno::ReturnAction HookHandler(dyno::HookType hookType, dyno::Hook& hook) auto callback = hookType == dyno::HookType::Pre ? vf->m_precallback : vf->m_postcallback; - if (callback == nullptr) { + if (callback == nullptr) + { return dyno::ReturnAction::Ignored; } callback->Reset(); callback->ScriptContext().Push(&hook); - for (auto fnMethodToCall : callback->GetFunctions()) { - if (!fnMethodToCall) - continue; + for (auto fnMethodToCall : callback->GetFunctions()) + { + if (!fnMethodToCall) continue; fnMethodToCall(&callback->ScriptContextStruct()); auto result = callback->ScriptContext().GetResult(); - CSSHARP_CORE_TRACE("Received hook callback result of {}, hook mode {}", result, - (int)hookType); + CSSHARP_CORE_TRACE("Received hook callback result of {}, hook mode {}", result, (int)hookType); - if (result >= HookResult::Handled) { + if (result >= HookResult::Handled) + { return dyno::ReturnAction::Supercede; } } @@ -269,7 +266,8 @@ std::vector ConvertArgsToDynoHook(const std::vector converted; converted.reserve(dataTypes.size()); - for (DataType_t dt : dataTypes) { + for (DataType_t dt : dataTypes) + { converted.push_back(dyno::DataObject(static_cast(dt))); } @@ -290,19 +288,25 @@ void ValveFunction::AddHook(CallbackT callable, bool post) hook->addCallback(dyno::HookType::Post, (dyno::HookHandler*)&HookHandler); hook->addCallback(dyno::HookType::Pre, (dyno::HookHandler*)&HookHandler); - if (post) { - if (m_postcallback == nullptr) { + if (post) + { + if (m_postcallback == nullptr) + { m_postcallback = globals::callbackManager.CreateCallback(""); } m_postcallback->AddListener(callable); - } else { - if (m_precallback == nullptr) { + } + else + { + if (m_precallback == nullptr) + { m_precallback = globals::callbackManager.CreateCallback(""); } m_precallback->AddListener(callable); } } -void ValveFunction::RemoveHook(CallbackT callable, bool post) { +void ValveFunction::RemoveHook(CallbackT callable, bool post) +{ dyno::HookManager& manager = dyno::HookManager::Get(); dyno::Hook* hook = manager.hook((void*)m_ulAddr, [this] { #ifdef _WIN32 @@ -313,12 +317,17 @@ void ValveFunction::RemoveHook(CallbackT callable, bool post) { }); g_HookMap[hook] = this; - if (post) { - if (m_postcallback != nullptr) { + if (post) + { + if (m_postcallback != nullptr) + { m_postcallback->RemoveListener(callable); } - } else { - if (m_precallback != nullptr) { + } + else + { + if (m_precallback != nullptr) + { m_precallback->RemoveListener(callable); } } diff --git a/src/core/function.h b/src/core/function.h index 163fa671..f30cd9ee 100644 --- a/src/core/function.h +++ b/src/core/function.h @@ -40,7 +40,8 @@ class Hook; namespace counterstrikesharp { -enum DataType_t { +enum DataType_t +{ DATA_TYPE_VOID, DATA_TYPE_BOOL, DATA_TYPE_CHAR, @@ -60,7 +61,8 @@ enum DataType_t { DATA_TYPE_VARIANT }; -enum Protection_t { +enum Protection_t +{ PROTECTION_NONE, PROTECTION_READ, PROTECTION_READ_WRITE, @@ -69,19 +71,20 @@ enum Protection_t { PROTECTION_EXECUTE_READ_WRITE }; -enum Convention_t { CONV_CUSTOM, CONV_CDECL, CONV_THISCALL, CONV_STDCALL, CONV_FASTCALL }; +enum Convention_t +{ + CONV_CUSTOM, + CONV_CDECL, + CONV_THISCALL, + CONV_STDCALL, + CONV_FASTCALL +}; -class ValveFunction { -public: - ValveFunction(void* ulAddr, - Convention_t callingConvention, - std::vector args, - DataType_t returnType); - ValveFunction(void* ulAddr, - Convention_t callingConvention, - DataType_t* args, - int argCount, - DataType_t returnType); +class ValveFunction +{ + public: + ValveFunction(void* ulAddr, Convention_t callingConvention, std::vector args, DataType_t returnType); + ValveFunction(void* ulAddr, Convention_t callingConvention, DataType_t* args, int argCount, DataType_t returnType); ~ValveFunction(); @@ -110,4 +113,4 @@ public: ScriptCallback* m_postcallback = nullptr; }; -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp diff --git a/src/core/game_system.cpp b/src/core/game_system.cpp index adf2acc8..385d0dc4 100644 --- a/src/core/game_system.cpp +++ b/src/core/game_system.cpp @@ -36,7 +36,8 @@ bool InitGameSystems() // bytes so we skip those uint8* ptr = (uint8*)counterstrikesharp::globals::gameConfig->ResolveSignature("IGameSystem_InitAllSystems_pFirst") + 3; - if (!ptr) { + if (!ptr) + { CSSHARP_CORE_ERROR("Failed to InitGameSystems, see warnings above."); return false; } @@ -63,4 +64,4 @@ GS_EVENT_MEMBER(CGameSystem, BuildGameSessionManifest) CSSHARP_CORE_INFO("CGameSystem::BuildGameSessionManifest"); counterstrikesharp::globals::serverManager.OnPrecacheResources(pResourceManifest); -} \ No newline at end of file +} diff --git a/src/core/game_system.h b/src/core/game_system.h index 16423bd7..30c9f115 100644 --- a/src/core/game_system.h +++ b/src/core/game_system.h @@ -37,11 +37,10 @@ class CGameSystem : public CBaseGameSystem void SetGameSystemGlobalPtrs(void* pValue) override { - if (sm_Factory) - sm_Factory->SetGlobalPtr(pValue); + if (sm_Factory) sm_Factory->SetGlobalPtr(pValue); } bool DoesGameSystemReallocate() override { return sm_Factory->ShouldAutoAdd(); } static IGameSystemFactory* sm_Factory; -}; \ No newline at end of file +}; diff --git a/src/core/gameconfig.h b/src/core/gameconfig.h index 196252b1..c1118b18 100644 --- a/src/core/gameconfig.h +++ b/src/core/gameconfig.h @@ -1,6 +1,5 @@ #pragma once - #include "core/globals.h" #include "core/memory_module.h" #include diff --git a/src/core/global_listener.h b/src/core/global_listener.h index 9b0c55ce..140ed5df 100644 --- a/src/core/global_listener.h +++ b/src/core/global_listener.h @@ -32,34 +32,37 @@ #pragma once namespace counterstrikesharp { -class GlobalClass { -public: +class GlobalClass +{ + public: virtual ~GlobalClass() = default; - GlobalClass() { + GlobalClass() + { m_pGlobalClassNext = GlobalClass::head; GlobalClass::head = this; } -public: + public: virtual void OnStartup() {} virtual void OnShutdown() {} virtual void OnAllInitialized() {} virtual void OnGameLoopInitialized() {} virtual void OnAllInitialized_Post() {} - virtual void OnLevelChange(const char *mapName) {} + virtual void OnLevelChange(const char* mapName) {} virtual void OnLevelEnd() {} -public: - GlobalClass *m_pGlobalClassNext; - static GlobalClass *head; + public: + GlobalClass* m_pGlobalClassNext; + static GlobalClass* head; }; -} // namespace counterstrikesharp +} // namespace counterstrikesharp #define CALL_GLOBAL_LISTENER(func) \ - GlobalClass *pBase = GlobalClass::head; \ + GlobalClass* pBase = GlobalClass::head; \ pBase = GlobalClass::head; \ - while (pBase) { \ + while (pBase) \ + { \ pBase->func; \ pBase = pBase->m_pGlobalClassNext; \ } diff --git a/src/core/globals.cpp b/src/core/globals.cpp index f3675962..dda8e483 100644 --- a/src/core/globals.cpp +++ b/src/core/globals.cpp @@ -1,4 +1,3 @@ -// clang-format off #include "mm_plugin.h" #include "core/globals.h" #include "core/managers/player_manager.h" @@ -28,7 +27,6 @@ #include #include -// clang-format on namespace counterstrikesharp { @@ -142,7 +140,8 @@ void DetourGameEventManagerInit(IGameEventManager2* pGameEventManager) } int source_hook_pluginid = 0; -CGlobalVars* getGlobalVars() { +CGlobalVars* getGlobalVars() +{ INetworkGameServer* server = networkServerService->GetIGameServer(); if (!server) return nullptr; return networkServerService->GetIGameServer()->GetGlobals(); diff --git a/src/core/log.cpp b/src/core/log.cpp index aab61dbe..70db52d9 100644 --- a/src/core/log.cpp +++ b/src/core/log.cpp @@ -7,7 +7,8 @@ namespace counterstrikesharp { std::shared_ptr Log::m_core_logger; -void Log::Init() { +void Log::Init() +{ std::vector log_sinks; auto color_sink = std::make_shared(); #if _WIN32 @@ -17,8 +18,7 @@ void Log::Init() { #endif log_sinks.emplace_back(color_sink); - log_sinks.emplace_back( - std::make_shared("counterstrikesharp.log", true)); + log_sinks.emplace_back(std::make_shared("counterstrikesharp.log", true)); log_sinks[0]->set_pattern("%^[%T.%e] %n: %v%$"); log_sinks[1]->set_pattern("[%T.%e] [%l] %n: %v"); @@ -31,8 +31,9 @@ void Log::Init() { spdlog::cfg::load_env_levels(); } -void Log::Close() { +void Log::Close() +{ spdlog::drop("CSSharp"); m_core_logger = nullptr; } -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/core/log.h b/src/core/log.h index b1446557..21c762cb 100644 --- a/src/core/log.h +++ b/src/core/log.h @@ -6,21 +6,22 @@ #include namespace counterstrikesharp { -class Log { -public: +class Log +{ + public: static void Init(); static void Close(); - static std::shared_ptr &GetCoreLogger() { return m_core_logger; } + static std::shared_ptr& GetCoreLogger() { return m_core_logger; } -private: + private: static std::shared_ptr m_core_logger; }; -} // namespace counterstrikesharp +} // namespace counterstrikesharp -#define CSSHARP_CORE_TRACE(...) ::counterstrikesharp::Log::GetCoreLogger()->trace(__VA_ARGS__) -#define CSSHARP_CORE_DEBUG(...) ::counterstrikesharp::Log::GetCoreLogger()->debug(__VA_ARGS__) -#define CSSHARP_CORE_INFO(...) ::counterstrikesharp::Log::GetCoreLogger()->info(__VA_ARGS__) -#define CSSHARP_CORE_WARN(...) ::counterstrikesharp::Log::GetCoreLogger()->warn(__VA_ARGS__) -#define CSSHARP_CORE_ERROR(...) ::counterstrikesharp::Log::GetCoreLogger()->error(__VA_ARGS__) +#define CSSHARP_CORE_TRACE(...) ::counterstrikesharp::Log::GetCoreLogger()->trace(__VA_ARGS__) +#define CSSHARP_CORE_DEBUG(...) ::counterstrikesharp::Log::GetCoreLogger()->debug(__VA_ARGS__) +#define CSSHARP_CORE_INFO(...) ::counterstrikesharp::Log::GetCoreLogger()->info(__VA_ARGS__) +#define CSSHARP_CORE_WARN(...) ::counterstrikesharp::Log::GetCoreLogger()->warn(__VA_ARGS__) +#define CSSHARP_CORE_ERROR(...) ::counterstrikesharp::Log::GetCoreLogger()->error(__VA_ARGS__) #define CSSHARP_CORE_CRITICAL(...) ::counterstrikesharp::Log::GetCoreLogger()->critical(__VA_ARGS__) diff --git a/src/core/managers/chat_manager.cpp b/src/core/managers/chat_manager.cpp index 79b0adea..3c288e3b 100644 --- a/src/core/managers/chat_manager.cpp +++ b/src/core/managers/chat_manager.cpp @@ -1,127 +1,127 @@ -/* - * This file is part of CounterStrikeSharp. - * CounterStrikeSharp is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * CounterStrikeSharp is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with CounterStrikeSharp. If not, see . * - */ - -#include "core/managers/chat_manager.h" - -#include -#include -#include - -#include "characterset.h" -#include "core/coreconfig.h" -#include "core/gameconfig.h" -#include "core/log.h" -#include "core/managers/con_command_manager.h" -#include "core/memory.h" -#include "core/memory_module.h" -#include "scripting/callback_manager.h" - -namespace counterstrikesharp { - -ChatManager::ChatManager() {} - -ChatManager::~ChatManager() {} - -void ChatManager::OnAllInitialized() -{ - m_pHostSay = reinterpret_cast(modules::server->FindSignature(globals::gameConfig->GetSignature("Host_Say"))); - - if (m_pHostSay == nullptr) - { - CSSHARP_CORE_ERROR("Failed to find signature for \'Host_Say\'"); - return; - } - - auto m_hook = funchook_create(); - funchook_prepare(m_hook, (void**)&m_pHostSay, (void*)&DetourHostSay); - funchook_install(m_hook, 0); -} - -void ChatManager::OnShutdown() {} - -void DetourHostSay(CEntityInstance* pController, CCommand& args, bool teamonly, int unk1, const char* unk2) -{ - if (pController) - { - auto pEvent = globals::gameEventManager->CreateEvent("player_chat", true); - if (pEvent) - { - pEvent->SetBool("teamonly", teamonly); - pEvent->SetInt("userid", pController->GetEntityIndex().Get() - 1); - pEvent->SetString("text", args[1]); - - globals::gameEventManager->FireEvent(pEvent, true); - } - } - - std::string prefix; - bool bSilent = globals::coreConfig->IsSilentChatTrigger(args[1], prefix); - bool bCommand = globals::coreConfig->IsPublicChatTrigger(args[1], prefix) || bSilent; - - if (!bSilent) - { - m_pHostSay(pController, args, teamonly, unk1, unk2); - } - - if (bCommand) - { - char* pszMessage = (char*)(args.ArgS() + prefix.length() + 1); - - // Trailing slashes are only removed if Host_Say has been called. - if (bSilent) pszMessage[V_strlen(pszMessage) - 1] = 0; - - CCommand args; - args.Tokenize(pszMessage); - - auto prefixedPhrase = std::string("css_") + args.Arg(0); - auto bValidWithPrefix = globals::conCommandManager.IsValidValveCommand(prefixedPhrase.c_str()); - - if (bValidWithPrefix) - { - // Re-tokenize with a `css_` prefix if we have found that its a valid command. - args.Tokenize(("css_" + std::string(pszMessage)).c_str()); - } - - globals::chatManager.OnSayCommandPost(pController, args); - } -} - -bool ChatManager::OnSayCommandPre(CEntityInstance* pController, CCommand& command) { return false; } - -void ChatManager::OnSayCommandPost(CEntityInstance* pController, CCommand& command) -{ - auto commandStr = command.Arg(0); - - return InternalDispatch(pController, commandStr, command); -} - -void ChatManager::InternalDispatch(CEntityInstance* pPlayerController, const char* szTriggerPhase, CCommand& fullCommand) -{ - if (pPlayerController == nullptr) - { - globals::conCommandManager.ExecuteCommandCallbacks(fullCommand.Arg(0), - CCommandContext(CommandTarget_t::CT_NO_TARGET, CPlayerSlot(-1)), fullCommand, - HookMode::Pre, CommandCallingContext::Chat); - return; - } - - auto index = pPlayerController->GetEntityIndex().Get(); - auto slot = CPlayerSlot(index - 1); - - globals::conCommandManager.ExecuteCommandCallbacks(fullCommand.Arg(0), CCommandContext(CommandTarget_t::CT_NO_TARGET, slot), - fullCommand, HookMode::Pre, CommandCallingContext::Chat); -} -} // namespace counterstrikesharp +/* + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ + +#include "core/managers/chat_manager.h" + +#include +#include +#include + +#include "characterset.h" +#include "core/coreconfig.h" +#include "core/gameconfig.h" +#include "core/log.h" +#include "core/managers/con_command_manager.h" +#include "core/memory.h" +#include "core/memory_module.h" +#include "scripting/callback_manager.h" + +namespace counterstrikesharp { + +ChatManager::ChatManager() {} + +ChatManager::~ChatManager() {} + +void ChatManager::OnAllInitialized() +{ + m_pHostSay = reinterpret_cast(modules::server->FindSignature(globals::gameConfig->GetSignature("Host_Say"))); + + if (m_pHostSay == nullptr) + { + CSSHARP_CORE_ERROR("Failed to find signature for \'Host_Say\'"); + return; + } + + auto m_hook = funchook_create(); + funchook_prepare(m_hook, (void**)&m_pHostSay, (void*)&DetourHostSay); + funchook_install(m_hook, 0); +} + +void ChatManager::OnShutdown() {} + +void DetourHostSay(CEntityInstance* pController, CCommand& args, bool teamonly, int unk1, const char* unk2) +{ + if (pController) + { + auto pEvent = globals::gameEventManager->CreateEvent("player_chat", true); + if (pEvent) + { + pEvent->SetBool("teamonly", teamonly); + pEvent->SetInt("userid", pController->GetEntityIndex().Get() - 1); + pEvent->SetString("text", args[1]); + + globals::gameEventManager->FireEvent(pEvent, true); + } + } + + std::string prefix; + bool bSilent = globals::coreConfig->IsSilentChatTrigger(args[1], prefix); + bool bCommand = globals::coreConfig->IsPublicChatTrigger(args[1], prefix) || bSilent; + + if (!bSilent) + { + m_pHostSay(pController, args, teamonly, unk1, unk2); + } + + if (bCommand) + { + char* pszMessage = (char*)(args.ArgS() + prefix.length() + 1); + + // Trailing slashes are only removed if Host_Say has been called. + if (bSilent) pszMessage[V_strlen(pszMessage) - 1] = 0; + + CCommand args; + args.Tokenize(pszMessage); + + auto prefixedPhrase = std::string("css_") + args.Arg(0); + auto bValidWithPrefix = globals::conCommandManager.IsValidValveCommand(prefixedPhrase.c_str()); + + if (bValidWithPrefix) + { + // Re-tokenize with a `css_` prefix if we have found that its a valid command. + args.Tokenize(("css_" + std::string(pszMessage)).c_str()); + } + + globals::chatManager.OnSayCommandPost(pController, args); + } +} + +bool ChatManager::OnSayCommandPre(CEntityInstance* pController, CCommand& command) { return false; } + +void ChatManager::OnSayCommandPost(CEntityInstance* pController, CCommand& command) +{ + auto commandStr = command.Arg(0); + + return InternalDispatch(pController, commandStr, command); +} + +void ChatManager::InternalDispatch(CEntityInstance* pPlayerController, const char* szTriggerPhase, CCommand& fullCommand) +{ + if (pPlayerController == nullptr) + { + globals::conCommandManager.ExecuteCommandCallbacks(fullCommand.Arg(0), + CCommandContext(CommandTarget_t::CT_NO_TARGET, CPlayerSlot(-1)), fullCommand, + HookMode::Pre, CommandCallingContext::Chat); + return; + } + + auto index = pPlayerController->GetEntityIndex().Get(); + auto slot = CPlayerSlot(index - 1); + + globals::conCommandManager.ExecuteCommandCallbacks(fullCommand.Arg(0), CCommandContext(CommandTarget_t::CT_NO_TARGET, slot), + fullCommand, HookMode::Pre, CommandCallingContext::Chat); +} +} // namespace counterstrikesharp diff --git a/src/core/managers/chat_manager.h b/src/core/managers/chat_manager.h index 12cb7970..d18ad3a9 100644 --- a/src/core/managers/chat_manager.h +++ b/src/core/managers/chat_manager.h @@ -1,68 +1,68 @@ -/* - * This file is part of CounterStrikeSharp. - * CounterStrikeSharp is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * CounterStrikeSharp is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with CounterStrikeSharp. If not, see . * - */ - -#pragma once - -#include -#include - -#include "core/global_listener.h" -#include "core/globals.h" -#include "scripting/script_engine.h" - -namespace counterstrikesharp { -class ScriptCallback; - -typedef void (*HostSay)(CEntityInstance*, CCommand&, bool, int, const char*); - -class ChatCommandInfo -{ - friend class ChatManager; - - public: - ChatCommandInfo() {} - - public: - ScriptCallback* GetCallback() { return callback_pre; } - - private: - std::string command; - ScriptCallback* callback_pre; - ScriptCallback* callback_post; -}; - -class ChatManager : public GlobalClass -{ - public: - ChatManager(); - ~ChatManager(); - void OnAllInitialized() override; - void OnShutdown() override; - - bool OnSayCommandPre(CEntityInstance* pController, CCommand& args); - void OnSayCommandPost(CEntityInstance* pController, CCommand& args); - - private: - void InternalDispatch(CEntityInstance* pPlayerController, const char* szTriggerPhrase, CCommand& pFullCommand); - - std::vector m_cmd_list; - std::map m_cmd_lookup; -}; - -static void DetourHostSay(CEntityInstance* pController, CCommand& args, bool teamonly, int unk1, const char* unk2); -static HostSay m_pHostSay = nullptr; - -} // namespace counterstrikesharp +/* + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ + +#pragma once + +#include +#include + +#include "core/global_listener.h" +#include "core/globals.h" +#include "scripting/script_engine.h" + +namespace counterstrikesharp { +class ScriptCallback; + +typedef void (*HostSay)(CEntityInstance*, CCommand&, bool, int, const char*); + +class ChatCommandInfo +{ + friend class ChatManager; + + public: + ChatCommandInfo() {} + + public: + ScriptCallback* GetCallback() { return callback_pre; } + + private: + std::string command; + ScriptCallback* callback_pre; + ScriptCallback* callback_post; +}; + +class ChatManager : public GlobalClass +{ + public: + ChatManager(); + ~ChatManager(); + void OnAllInitialized() override; + void OnShutdown() override; + + bool OnSayCommandPre(CEntityInstance* pController, CCommand& args); + void OnSayCommandPost(CEntityInstance* pController, CCommand& args); + + private: + void InternalDispatch(CEntityInstance* pPlayerController, const char* szTriggerPhrase, CCommand& pFullCommand); + + std::vector m_cmd_list; + std::map m_cmd_lookup; +}; + +static void DetourHostSay(CEntityInstance* pController, CCommand& args, bool teamonly, int unk1, const char* unk2); +static HostSay m_pHostSay = nullptr; + +} // namespace counterstrikesharp diff --git a/src/core/managers/entity_manager.cpp b/src/core/managers/entity_manager.cpp index 9938e6ae..55cf1f65 100644 --- a/src/core/managers/entity_manager.cpp +++ b/src/core/managers/entity_manager.cpp @@ -1,18 +1,18 @@ /* -* This file is part of CounterStrikeSharp. -* CounterStrikeSharp is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* CounterStrikeSharp is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with CounterStrikeSharp. If not, see . * -*/ + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ #include "core/managers/entity_manager.h" #include "core/gameconfig.h" @@ -25,18 +25,28 @@ #include #include "scripting/callback_manager.h" -SH_DECL_HOOK7_void(ISource2GameEntities, CheckTransmit, SH_NOATTRIB, 0, CCheckTransmitInfo**, int, CBitVec<16384>&, const Entity2Networkable_t**, const uint16*, int, bool); +SH_DECL_HOOK7_void(ISource2GameEntities, + CheckTransmit, + SH_NOATTRIB, + 0, + CCheckTransmitInfo**, + int, + CBitVec<16384>&, + const Entity2Networkable_t**, + const uint16*, + int, + bool); namespace counterstrikesharp { -EntityManager::EntityManager() -{ - m_profile_name = "EntityManager"; -} +EntityManager::EntityManager() { m_profile_name = "EntityManager"; } EntityManager::~EntityManager() {} -CCheckTransmitInfoList::CCheckTransmitInfoList(CCheckTransmitInfo** pInfoInfoList, int nInfoCount) : infoList(pInfoInfoList), infoCount(nInfoCount) {} +CCheckTransmitInfoList::CCheckTransmitInfoList(CCheckTransmitInfo** pInfoInfoList, int nInfoCount) + : infoList(pInfoInfoList), infoCount(nInfoCount) +{ +} void EntityManager::OnAllInitialized() { @@ -46,13 +56,13 @@ void EntityManager::OnAllInitialized() on_entity_spawned_callback = globals::callbackManager.CreateCallback("OnEntitySpawned"); on_entity_created_callback = globals::callbackManager.CreateCallback("OnEntityCreated"); on_entity_deleted_callback = globals::callbackManager.CreateCallback("OnEntityDeleted"); - on_entity_parent_changed_callback = - globals::callbackManager.CreateCallback("OnEntityParentChanged"); + on_entity_parent_changed_callback = globals::callbackManager.CreateCallback("OnEntityParentChanged"); - m_pFireOutputInternal = reinterpret_cast(modules::server->FindSignature( - globals::gameConfig->GetSignature("CEntityIOOutput_FireOutputInternal"))); + m_pFireOutputInternal = reinterpret_cast( + modules::server->FindSignature(globals::gameConfig->GetSignature("CEntityIOOutput_FireOutputInternal"))); - if (m_pFireOutputInternal == nullptr) { + if (m_pFireOutputInternal == nullptr) + { CSSHARP_CORE_CRITICAL("Failed to find signature for \'CEntityIOOutput_FireOutputInternal\'"); return; } @@ -73,7 +83,7 @@ void EntityManager::OnAllInitialized() CSSHARP_CORE_CRITICAL("Failed to find signature for \'CEntitySystem_AddEntityIOEvent\'"); } - CBaseEntity_EmitSoundFilter = decltype(CBaseEntity_EmitSoundFilter) ( + CBaseEntity_EmitSoundFilter = decltype(CBaseEntity_EmitSoundFilter)( modules::server->FindSignature(globals::gameConfig->GetSignature("CBaseEntity_EmitSoundFilter"))); if (!CBaseEntity_EmitSoundFilter) @@ -104,7 +114,8 @@ void CEntityListener::OnEntitySpawned(CEntityInstance* pEntity) { auto callback = globals::entityManager.on_entity_spawned_callback; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->ScriptContext().Push(pEntity); callback->Execute(); @@ -114,7 +125,8 @@ void CEntityListener::OnEntityCreated(CEntityInstance* pEntity) { auto callback = globals::entityManager.on_entity_created_callback; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->ScriptContext().Push(pEntity); callback->Execute(); @@ -124,7 +136,8 @@ void CEntityListener::OnEntityDeleted(CEntityInstance* pEntity) { auto callback = globals::entityManager.on_entity_deleted_callback; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->ScriptContext().Push(pEntity); callback->Execute(); @@ -134,7 +147,8 @@ void CEntityListener::OnEntityParentChanged(CEntityInstance* pEntity, CEntityIns { auto callback = globals::entityManager.on_entity_parent_changed_callback; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->ScriptContext().Push(pEntity); callback->ScriptContext().Push(pNewParent); @@ -142,49 +156,58 @@ void CEntityListener::OnEntityParentChanged(CEntityInstance* pEntity, CEntityIns } } -void EntityManager::HookEntityOutput(const char* szClassname, const char* szOutput, - CallbackT fnCallback, HookMode mode) +void EntityManager::HookEntityOutput(const char* szClassname, const char* szOutput, CallbackT fnCallback, HookMode mode) { auto outputKey = OutputKey_t(szClassname, szOutput); CallbackPair* pCallbackPair; auto search = m_pHookMap.find(outputKey); - if (search == m_pHookMap.end()) { + if (search == m_pHookMap.end()) + { m_pHookMap[outputKey] = new CallbackPair(); pCallbackPair = m_pHookMap[outputKey]; - } else + } + else pCallbackPair = search->second; auto* pCallback = mode == HookMode::Pre ? pCallbackPair->pre : pCallbackPair->post; pCallback->AddListener(fnCallback); } -void EntityManager::UnhookEntityOutput(const char* szClassname, const char* szOutput, - CallbackT fnCallback, HookMode mode) +void EntityManager::UnhookEntityOutput(const char* szClassname, const char* szOutput, CallbackT fnCallback, HookMode mode) { auto outputKey = OutputKey_t(szClassname, szOutput); auto search = m_pHookMap.find(outputKey); - if (search != m_pHookMap.end()) { + if (search != m_pHookMap.end()) + { auto* pCallbackPair = search->second; auto* pCallback = mode == Pre ? pCallbackPair->pre : pCallbackPair->post; pCallback->RemoveListener(fnCallback); - if (!pCallbackPair->HasCallbacks()) { + if (!pCallbackPair->HasCallbacks()) + { m_pHookMap.erase(outputKey); } } } -void EntityManager::CheckTransmit(CCheckTransmitInfo** pInfoInfoList, int nInfoCount, CBitVec<16384>& unionTransmitEdicts, const Entity2Networkable_t** pNetworkables, const uint16* pEntityIndicies, int nEntityIndices, bool bEnablePVSBits) +void EntityManager::CheckTransmit(CCheckTransmitInfo** pInfoInfoList, + int nInfoCount, + CBitVec<16384>& unionTransmitEdicts, + const Entity2Networkable_t** pNetworkables, + const uint16* pEntityIndicies, + int nEntityIndices, + bool bEnablePVSBits) { VPROF_BUDGET(m_profile_name.c_str(), "CS# CheckTransmit"); - + auto callback = globals::entityManager.check_transmit; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { CCheckTransmitInfoList* infoList = new CCheckTransmitInfoList(pInfoInfoList, nInfoCount); callback->ScriptContext().Reset(); @@ -195,39 +218,43 @@ void EntityManager::CheckTransmit(CCheckTransmitInfo** pInfoInfoList, int nInfoC } } -void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pActivator, - CEntityInstance* pCaller, const CVariant* const value, float flDelay) +void DetourFireOutputInternal( + CEntityIOOutput* const pThis, CEntityInstance* pActivator, CEntityInstance* pCaller, const CVariant* const value, float flDelay) { - std::vector vecSearchKeys{OutputKey_t("*", pThis->m_pDesc->m_pName), - OutputKey_t("*", "*")}; + std::vector vecSearchKeys{ OutputKey_t("*", pThis->m_pDesc->m_pName), OutputKey_t("*", "*") }; - if (pCaller) { + if (pCaller) + { vecSearchKeys.push_back(OutputKey_t(pCaller->GetClassname(), pThis->m_pDesc->m_pName)); OutputKey_t(pCaller->GetClassname(), "*"); } std::vector vecCallbackPairs; - if (pCaller) { - CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, {}", pThis->m_pDesc->m_pName, - pCaller->GetClassname()); + if (pCaller) + { + CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, {}", pThis->m_pDesc->m_pName, pCaller->GetClassname()); auto& hookMap = globals::entityManager.m_pHookMap; - for (auto& searchKey : vecSearchKeys) { + for (auto& searchKey : vecSearchKeys) + { auto search = hookMap.find(searchKey); - if (search != hookMap.end()) { + if (search != hookMap.end()) + { vecCallbackPairs.push_back(search->second); } } - } else - CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, unknown caller", - pThis->m_pDesc->m_pName); + } + else + CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, unknown caller", pThis->m_pDesc->m_pName); HookResult result = HookResult::Continue; - for (auto pCallbackPair : vecCallbackPairs) { - if (pCallbackPair->pre->GetFunctionCount()) { + for (auto pCallbackPair : vecCallbackPairs) + { + if (pCallbackPair->pre->GetFunctionCount()) + { pCallbackPair->pre->ScriptContext().Reset(); pCallbackPair->pre->ScriptContext().Push(pThis); pCallbackPair->pre->ScriptContext().Push(pThis->m_pDesc->m_pName); @@ -236,32 +263,37 @@ void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pAc pCallbackPair->pre->ScriptContext().Push(value); pCallbackPair->pre->ScriptContext().Push(flDelay); - for (auto fnMethodToCall : pCallbackPair->pre->GetFunctions()) { - if (!fnMethodToCall) - continue; + for (auto fnMethodToCall : pCallbackPair->pre->GetFunctions()) + { + if (!fnMethodToCall) continue; fnMethodToCall(&pCallbackPair->pre->ScriptContextStruct()); auto thisResult = pCallbackPair->pre->ScriptContext().GetResult(); - if (thisResult >= HookResult::Stop) { + if (thisResult >= HookResult::Stop) + { return; } - if (thisResult > result) { + if (thisResult > result) + { result = thisResult; } } } } - if (result >= HookResult::Handled) { + if (result >= HookResult::Handled) + { return; } m_pFireOutputInternal(pThis, pActivator, pCaller, value, flDelay); - for (auto pCallbackPair : vecCallbackPairs) { - if (pCallbackPair->post->GetFunctionCount()) { + for (auto pCallbackPair : vecCallbackPairs) + { + if (pCallbackPair->post->GetFunctionCount()) + { pCallbackPair->post->ScriptContext().Reset(); pCallbackPair->post->ScriptContext().Push(pThis); pCallbackPair->post->ScriptContext().Push(pThis->m_pDesc->m_pName); @@ -276,8 +308,10 @@ void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pAc SndOpEventGuid_t EntityEmitSoundFilter(IRecipientFilter& filter, uint32 ent, const char* pszSound, float flVolume, float flPitch) { - if (!CBaseEntity_EmitSoundFilter) { - CSSHARP_CORE_ERROR("[EntityManager][EmitSoundFilter] - Failed to emit a sound. Signature for \'CBaseEntity_EmitSoundFilter\' is not found. The latest update may have broken it."); + if (!CBaseEntity_EmitSoundFilter) + { + CSSHARP_CORE_ERROR("[EntityManager][EmitSoundFilter] - Failed to emit a sound. Signature for \'CBaseEntity_EmitSoundFilter\' is " + "not found. The latest update may have broken it."); return SndOpEventGuid_t{}; } diff --git a/src/core/managers/entity_manager.h b/src/core/managers/entity_manager.h index 500ed6bc..0bbbf0ac 100644 --- a/src/core/managers/entity_manager.h +++ b/src/core/managers/entity_manager.h @@ -1,18 +1,18 @@ /* -* This file is part of CounterStrikeSharp. -* CounterStrikeSharp is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* CounterStrikeSharp is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with CounterStrikeSharp. If not, see . * -*/ + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ #pragma once @@ -34,24 +34,29 @@ class ScriptCallback; typedef std::pair OutputKey_t; -class CEntityListener : public IEntityListener { - void OnEntitySpawned(CEntityInstance *pEntity) override; - void OnEntityCreated(CEntityInstance *pEntity) override; - void OnEntityDeleted(CEntityInstance *pEntity) override; - void OnEntityParentChanged(CEntityInstance *pEntity, CEntityInstance *pNewParent) override; +class CEntityListener : public IEntityListener +{ + void OnEntitySpawned(CEntityInstance* pEntity) override; + void OnEntityCreated(CEntityInstance* pEntity) override; + void OnEntityDeleted(CEntityInstance* pEntity) override; + void OnEntityParentChanged(CEntityInstance* pEntity, CEntityInstance* pNewParent) override; }; -class CCheckTransmitInfoList { -public: +class CCheckTransmitInfoList +{ + public: CCheckTransmitInfoList(CCheckTransmitInfo** pInfoInfoList, int nInfoCount); -private: + + private: CCheckTransmitInfo** infoList; int infoCount; }; -class EntityManager : public GlobalClass { +class EntityManager : public GlobalClass +{ friend CEntityListener; -public: + + public: EntityManager(); ~EntityManager(); void OnAllInitialized() override; @@ -60,19 +65,25 @@ public: void UnhookEntityOutput(const char* szClassname, const char* szOutput, CallbackT fnCallback, HookMode mode); CEntityListener entityListener; std::map m_pHookMap; -private: - void CheckTransmit(CCheckTransmitInfo** pInfoInfoList, int nInfoCount, CBitVec<16384>& unionTransmitEdicts, const Entity2Networkable_t** pNetworkables, const uint16* pEntityIndicies, int nEntityIndices, bool bEnablePVSBits); - ScriptCallback *on_entity_spawned_callback; - ScriptCallback *on_entity_created_callback; - ScriptCallback *on_entity_deleted_callback; - ScriptCallback *on_entity_parent_changed_callback; - ScriptCallback *check_transmit; + private: + void CheckTransmit(CCheckTransmitInfo** pInfoInfoList, + int nInfoCount, + CBitVec<16384>& unionTransmitEdicts, + const Entity2Networkable_t** pNetworkables, + const uint16* pEntityIndicies, + int nEntityIndices, + bool bEnablePVSBits); + + ScriptCallback* on_entity_spawned_callback; + ScriptCallback* on_entity_created_callback; + ScriptCallback* on_entity_deleted_callback; + ScriptCallback* on_entity_parent_changed_callback; + ScriptCallback* check_transmit; std::string m_profile_name; }; - enum EntityIOTargetType_t { ENTITY_IO_TARGET_INVALID = 0xFFFFFFFF, @@ -118,16 +129,16 @@ class CEntityIOOutput EntityIOOutputDesc_t* m_pDesc; }; -typedef void (*FireOutputInternal)(CEntityIOOutput* const, CEntityInstance*, CEntityInstance*, - const CVariant* const, float); +typedef void (*FireOutputInternal)(CEntityIOOutput* const, CEntityInstance*, CEntityInstance*, const CVariant* const, float); -static void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pActivator, - CEntityInstance* pCaller, const CVariant* const value, float flDelay); +static void DetourFireOutputInternal( + CEntityIOOutput* const pThis, CEntityInstance* pActivator, CEntityInstance* pCaller, const CVariant* const value, float flDelay); static FireOutputInternal m_pFireOutputInternal = nullptr; // Do it in here because i didn't found a good place to do this -inline void (*CEntityInstance_AcceptInput)(CEntityInstance* pThis, const char* pInputName, CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, int nOutputID); +inline void (*CEntityInstance_AcceptInput)( + CEntityInstance* pThis, const char* pInputName, CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, int nOutputID); inline void (*CEntitySystem_AddEntityIOEvent)(CEntitySystem* pEntitySystem, CEntityInstance* pTarget, @@ -142,66 +153,53 @@ typedef uint32 SoundEventGuid_t; enum gender_t : uint8 { - GENDER_NONE = 0x0, - GENDER_MALE = 0x1, - GENDER_FEMALE = 0x2, - GENDER_NAMVET = 0x3, - GENDER_TEENGIRL = 0x4, - GENDER_BIKER = 0x5, - GENDER_MANAGER = 0x6, - GENDER_GAMBLER = 0x7, - GENDER_PRODUCER = 0x8, - GENDER_COACH = 0x9, - GENDER_MECHANIC = 0xA, - GENDER_CEDA = 0xB, - GENDER_CRAWLER = 0xC, - GENDER_UNDISTRACTABLE = 0xD, - GENDER_FALLEN = 0xE, - GENDER_RIOT_CONTROL = 0xF, - GENDER_CLOWN = 0x10, - GENDER_JIMMY = 0x11, - GENDER_HOSPITAL_PATIENT = 0x12, - GENDER_BRIDE = 0x13, - GENDER_LAST = 0x14, + GENDER_NONE = 0x0, + GENDER_MALE = 0x1, + GENDER_FEMALE = 0x2, + GENDER_NAMVET = 0x3, + GENDER_TEENGIRL = 0x4, + GENDER_BIKER = 0x5, + GENDER_MANAGER = 0x6, + GENDER_GAMBLER = 0x7, + GENDER_PRODUCER = 0x8, + GENDER_COACH = 0x9, + GENDER_MECHANIC = 0xA, + GENDER_CEDA = 0xB, + GENDER_CRAWLER = 0xC, + GENDER_UNDISTRACTABLE = 0xD, + GENDER_FALLEN = 0xE, + GENDER_RIOT_CONTROL = 0xF, + GENDER_CLOWN = 0x10, + GENDER_JIMMY = 0x11, + GENDER_HOSPITAL_PATIENT = 0x12, + GENDER_BRIDE = 0x13, + GENDER_LAST = 0x14, }; struct EmitSound_t { - EmitSound_t() : - m_nChannel(0), - m_pSoundName(0), - m_flVolume(VOL_NORM), - m_SoundLevel(SNDLVL_NONE), - m_nFlags(0), - m_nPitch(PITCH_NORM), - m_pOrigin(0), - m_flSoundTime(0.0f), - m_pflSoundDuration(0), - m_bEmitCloseCaption(true), - m_bWarnOnMissingCloseCaption(false), - m_bWarnOnDirectWaveReference(false), - m_nSpeakerEntity(-1), - m_UtlVecSoundOrigin(), - m_nForceGuid(0), - m_SpeakerGender(GENDER_NONE) - { - } - int m_nChannel; - const char* m_pSoundName; - float m_flVolume; - soundlevel_t m_SoundLevel; - int m_nFlags; - int m_nPitch; - const Vector* m_pOrigin; - float m_flSoundTime; - float* m_pflSoundDuration; - bool m_bEmitCloseCaption; - bool m_bWarnOnMissingCloseCaption; - bool m_bWarnOnDirectWaveReference; - CEntityIndex m_nSpeakerEntity; - CUtlVector > m_UtlVecSoundOrigin; - SoundEventGuid_t m_nForceGuid; - gender_t m_SpeakerGender; + EmitSound_t() + : m_nChannel(0), m_pSoundName(0), m_flVolume(VOL_NORM), m_SoundLevel(SNDLVL_NONE), m_nFlags(0), m_nPitch(PITCH_NORM), m_pOrigin(0), + m_flSoundTime(0.0f), m_pflSoundDuration(0), m_bEmitCloseCaption(true), m_bWarnOnMissingCloseCaption(false), + m_bWarnOnDirectWaveReference(false), m_nSpeakerEntity(-1), m_UtlVecSoundOrigin(), m_nForceGuid(0), m_SpeakerGender(GENDER_NONE) + { + } + int m_nChannel; + const char* m_pSoundName; + float m_flVolume; + soundlevel_t m_SoundLevel; + int m_nFlags; + int m_nPitch; + const Vector* m_pOrigin; + float m_flSoundTime; + float* m_pflSoundDuration; + bool m_bEmitCloseCaption; + bool m_bWarnOnMissingCloseCaption; + bool m_bWarnOnDirectWaveReference; + CEntityIndex m_nSpeakerEntity; + CUtlVector> m_UtlVecSoundOrigin; + SoundEventGuid_t m_nForceGuid; + gender_t m_SpeakerGender; }; struct SndOpEventGuid_t @@ -212,5 +210,6 @@ struct SndOpEventGuid_t inline SndOpEventGuid_t(FASTCALL* CBaseEntity_EmitSoundFilter)(IRecipientFilter& filter, CEntityIndex ent, const EmitSound_t& params); -SndOpEventGuid_t EntityEmitSoundFilter(IRecipientFilter& filter, uint32 ent, const char* pszSound, float flVolume = 1.0f, float flPitch = 1.0f); -} // namespace counterstrikesharp +SndOpEventGuid_t +EntityEmitSoundFilter(IRecipientFilter& filter, uint32 ent, const char* pszSound, float flVolume = 1.0f, float flPitch = 1.0f); +} // namespace counterstrikesharp diff --git a/src/core/managers/player_manager.cpp b/src/core/managers/player_manager.cpp index 69d6a443..5260647c 100644 --- a/src/core/managers/player_manager.cpp +++ b/src/core/managers/player_manager.cpp @@ -44,19 +44,15 @@ #include // extern CEntitySystem *g_pEntitySystem; -SH_DECL_HOOK4_void(IServerGameClients, ClientActive, SH_NOATTRIB, 0, CPlayerSlot, bool, const char*, - uint64); -SH_DECL_HOOK5_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, CPlayerSlot, - ENetworkDisconnectionReason, const char*, uint64, const char*); +SH_DECL_HOOK4_void(IServerGameClients, ClientActive, SH_NOATTRIB, 0, CPlayerSlot, bool, const char*, uint64); +SH_DECL_HOOK5_void( + IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, CPlayerSlot, ENetworkDisconnectionReason, const char*, uint64, const char*); SH_DECL_HOOK1_void(IServerGameClients, ClientVoice, SH_NOATTRIB, 0, CPlayerSlot); -SH_DECL_HOOK4_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, CPlayerSlot, char const*, - int, uint64); +SH_DECL_HOOK4_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, CPlayerSlot, char const*, int, uint64); SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, CPlayerSlot); -SH_DECL_HOOK6_void(IServerGameClients, OnClientConnected, SH_NOATTRIB, 0, CPlayerSlot, const char*, - uint64, const char*, const char*, bool); -SH_DECL_HOOK6(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, CPlayerSlot, const char*, - uint64, const char*, bool, CBufferString*); +SH_DECL_HOOK6_void(IServerGameClients, OnClientConnected, SH_NOATTRIB, 0, CPlayerSlot, const char*, uint64, const char*, const char*, bool); +SH_DECL_HOOK6(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, CPlayerSlot, const char*, uint64, const char*, bool, CBufferString*); SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, CPlayerSlot, const CCommand&); @@ -66,48 +62,39 @@ void PlayerManager::OnStartup() {} void PlayerManager::OnAllInitialized() { - SH_ADD_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientConnect), false); - SH_ADD_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true); - SH_ADD_HOOK(IServerGameClients, ClientPutInServer, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true); - SH_ADD_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false); - SH_ADD_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true); - SH_ADD_HOOK(IServerGameClients, ClientCommand, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientCommand), false); - SH_ADD_HOOK(IServerGameClients, ClientVoice, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientVoice), true); + SH_ADD_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false); + SH_ADD_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true); + SH_ADD_HOOK(IServerGameClients, ClientPutInServer, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), + true); + SH_ADD_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), + false); + SH_ADD_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), + true); + SH_ADD_HOOK(IServerGameClients, ClientCommand, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false); + SH_ADD_HOOK(IServerGameClients, ClientVoice, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientVoice), true); m_on_client_connect_callback = globals::callbackManager.CreateCallback("OnClientConnect"); m_on_client_connected_callback = globals::callbackManager.CreateCallback("OnClientConnected"); - m_on_client_put_in_server_callback = - globals::callbackManager.CreateCallback("OnClientPutInServer"); + m_on_client_put_in_server_callback = globals::callbackManager.CreateCallback("OnClientPutInServer"); m_on_client_disconnect_callback = globals::callbackManager.CreateCallback("OnClientDisconnect"); - m_on_client_disconnect_post_callback = - globals::callbackManager.CreateCallback("OnClientDisconnectPost"); + m_on_client_disconnect_post_callback = globals::callbackManager.CreateCallback("OnClientDisconnectPost"); m_on_client_voice_callback = globals::callbackManager.CreateCallback("OnClientVoice"); m_on_client_authorized_callback = globals::callbackManager.CreateCallback("OnClientAuthorized"); } void PlayerManager::OnShutdown() { - SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientConnect), false); - SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true); - SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true); - SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false); + SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false); + SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), + true); + SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), + true); + SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), + false); SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true); - SH_REMOVE_HOOK(IServerGameClients, ClientCommand, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientCommand), false); - SH_REMOVE_HOOK(IServerGameClients, ClientVoice, globals::serverGameClients, - SH_MEMBER(this, &PlayerManager::OnClientVoice), true); + SH_REMOVE_HOOK(IServerGameClients, ClientCommand, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false); + SH_REMOVE_HOOK(IServerGameClients, ClientVoice, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientVoice), true); globals::callbackManager.ReleaseCallback(m_on_client_connect_callback); globals::callbackManager.ReleaseCallback(m_on_client_connected_callback); @@ -118,21 +105,18 @@ void PlayerManager::OnShutdown() globals::callbackManager.ReleaseCallback(m_on_client_voice_callback); } -bool PlayerManager::OnClientConnect(CPlayerSlot slot, const char* pszName, uint64 xuid, - const char* pszNetworkID, bool unk1, - CBufferString* pRejectReason) +bool PlayerManager::OnClientConnect( + CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason) { - CSSHARP_CORE_TRACE("[PlayerManager][OnClientConnect] - {}, {}, {}", slot.Get(), pszName, - pszNetworkID); + CSSHARP_CORE_TRACE("[PlayerManager][OnClientConnect] - {}, {}, {}", slot.Get(), pszName, pszNetworkID); int client = slot.Get(); CPlayer* pPlayer = &m_players[client]; - if (pPlayer->IsConnected()) { - OnClientDisconnect(slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, pszName, - xuid, pszNetworkID); - OnClientDisconnect_Post(slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, - pszName, xuid, pszNetworkID); + if (pPlayer->IsConnected()) + { + OnClientDisconnect(slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, pszName, xuid, pszNetworkID); + OnClientDisconnect_Post(slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, pszName, xuid, pszNetworkID); } pPlayer->Initialize(pszName, pszNetworkID, slot); @@ -143,7 +127,8 @@ bool PlayerManager::OnClientConnect(CPlayerSlot slot, const char* pszName, uint6 m_on_client_connect_callback->ScriptContext().Push(pszNetworkID); m_on_client_connect_callback->Execute(); - if (m_on_client_connect_callback->GetFunctionCount() > 0) { + if (m_on_client_connect_callback->GetFunctionCount() > 0) + { // auto cancel = m_on_client_connect_callback->ScriptContext().GetArgument(0); // auto cancelReason = // m_on_client_connect_callback->ScriptContext().GetArgument(1); @@ -167,47 +152,47 @@ bool PlayerManager::OnClientConnect(CPlayerSlot slot, const char* pszName, uint6 return true; } -bool PlayerManager::OnClientConnect_Post(CPlayerSlot slot, const char* pszName, uint64 xuid, - const char* pszNetworkID, bool unk1, - CBufferString* pRejectReason) +bool PlayerManager::OnClientConnect_Post( + CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason) { - CSSHARP_CORE_TRACE("[PlayerManager][OnClientConnect_Post] - {}, {}, {}", slot.Get(), pszName, - pszNetworkID); + CSSHARP_CORE_TRACE("[PlayerManager][OnClientConnect_Post] - {}, {}, {}", slot.Get(), pszName, pszNetworkID); int client = slot.Get(); bool orig_value = META_RESULT_ORIG_RET(bool); CPlayer* pPlayer = &m_players[client]; - if (orig_value) { + if (orig_value) + { m_on_client_connected_callback->ScriptContext().Reset(); m_on_client_connected_callback->ScriptContext().Push(pPlayer->m_slot.Get()); m_on_client_connected_callback->Execute(); - if (!pPlayer->IsFakeClient() && m_is_listen_server && - strncmp(pszNetworkID, "127.0.0.1", 9) == 0) { + if (!pPlayer->IsFakeClient() && m_is_listen_server && strncmp(pszNetworkID, "127.0.0.1", 9) == 0) + { m_listen_client = client; } - } else { + } + else + { InvalidatePlayer(pPlayer); } return true; } -void PlayerManager::OnClientPutInServer(CPlayerSlot slot, char const* pszName, int type, - uint64 xuid) +void PlayerManager::OnClientPutInServer(CPlayerSlot slot, char const* pszName, int type, uint64 xuid) { - CSSHARP_CORE_TRACE("[PlayerManager][OnClientPutInServer] - {}, {}, {}", slot.Get(), pszName, - type); + CSSHARP_CORE_TRACE("[PlayerManager][OnClientPutInServer] - {}, {}, {}", slot.Get(), pszName, type); int client = slot.Get(); CPlayer* pPlayer = &m_players[client]; - if (!pPlayer->IsConnected()) { + if (!pPlayer->IsConnected()) + { pPlayer->m_is_fake_client = true; - if (!OnClientConnect(slot, pszName, 0, "127.0.0.1", false, - new CBufferStringGrowable<255>())) { + if (!OnClientConnect(slot, pszName, 0, "127.0.0.1", false, new CBufferStringGrowable<255>())) + { /* :TODO: kick the bot if it's rejected */ return; } @@ -233,39 +218,39 @@ void PlayerManager::OnClientPutInServer(CPlayerSlot slot, char const* pszName, i m_on_client_put_in_server_callback->Execute(); } -void PlayerManager::OnClientDisconnect(CPlayerSlot slot, ENetworkDisconnectionReason reason, - const char* pszName, uint64 xuid, const char* pszNetworkID) +void PlayerManager::OnClientDisconnect( + CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID) { - CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect] - {}, {}, {}", slot.Get(), pszName, - pszNetworkID); + CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect] - {}, {}, {}", slot.Get(), pszName, pszNetworkID); int client = slot.Get(); CPlayer* pPlayer = &m_players[client]; - if (pPlayer->IsConnected()) { + if (pPlayer->IsConnected()) + { m_on_client_disconnect_callback->ScriptContext().Reset(); m_on_client_disconnect_callback->ScriptContext().Push(pPlayer->m_slot.Get()); m_on_client_disconnect_callback->ScriptContext().Push(reason); m_on_client_disconnect_callback->Execute(); } - if (pPlayer->WasCountedAsInGame()) { + if (pPlayer->WasCountedAsInGame()) + { m_player_count--; } // globals::entityListener.HandleEntityDeleted(pPlayer->GetBaseEntity(), client); } -void PlayerManager::OnClientDisconnect_Post(CPlayerSlot slot, ENetworkDisconnectionReason reason, - const char* pszName, uint64 xuid, - const char* pszNetworkID) const +void PlayerManager::OnClientDisconnect_Post( + CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID) const { - CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect_Post] - {}, {}, {}", slot.Get(), pszName, - pszNetworkID); + CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect_Post] - {}, {}, {}", slot.Get(), pszName, pszNetworkID); int client = slot.Get(); CPlayer* pPlayer = &m_players[client]; - if (!pPlayer->IsConnected()) { + if (!pPlayer->IsConnected()) + { /* We don't care, prevent a double call */ return; } @@ -291,14 +276,14 @@ void PlayerManager::OnLevelEnd() { CSSHARP_CORE_TRACE("[PlayerManager][OnLevelEnd]"); - for (int i = 0; i <= MaxClients(); i++) { - if (m_players[i].IsConnected()) { - OnClientDisconnect(m_players[i].m_slot, - ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, - m_players[i].GetName(), 0, m_players[i].GetIpAddress()); - OnClientDisconnect_Post(m_players[i].m_slot, - ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, - m_players[i].GetName(), 0, m_players[i].GetIpAddress()); + for (int i = 0; i <= MaxClients(); i++) + { + if (m_players[i].IsConnected()) + { + OnClientDisconnect(m_players[i].m_slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, m_players[i].GetName(), 0, + m_players[i].GetIpAddress()); + OnClientDisconnect_Post(m_players[i].m_slot, ENetworkDisconnectionReason::NETWORK_DISCONNECT_INVALID, m_players[i].GetName(), 0, + m_players[i].GetIpAddress()); } } m_player_count = 0; @@ -306,17 +291,17 @@ void PlayerManager::OnLevelEnd() void PlayerManager::OnClientCommand(CPlayerSlot slot, const CCommand& args) const { - CSSHARP_CORE_TRACE("[PlayerManager][OnClientCommand] - {}, {}, {}", slot.Get(), args.Arg(0), - (void*)&args); + CSSHARP_CORE_TRACE("[PlayerManager][OnClientCommand] - {}, {}, {}", slot.Get(), args.Arg(0), (void*)&args); const char* cmd = args.Arg(0); globals::voiceManager.OnClientCommand(slot, args); - auto result = globals::conCommandManager.ExecuteCommandCallbacks( - cmd, CCommandContext(CommandTarget_t::CT_NO_TARGET, slot), args, HookMode::Pre, CommandCallingContext::Console); + auto result = globals::conCommandManager.ExecuteCommandCallbacks(cmd, CCommandContext(CommandTarget_t::CT_NO_TARGET, slot), args, + HookMode::Pre, CommandCallingContext::Console); - if (result >= HookResult::Handled) { + if (result >= HookResult::Handled) + { RETURN_META(MRES_SUPERCEDE); } } @@ -329,7 +314,8 @@ int PlayerManager::MaxClients() const { return globals::getGlobalVars()->maxClie CPlayer* PlayerManager::GetPlayerBySlot(int client) const { - if (client > MaxClients() || client < 0) { + if (client > MaxClients() || client < 0) + { return nullptr; } @@ -378,8 +364,7 @@ CPlayer* PlayerManager::GetPlayerBySlot(int client) const void PlayerManager::InvalidatePlayer(CPlayer* pPlayer) const { auto userid = globals::engine->GetPlayerUserId(pPlayer->m_slot); - if (userid.Get() != -1) - m_user_id_lookup[userid.Get()] = 0; + if (userid.Get() != -1) m_user_id_lookup[userid.Get()] = 0; pPlayer->Disconnect(); } @@ -406,7 +391,8 @@ bool CPlayer::IsAuthorized() const { return m_is_authorized; } bool CPlayer::IsAuthStringValidated() const { - if (!IsFakeClient()) { + if (!IsFakeClient()) + { return globals::engine->IsClientFullyAuthenticated(m_slot); } return false; @@ -416,12 +402,14 @@ void CPlayer::Authorize() { m_is_authorized = true; } void CPlayer::PrintToConsole(const char* message) const { - if (m_is_connected == false || m_is_fake_client == true) { + if (m_is_connected == false || m_is_fake_client == true) + { return; } INetChannelInfo* pNetChan = globals::engine->GetPlayerNetInfo(m_slot); - if (pNetChan == nullptr) { + if (pNetChan == nullptr) + { return; } @@ -457,18 +445,21 @@ PlayerManager::PlayerManager() void PlayerManager::RunAuthChecks() { - if (globals::timerSystem.GetTickedTime() - m_last_auth_check_time < 0.5F) { + if (globals::timerSystem.GetTickedTime() - m_last_auth_check_time < 0.5F) + { return; } m_last_auth_check_time = globals::timerSystem.GetTickedTime(); - for (int i = 0; i <= MaxClients(); i++) { - if (m_players[i].IsConnected()) { - if (m_players[i].IsAuthorized() || m_players[i].IsFakeClient()) - continue; + for (int i = 0; i <= MaxClients(); i++) + { + if (m_players[i].IsConnected()) + { + if (m_players[i].IsAuthorized() || m_players[i].IsFakeClient()) continue; - if (globals::engine->IsClientFullyAuthenticated(i)) { + if (globals::engine->IsClientFullyAuthenticated(i)) + { m_players[i].Authorize(); m_players[i].SetSteamId(globals::engine->GetClientSteamID(i)); OnAuthorized(&m_players[i]); @@ -479,8 +470,7 @@ void PlayerManager::RunAuthChecks() void PlayerManager::OnAuthorized(CPlayer* player) const { - CSSHARP_CORE_TRACE("[PlayerManager][OnAuthorized] - {} {}", player->GetName(), - player->GetSteamId()->ConvertToUint64()); + CSSHARP_CORE_TRACE("[PlayerManager][OnAuthorized] - {} {}", player->GetName(), player->GetSteamId()->ConvertToUint64()); m_on_client_authorized_callback->ScriptContext().Reset(); m_on_client_authorized_callback->ScriptContext().Push(player->m_slot.Get()); @@ -492,7 +482,8 @@ bool CPlayer::WasCountedAsInGame() const { return m_is_in_game; } int CPlayer::GetUserId() { - if (m_user_id == -1) { + if (m_user_id == -1) + { m_user_id = globals::engine->GetPlayerUserId(m_slot).Get(); } @@ -523,10 +514,7 @@ int CPlayer::GetFrags() const { return m_info->GetFragCount(); } int CPlayer::GetDeaths() const { return m_info->GetDeathCount(); } -const char* CPlayer::GetKeyValue(const char* key) const -{ - return globals::engine->GetClientConVarValue(m_slot, key); -} +const char* CPlayer::GetKeyValue(const char* key) const { return globals::engine->GetClientConVarValue(m_slot, key); } Vector CPlayer::GetMaxSize() const { return m_info->GetPlayerMaxs(); } @@ -542,17 +530,15 @@ int CPlayer::GetUserId() const { return m_user_id; } float CPlayer::GetTimeConnected() const { - if (!IsConnected() || IsFakeClient()) { + if (!IsConnected() || IsFakeClient()) + { return 0; } return GetNetInfo()->GetTimeConnected(); } -void CPlayer::SetListen(CPlayerSlot slot, ListenOverride listen) -{ - m_listenMap[slot.Get()] = listen; -} +void CPlayer::SetListen(CPlayerSlot slot, ListenOverride listen) { m_listenMap[slot.Get()] = listen; } void CPlayer::SetVoiceFlags(VoiceFlag_t flags) { m_voiceFlag = flags; } @@ -562,7 +548,8 @@ ListenOverride CPlayer::GetListen(CPlayerSlot slot) const { return m_listenMap[s void CPlayer::Connect() { - if (m_is_in_game) { + if (m_is_in_game) + { return; } @@ -590,7 +577,8 @@ Vector CPlayer::GetAbsOrigin() const { return m_info->GetAbsOrigin(); } bool CPlayer::IsAlive() const { - if (!IsInGame()) { + if (!IsInGame()) + { return false; } @@ -599,4 +587,4 @@ bool CPlayer::IsAlive() const const CSteamID* CPlayer::GetSteamId() { return m_steamId; } void CPlayer::SetSteamId(const CSteamID* steam_id) { m_steamId = steam_id; } -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp diff --git a/src/core/managers/player_manager.h b/src/core/managers/player_manager.h index 25d0ae9a..19a39fda 100644 --- a/src/core/managers/player_manager.h +++ b/src/core/managers/player_manager.h @@ -143,15 +143,15 @@ class PlayerManager : public GlobalClass PlayerManager(); void OnStartup() override; void OnAllInitialized() override; - bool OnClientConnect(CPlayerSlot slot, const char* pszName, uint64 xuid, - const char* pszNetworkID, bool unk1, CBufferString* pRejectReason); - bool OnClientConnect_Post(CPlayerSlot slot, const char* pszName, uint64 xuid, - const char* pszNetworkID, bool unk1, CBufferString* pRejectReason); + bool + OnClientConnect(CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason); + bool OnClientConnect_Post( + CPlayerSlot slot, const char* pszName, uint64 xuid, const char* pszNetworkID, bool unk1, CBufferString* pRejectReason); void OnClientPutInServer(CPlayerSlot slot, char const* pszName, int type, uint64 xuid); - void OnClientDisconnect(CPlayerSlot slot, ENetworkDisconnectionReason reason, - const char* pszName, uint64 xuid, const char* pszNetworkID); - void OnClientDisconnect_Post(CPlayerSlot slot, ENetworkDisconnectionReason reason, - const char* pszName, uint64 xuid, const char* pszNetworkID) const; + void + OnClientDisconnect(CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID); + void OnClientDisconnect_Post( + CPlayerSlot slot, ENetworkDisconnectionReason reason, const char* pszName, uint64 xuid, const char* pszNetworkID) const; void OnClientVoice(CPlayerSlot slot) const; void OnAuthorized(CPlayer* player) const; void OnServerActivate(edict_t* pEdictList, int edictCount, int clientMax) const; @@ -188,4 +188,4 @@ class PlayerManager : public GlobalClass ScriptCallback* m_on_client_authorized_callback; }; -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp diff --git a/src/core/managers/server_manager.cpp b/src/core/managers/server_manager.cpp index f52b4ecc..47004200 100644 --- a/src/core/managers/server_manager.cpp +++ b/src/core/managers/server_manager.cpp @@ -1,18 +1,18 @@ /* -* This file is part of CounterStrikeSharp. -* CounterStrikeSharp is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* CounterStrikeSharp is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with CounterStrikeSharp. If not, see . * -*/ + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ #include "core/managers/server_manager.h" @@ -36,21 +36,17 @@ ServerManager::ServerManager() = default; ServerManager::~ServerManager() = default; -void ServerManager::OnAllInitialized() { - SH_ADD_HOOK(ISource2Server, ServerHibernationUpdate, globals::server, - SH_MEMBER(this, &ServerManager::ServerHibernationUpdate), true); - SH_ADD_HOOK(ISource2Server, GameServerSteamAPIActivated, globals::server, - SH_MEMBER(this, &ServerManager::GameServerSteamAPIActivated), true); +void ServerManager::OnAllInitialized() +{ + SH_ADD_HOOK(ISource2Server, ServerHibernationUpdate, globals::server, SH_MEMBER(this, &ServerManager::ServerHibernationUpdate), true); + SH_ADD_HOOK(ISource2Server, GameServerSteamAPIActivated, globals::server, SH_MEMBER(this, &ServerManager::GameServerSteamAPIActivated), + true); SH_ADD_HOOK(ISource2Server, GameServerSteamAPIDeactivated, globals::server, SH_MEMBER(this, &ServerManager::GameServerSteamAPIDeactivated), true); - SH_ADD_HOOK(ISource2Server, OnHostNameChanged, globals::server, - SH_MEMBER(this, &ServerManager::OnHostNameChanged), true); - SH_ADD_HOOK(ISource2Server, PreFatalShutdown, globals::server, - SH_MEMBER(this, &ServerManager::PreFatalShutdown), true); - SH_ADD_HOOK(ISource2Server, UpdateWhenNotInGame, globals::server, - SH_MEMBER(this, &ServerManager::UpdateWhenNotInGame), true); - SH_ADD_HOOK(ISource2Server, PreWorldUpdate, globals::server, - SH_MEMBER(this, &ServerManager::PreWorldUpdate), true); + SH_ADD_HOOK(ISource2Server, OnHostNameChanged, globals::server, SH_MEMBER(this, &ServerManager::OnHostNameChanged), true); + SH_ADD_HOOK(ISource2Server, PreFatalShutdown, globals::server, SH_MEMBER(this, &ServerManager::PreFatalShutdown), true); + SH_ADD_HOOK(ISource2Server, UpdateWhenNotInGame, globals::server, SH_MEMBER(this, &ServerManager::UpdateWhenNotInGame), true); + SH_ADD_HOOK(ISource2Server, PreWorldUpdate, globals::server, SH_MEMBER(this, &ServerManager::PreWorldUpdate), true); on_server_hibernation_update_callback = globals::callbackManager.CreateCallback("OnServerHibernationUpdate"); on_server_steam_api_activated_callback = globals::callbackManager.CreateCallback("OnGameServerSteamAPIActivated"); @@ -63,21 +59,18 @@ void ServerManager::OnAllInitialized() { on_server_precache_resources = globals::callbackManager.CreateCallback("OnServerPrecacheResources"); } -void ServerManager::OnShutdown() { - SH_REMOVE_HOOK(ISource2Server, ServerHibernationUpdate, globals::server, - SH_MEMBER(this, &ServerManager::ServerHibernationUpdate), true); +void ServerManager::OnShutdown() +{ + SH_REMOVE_HOOK(ISource2Server, ServerHibernationUpdate, globals::server, SH_MEMBER(this, &ServerManager::ServerHibernationUpdate), + true); SH_REMOVE_HOOK(ISource2Server, GameServerSteamAPIActivated, globals::server, - SH_MEMBER(this, &ServerManager::GameServerSteamAPIActivated), true); + SH_MEMBER(this, &ServerManager::GameServerSteamAPIActivated), true); SH_REMOVE_HOOK(ISource2Server, GameServerSteamAPIDeactivated, globals::server, - SH_MEMBER(this, &ServerManager::GameServerSteamAPIDeactivated), true); - SH_REMOVE_HOOK(ISource2Server, OnHostNameChanged, globals::server, - SH_MEMBER(this, &ServerManager::OnHostNameChanged), true); - SH_REMOVE_HOOK(ISource2Server, PreFatalShutdown, globals::server, - SH_MEMBER(this, &ServerManager::PreFatalShutdown), true); - SH_REMOVE_HOOK(ISource2Server, UpdateWhenNotInGame, globals::server, - SH_MEMBER(this, &ServerManager::UpdateWhenNotInGame), true); - SH_REMOVE_HOOK(ISource2Server, PreWorldUpdate, globals::server, - SH_MEMBER(this, &ServerManager::PreWorldUpdate), true); + SH_MEMBER(this, &ServerManager::GameServerSteamAPIDeactivated), true); + SH_REMOVE_HOOK(ISource2Server, OnHostNameChanged, globals::server, SH_MEMBER(this, &ServerManager::OnHostNameChanged), true); + SH_REMOVE_HOOK(ISource2Server, PreFatalShutdown, globals::server, SH_MEMBER(this, &ServerManager::PreFatalShutdown), true); + SH_REMOVE_HOOK(ISource2Server, UpdateWhenNotInGame, globals::server, SH_MEMBER(this, &ServerManager::UpdateWhenNotInGame), true); + SH_REMOVE_HOOK(ISource2Server, PreWorldUpdate, globals::server, SH_MEMBER(this, &ServerManager::PreWorldUpdate), true); globals::callbackManager.ReleaseCallback(on_server_hibernation_update_callback); globals::callbackManager.ReleaseCallback(on_server_steam_api_activated_callback); @@ -86,19 +79,13 @@ void ServerManager::OnShutdown() { globals::callbackManager.ReleaseCallback(on_server_pre_fatal_shutdown); globals::callbackManager.ReleaseCallback(on_server_update_when_not_in_game); globals::callbackManager.ReleaseCallback(on_server_pre_world_update); - + globals::callbackManager.ReleaseCallback(on_server_precache_resources); } -void* ServerManager::GetEconItemSystem() -{ - return globals::server->GetEconItemSystem(); -} +void* ServerManager::GetEconItemSystem() { return globals::server->GetEconItemSystem(); } -bool ServerManager::IsPaused() -{ - return globals::server->IsPaused(); -} +bool ServerManager::IsPaused() { return globals::server->IsPaused(); } void ServerManager::ServerHibernationUpdate(bool bHibernating) { @@ -106,7 +93,8 @@ void ServerManager::ServerHibernationUpdate(bool bHibernating) auto callback = globals::serverManager.on_server_hibernation_update_callback; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->ScriptContext().Push(bHibernating); callback->Execute(); @@ -119,7 +107,8 @@ void ServerManager::GameServerSteamAPIActivated() auto callback = globals::serverManager.on_server_steam_api_activated_callback; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->Execute(); } @@ -131,19 +120,21 @@ void ServerManager::GameServerSteamAPIDeactivated() auto callback = globals::serverManager.on_server_steam_api_deactivated_callback; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->Execute(); } } -void ServerManager::OnHostNameChanged(const char *pHostname) +void ServerManager::OnHostNameChanged(const char* pHostname) { CSSHARP_CORE_TRACE("Server hostname changed {0}", pHostname); auto callback = globals::serverManager.on_server_hostname_changed_callback; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->ScriptContext().Push(pHostname); callback->Execute(); @@ -156,7 +147,8 @@ void ServerManager::PreFatalShutdown() auto callback = globals::serverManager.on_server_pre_fatal_shutdown; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->Execute(); } @@ -168,7 +160,8 @@ void ServerManager::UpdateWhenNotInGame(float flFrameTime) auto callback = globals::serverManager.on_server_update_when_not_in_game; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->ScriptContext().Push(flFrameTime); callback->Execute(); @@ -181,18 +174,20 @@ void ServerManager::PreWorldUpdate(bool bSimulating) auto size = m_nextWorldUpdateTasks.try_dequeue_bulk(out_list.begin(), 1024); - if (size > 0) { - CSSHARP_CORE_TRACE("Executing queued tasks of size: {0} at time {1}", size, - globals::getGlobalVars()->curtime); + if (size > 0) + { + CSSHARP_CORE_TRACE("Executing queued tasks of size: {0} at time {1}", size, globals::getGlobalVars()->curtime); - for (size_t i = 0; i < size; i++) { + for (size_t i = 0; i < size; i++) + { out_list[i](); } } auto callback = globals::serverManager.on_server_pre_world_update; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->ScriptContext().Push(bSimulating); callback->Execute(); @@ -208,11 +203,12 @@ void ServerManager::OnPrecacheResources(IEntityResourceManifest* pResourceManife { CSSHARP_CORE_TRACE("Precache resources"); auto callback = globals::serverManager.on_server_precache_resources; - if (callback && callback->GetFunctionCount()) { + if (callback && callback->GetFunctionCount()) + { callback->ScriptContext().Reset(); callback->ScriptContext().Push(pResourceManifest); callback->Execute(); } } -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp diff --git a/src/core/managers/server_manager.h b/src/core/managers/server_manager.h index 6f37cef9..44bad65b 100644 --- a/src/core/managers/server_manager.h +++ b/src/core/managers/server_manager.h @@ -1,18 +1,18 @@ /* -* This file is part of CounterStrikeSharp. -* CounterStrikeSharp is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* CounterStrikeSharp is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with CounterStrikeSharp. If not, see . * -*/ + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ #pragma once @@ -26,8 +26,9 @@ namespace counterstrikesharp { class ScriptCallback; -class ServerManager : public GlobalClass { -public: +class ServerManager : public GlobalClass +{ + public: ServerManager(); ~ServerManager(); void OnAllInitialized() override; @@ -37,27 +38,26 @@ public: void AddTaskForNextWorldUpdate(std::function&& task); void OnPrecacheResources(IEntityResourceManifest* pResourceManifest); -private: + private: void ServerHibernationUpdate(bool bHibernating); void GameServerSteamAPIActivated(); void GameServerSteamAPIDeactivated(); - void OnHostNameChanged(const char *pHostname); + void OnHostNameChanged(const char* pHostname); void PreFatalShutdown(); void UpdateWhenNotInGame(float flFrameTime); void PreWorldUpdate(bool bSimulating); + ScriptCallback* on_server_hibernation_update_callback; + ScriptCallback* on_server_steam_api_activated_callback; + ScriptCallback* on_server_steam_api_deactivated_callback; + ScriptCallback* on_server_hostname_changed_callback; + ScriptCallback* on_server_pre_fatal_shutdown; + ScriptCallback* on_server_update_when_not_in_game; + ScriptCallback* on_server_pre_world_update; - ScriptCallback *on_server_hibernation_update_callback; - ScriptCallback *on_server_steam_api_activated_callback; - ScriptCallback *on_server_steam_api_deactivated_callback; - ScriptCallback *on_server_hostname_changed_callback; - ScriptCallback *on_server_pre_fatal_shutdown; - ScriptCallback *on_server_update_when_not_in_game; - ScriptCallback *on_server_pre_world_update; - - ScriptCallback *on_server_precache_resources; + ScriptCallback* on_server_precache_resources; moodycamel::ConcurrentQueue> m_nextWorldUpdateTasks; }; -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp diff --git a/src/core/managers/voice_manager.h b/src/core/managers/voice_manager.h index c94baae7..15a54c85 100644 --- a/src/core/managers/voice_manager.h +++ b/src/core/managers/voice_manager.h @@ -32,7 +32,8 @@ class VoiceManager : public GlobalClass void OnShutdown() override; bool SetClientListening(CPlayerSlot iReceiver, CPlayerSlot iSender, bool bListen); void OnClientCommand(CPlayerSlot slot, const CCommand& args); + private: }; -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp diff --git a/src/core/memory.cpp b/src/core/memory.cpp index 1b027aa4..da355d9b 100644 --- a/src/core/memory.cpp +++ b/src/core/memory.cpp @@ -22,9 +22,11 @@ #include "gameconfig.h" #include "memory_module.h" -void* FindSignature(const char* moduleName, const char* bytesStr) { +void* FindSignature(const char* moduleName, const char* bytesStr) +{ auto module = counterstrikesharp::modules::GetModuleByName(moduleName); - if (module == nullptr) { + if (module == nullptr) + { return nullptr; } diff --git a/src/core/memory.h b/src/core/memory.h index 3f306763..85ab38a6 100644 --- a/src/core/memory.h +++ b/src/core/memory.h @@ -1,15 +1,15 @@ #pragma once #ifdef _WIN32 - #define ROOTBIN "/bin/win64/" - #define GAMEBIN "/csgo/bin/win64/" +#define ROOTBIN "/bin/win64/" +#define GAMEBIN "/csgo/bin/win64/" #define MODULE_PREFIX "" -#define MODULE_EXT ".dll" +#define MODULE_EXT ".dll" #else - #define ROOTBIN "/bin/linuxsteamrt64/" - #define GAMEBIN "/csgo/bin/linuxsteamrt64/" +#define ROOTBIN "/bin/linuxsteamrt64/" +#define GAMEBIN "/csgo/bin/linuxsteamrt64/" #define MODULE_PREFIX "lib" -#define MODULE_EXT ".so" +#define MODULE_EXT ".so" #endif void* FindSignature(const char* moduleName, const char* bytesStr); diff --git a/src/core/memory_module.cpp b/src/core/memory_module.cpp index 08901064..98f70221 100644 --- a/src/core/memory_module.cpp +++ b/src/core/memory_module.cpp @@ -63,8 +63,7 @@ void Initialize() moduleList.emplace_back(std::move(mod)); } #else - dl_iterate_phdr( - [](struct dl_phdr_info* info, size_t, void*) { + dl_iterate_phdr([](struct dl_phdr_info* info, size_t, void*) { std::string name = info->dlpi_name; if (name.rfind(MODULE_EXT) != name.length() - strlen(MODULE_EXT)) return 0; @@ -80,8 +79,7 @@ void Initialize() moduleList.emplace_back(std::move(mod)); return 0; - }, - nullptr); + }, nullptr); #endif } diff --git a/src/core/memory_module.h b/src/core/memory_module.h index 7f339a1e..3d129552 100644 --- a/src/core/memory_module.h +++ b/src/core/memory_module.h @@ -77,8 +77,8 @@ class CModule std::uintptr_t m_baseAddress{}; std::unordered_map _symbols{}; std::unordered_map _interfaces{}; - using fnCreateInterface = void*(*)(const char*); - fnCreateInterface m_fnCreateInterface {}; + using fnCreateInterface = void* (*)(const char*); + fnCreateInterface m_fnCreateInterface{}; #ifdef _WIN32 void DumpSymbols(); @@ -86,7 +86,8 @@ class CModule void DumpSymbols(ElfW(Dyn) * dyn); #endif - std::optional> GetOriginalBytes(const std::vector& disk_data, std::uintptr_t rva, std::size_t size); + std::optional> + GetOriginalBytes(const std::vector& disk_data, std::uintptr_t rva, std::size_t size); void* FindSignature(const std::vector& sigBytes); }; diff --git a/src/core/recipientfilters.h b/src/core/recipientfilters.h index 131eda2c..b751ed01 100644 --- a/src/core/recipientfilters.h +++ b/src/core/recipientfilters.h @@ -1,84 +1,84 @@ -/* - * This file is part of CounterStrikeSharp. - * CounterStrikeSharp is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * CounterStrikeSharp is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with CounterStrikeSharp. If not, see . * - */ - -#include "irecipientfilter.h" - -class CSingleRecipientFilter : public IRecipientFilter -{ - public: - CSingleRecipientFilter(CPlayerSlot iRecipient, NetChannelBufType_t nBufType = BUF_RELIABLE, bool bInitMessage = false) - : m_iRecipient(iRecipient), m_nBufType(nBufType), m_bInitMessage(bInitMessage) - { - } - - ~CSingleRecipientFilter() override {} - - NetChannelBufType_t GetNetworkBufType(void) const override { return m_nBufType; } - bool IsInitMessage(void) const override { return m_bInitMessage; } - int GetRecipientCount(void) const override { return 1; } - CPlayerSlot GetRecipientIndex(int slot) const override { return m_iRecipient; } - - private: - CPlayerSlot m_iRecipient; - NetChannelBufType_t m_nBufType; - bool m_bInitMessage; -}; - -class CRecipientFilter : public IRecipientFilter -{ - public: - CRecipientFilter() - { - m_nBufType = BUF_RELIABLE; - m_bInitMessage = false; - } - - ~CRecipientFilter() override {} - - NetChannelBufType_t GetNetworkBufType(void) const override { return m_nBufType; } - bool IsInitMessage(void) const override { return m_bInitMessage; } - int GetRecipientCount(void) const override { return m_Recipients.Count(); } - - CPlayerSlot GetRecipientIndex(int slot) const override - { - if (slot < 0 || slot >= GetRecipientCount()) return CPlayerSlot(-1); - - return m_Recipients[slot]; - } - - void AddRecipient(CPlayerSlot slot) - { - if (m_Recipients.Find(slot) != m_Recipients.InvalidIndex()) return; - - m_Recipients.AddToTail(slot); - } - - void AddRecipientsFromMask(uint64 mask) - { - for (int i = 0; i < 64; ++i) - { - if (mask & (uint64)1 << i) - { - AddRecipient(CPlayerSlot(i)); - } - } - } - - private: - NetChannelBufType_t m_nBufType; - bool m_bInitMessage; - CUtlVectorFixed m_Recipients; -}; +/* + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ + +#include "irecipientfilter.h" + +class CSingleRecipientFilter : public IRecipientFilter +{ + public: + CSingleRecipientFilter(CPlayerSlot iRecipient, NetChannelBufType_t nBufType = BUF_RELIABLE, bool bInitMessage = false) + : m_iRecipient(iRecipient), m_nBufType(nBufType), m_bInitMessage(bInitMessage) + { + } + + ~CSingleRecipientFilter() override {} + + NetChannelBufType_t GetNetworkBufType(void) const override { return m_nBufType; } + bool IsInitMessage(void) const override { return m_bInitMessage; } + int GetRecipientCount(void) const override { return 1; } + CPlayerSlot GetRecipientIndex(int slot) const override { return m_iRecipient; } + + private: + CPlayerSlot m_iRecipient; + NetChannelBufType_t m_nBufType; + bool m_bInitMessage; +}; + +class CRecipientFilter : public IRecipientFilter +{ + public: + CRecipientFilter() + { + m_nBufType = BUF_RELIABLE; + m_bInitMessage = false; + } + + ~CRecipientFilter() override {} + + NetChannelBufType_t GetNetworkBufType(void) const override { return m_nBufType; } + bool IsInitMessage(void) const override { return m_bInitMessage; } + int GetRecipientCount(void) const override { return m_Recipients.Count(); } + + CPlayerSlot GetRecipientIndex(int slot) const override + { + if (slot < 0 || slot >= GetRecipientCount()) return CPlayerSlot(-1); + + return m_Recipients[slot]; + } + + void AddRecipient(CPlayerSlot slot) + { + if (m_Recipients.Find(slot) != m_Recipients.InvalidIndex()) return; + + m_Recipients.AddToTail(slot); + } + + void AddRecipientsFromMask(uint64 mask) + { + for (int i = 0; i < 64; ++i) + { + if (mask & (uint64)1 << i) + { + AddRecipient(CPlayerSlot(i)); + } + } + } + + private: + NetChannelBufType_t m_nBufType; + bool m_bInitMessage; + CUtlVectorFixed m_Recipients; +}; diff --git a/src/core/tick_scheduler.cpp b/src/core/tick_scheduler.cpp index b7f01136..df192926 100644 --- a/src/core/tick_scheduler.cpp +++ b/src/core/tick_scheduler.cpp @@ -1,45 +1,47 @@ -/* - * This file is part of CounterStrikeSharp. - * CounterStrikeSharp is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * CounterStrikeSharp is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with CounterStrikeSharp. If not, see . * - */ - -#include "tick_scheduler.h" - -namespace counterstrikesharp { - -void TickScheduler::schedule(int tick, std::function callback) -{ - std::lock_guard lock(taskMutex); - scheduledTasks.push(std::make_pair(tick, callback)); -} - -std::vector> TickScheduler::getCallbacks(int currentTick) -{ - std::vector> callbacksToRun; - - std::lock_guard lock(taskMutex); - - if (scheduledTasks.empty()) { - return callbacksToRun; - } - - // Process tasks due for the current tick - while (!scheduledTasks.empty() && scheduledTasks.top().first <= currentTick) { - callbacksToRun.push_back(scheduledTasks.top().second); - scheduledTasks.pop(); - } - - return callbacksToRun; -} -} // namespace counterstrikesharp \ No newline at end of file +/* + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ + +#include "tick_scheduler.h" + +namespace counterstrikesharp { + +void TickScheduler::schedule(int tick, std::function callback) +{ + std::lock_guard lock(taskMutex); + scheduledTasks.push(std::make_pair(tick, callback)); +} + +std::vector> TickScheduler::getCallbacks(int currentTick) +{ + std::vector> callbacksToRun; + + std::lock_guard lock(taskMutex); + + if (scheduledTasks.empty()) + { + return callbacksToRun; + } + + // Process tasks due for the current tick + while (!scheduledTasks.empty() && scheduledTasks.top().first <= currentTick) + { + callbacksToRun.push_back(scheduledTasks.top().second); + scheduledTasks.pop(); + } + + return callbacksToRun; +} +} // namespace counterstrikesharp diff --git a/src/core/tick_scheduler.h b/src/core/tick_scheduler.h index 027fafa5..7eaf25eb 100644 --- a/src/core/tick_scheduler.h +++ b/src/core/tick_scheduler.h @@ -1,44 +1,42 @@ -/* -* This file is part of CounterStrikeSharp. -* CounterStrikeSharp is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* CounterStrikeSharp is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with CounterStrikeSharp. If not, see . * -*/ - -#include -#include -#include -#include - -namespace counterstrikesharp { -class TickScheduler -{ - public: - struct TaskComparator - { - bool operator()(const std::pair>& a, - const std::pair>& b) const - { - return a.first > b.first; - } - }; - - void schedule(int tick, std::function callback); - std::vector> getCallbacks(int currentTick); - private: - std::priority_queue>, - std::vector>>, - TaskComparator> - scheduledTasks; - std::mutex taskMutex; -}; -} // namespace counterstrikesharp \ No newline at end of file +/* + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ + +#include +#include +#include +#include + +namespace counterstrikesharp { +class TickScheduler +{ + public: + struct TaskComparator + { + bool operator()(const std::pair>& a, const std::pair>& b) const + { + return a.first > b.first; + } + }; + + void schedule(int tick, std::function callback); + std::vector> getCallbacks(int currentTick); + + private: + std::priority_queue>, std::vector>>, TaskComparator> + scheduledTasks; + std::mutex taskMutex; +}; +} // namespace counterstrikesharp diff --git a/src/core/timer_system.h b/src/core/timer_system.h index d7447791..4a9a28a4 100644 --- a/src/core/timer_system.h +++ b/src/core/timer_system.h @@ -41,30 +41,32 @@ class TimerSystem; class ScriptCallback; namespace timers { -#define TIMER_FLAG_REPEAT (1 << 0) /**< Timer will repeat until stopped */ +#define TIMER_FLAG_REPEAT (1 << 0) /**< Timer will repeat until stopped */ #define TIMER_FLAG_NO_MAPCHANGE (1 << 1) /**< Timer will not carry over mapchanges */ -class Timer { +class Timer +{ friend class TimerSystem; -public: + public: Timer(float interval, float exec_time, CallbackT callback, int flags); ~Timer(); float m_interval; - ScriptCallback *m_callback; + ScriptCallback* m_callback; int m_flags; float m_exec_time; bool m_in_exec; bool m_kill_me; }; -} // namespace timers +} // namespace timers class ScriptCallback; -class TimerSystem : public GlobalClass { -public: +class TimerSystem : public GlobalClass +{ + public: TimerSystem(); void OnAllInitialized() override; void OnShutdown() override; @@ -74,19 +76,18 @@ public: double CalculateNextThink(double last_think_time, float interval); void RunFrame(); void RemoveMapChangeTimers(); - timers::Timer *CreateTimer(float interval, CallbackT callback, int flags); - void KillTimer(timers::Timer *timer); + timers::Timer* CreateTimer(float interval, CallbackT callback, int flags); + void KillTimer(timers::Timer* timer); double GetTickedTime(); - private: bool m_has_map_ticked = false; bool m_has_map_simulated = false; float m_last_ticked_time = 0.0f; - ScriptCallback *m_on_tick_callback_ = nullptr; - ScriptCallback *on_map_end_callback = nullptr; + ScriptCallback* m_on_tick_callback_ = nullptr; + ScriptCallback* on_map_end_callback = nullptr; - std::vector m_once_off_timers; - std::vector m_repeat_timers; + std::vector m_once_off_timers; + std::vector m_repeat_timers; }; -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/core/utils.h b/src/core/utils.h index d68734f3..845ed5a1 100644 --- a/src/core/utils.h +++ b/src/core/utils.h @@ -10,8 +10,10 @@ namespace utils { static std::string gameDirectory; -inline std::string GameDirectory() { - if (gameDirectory.empty()) { +inline std::string GameDirectory() +{ + if (gameDirectory.empty()) + { CBufferStringGrowable<255> gamePath; globals::engine->GetGameDir(gamePath); gameDirectory = std::string(gamePath.Get()); @@ -25,5 +27,5 @@ inline std::string PluginsDirectory() { return GameDirectory() + "/addons/counte inline std::string ConfigsDirectory() { return GameDirectory() + "/addons/counterstrikesharp/configs"; } inline std::string GamedataDirectory() { return GameDirectory() + "/addons/counterstrikesharp/gamedata"; } -} // namespace utils -} // namespace counterstrikesharp +} // namespace utils +} // namespace counterstrikesharp diff --git a/src/mm_plugin.h b/src/mm_plugin.h index 36086594..ce6a10df 100644 --- a/src/mm_plugin.h +++ b/src/mm_plugin.h @@ -17,7 +17,6 @@ #ifndef _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_ #define _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_ -// clang-format off #include #include #include @@ -27,7 +26,6 @@ #include #include "entitysystem.h" #include "concurrentqueue.h" -// clang-format on namespace counterstrikesharp { class ScriptCallback; @@ -74,9 +72,7 @@ static ScriptCallback* on_activate_callback; static ScriptCallback* on_metamod_all_plugins_loaded_callback; extern CounterStrikeSharpMMPlugin gPlugin; - #endif //_INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_ } PLUGIN_GLOBALVARS(); - diff --git a/src/protobuf/google/protobuf/descriptor.proto b/src/protobuf/google/protobuf/descriptor.proto index f8eb216c..512acf7e 100644 --- a/src/protobuf/google/protobuf/descriptor.proto +++ b/src/protobuf/google/protobuf/descriptor.proto @@ -36,7 +36,6 @@ // A valid .proto file can be translated directly to a FileDescriptorProto // without any other information (e.g. without reading its imports). - syntax = "proto2"; package google.protobuf; @@ -54,258 +53,268 @@ option optimize_for = SPEED; // The protocol compiler can output a FileDescriptorSet containing the .proto // files it parses. -message FileDescriptorSet { - repeated FileDescriptorProto file = 1; -} +message FileDescriptorSet { repeated FileDescriptorProto file = 1; } // Describes a complete .proto file. -message FileDescriptorProto { - optional string name = 1; // file name, relative to root of source tree - optional string package = 2; // e.g. "foo", "foo.bar", etc. +message FileDescriptorProto +{ + optional string name = 1; // file name, relative to root of source tree + optional string package = 2; // e.g. "foo", "foo.bar", etc. - // Names of files imported by this file. - repeated string dependency = 3; - // Indexes of the public imported files in the dependency list above. - repeated int32 public_dependency = 10; - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - repeated int32 weak_dependency = 11; + // Names of files imported by this file. + repeated string dependency = 3; + // Indexes of the public imported files in the dependency list above. + repeated int32 public_dependency = 10; + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + repeated int32 weak_dependency = 11; - // All top-level definitions in this file. - repeated DescriptorProto message_type = 4; - repeated EnumDescriptorProto enum_type = 5; - repeated ServiceDescriptorProto service = 6; - repeated FieldDescriptorProto extension = 7; + // All top-level definitions in this file. + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; - optional FileOptions options = 8; + optional FileOptions options = 8; - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - optional SourceCodeInfo source_code_info = 9; + // This field contains optional information about the original source code. + // You may safely remove this entire field without harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + optional SourceCodeInfo source_code_info = 9; - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - optional string syntax = 12; + // The syntax of the proto file. + // The supported values are "proto2" and "proto3". + optional string syntax = 12; } // Describes a message type. -message DescriptorProto { - optional string name = 1; +message DescriptorProto +{ + optional string name = 1; - repeated FieldDescriptorProto field = 2; - repeated FieldDescriptorProto extension = 6; + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; - repeated DescriptorProto nested_type = 3; - repeated EnumDescriptorProto enum_type = 4; + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; - message ExtensionRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Exclusive. + message ExtensionRange + { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. - optional ExtensionRangeOptions options = 3; - } - repeated ExtensionRange extension_range = 5; + optional ExtensionRangeOptions options = 3; + } + repeated ExtensionRange extension_range = 5; - repeated OneofDescriptorProto oneof_decl = 8; + repeated OneofDescriptorProto oneof_decl = 8; - optional MessageOptions options = 7; + optional MessageOptions options = 7; - // Range of reserved tag numbers. Reserved tag numbers may not be used by - // fields or extension ranges in the same message. Reserved ranges may - // not overlap. - message ReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Exclusive. - } - repeated ReservedRange reserved_range = 9; - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - repeated string reserved_name = 10; + // Range of reserved tag numbers. Reserved tag numbers may not be used by + // fields or extension ranges in the same message. Reserved ranges may + // not overlap. + message ReservedRange + { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + } + repeated ReservedRange reserved_range = 9; + // Reserved field names, which may not be used by fields in the same message. + // A given name may only be reserved once. + repeated string reserved_name = 10; } -message ExtensionRangeOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; +message ExtensionRangeOptions +{ + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; } // Describes a field within a message. -message FieldDescriptorProto { - enum Type { - // 0 is reserved for errors. - // Order is weird for historical reasons. - TYPE_DOUBLE = 1; - TYPE_FLOAT = 2; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - TYPE_INT64 = 3; - TYPE_UINT64 = 4; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - TYPE_INT32 = 5; - TYPE_FIXED64 = 6; - TYPE_FIXED32 = 7; - TYPE_BOOL = 8; - TYPE_STRING = 9; - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - TYPE_GROUP = 10; - TYPE_MESSAGE = 11; // Length-delimited aggregate. +message FieldDescriptorProto +{ + enum Type + { + // 0 is reserved for errors. + // Order is weird for historical reasons. + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + // Tag-delimited aggregate. + // Group type is deprecated and not supported in proto3. However, Proto3 + // implementations should still be able to parse the group wire format and + // treat group fields as unknown fields. + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; // Length-delimited aggregate. - // New in version 2. - TYPE_BYTES = 12; - TYPE_UINT32 = 13; - TYPE_ENUM = 14; - TYPE_SFIXED32 = 15; - TYPE_SFIXED64 = 16; - TYPE_SINT32 = 17; // Uses ZigZag encoding. - TYPE_SINT64 = 18; // Uses ZigZag encoding. - } + // New in version 2. + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; // Uses ZigZag encoding. + TYPE_SINT64 = 18; // Uses ZigZag encoding. + } - enum Label { - // 0 is reserved for errors - LABEL_OPTIONAL = 1; - LABEL_REQUIRED = 2; - LABEL_REPEATED = 3; - } + enum Label + { + // 0 is reserved for errors + LABEL_OPTIONAL = 1; + LABEL_REQUIRED = 2; + LABEL_REPEATED = 3; + } - optional string name = 1; - optional int32 number = 3; - optional Label label = 4; + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - optional Type type = 5; + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + optional Type type = 5; - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - optional string type_name = 6; + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + optional string type_name = 6; - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - optional string extendee = 2; + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + optional string extendee = 2; - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - optional string default_value = 7; + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + optional string default_value = 7; - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - optional int32 oneof_index = 9; + // If set, gives the index of a oneof in the containing type's oneof_decl + // list. This field is a member of that oneof. + optional int32 oneof_index = 9; - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - optional string json_name = 10; + // JSON name of this field. The value is set by protocol compiler. If the + // user has set a "json_name" option on this field, that option's value + // will be used. Otherwise, it's deduced from the field's name by converting + // it to camelCase. + optional string json_name = 10; - optional FieldOptions options = 8; + optional FieldOptions options = 8; - // If true, this is a proto3 "optional". When a proto3 field is optional, it - // tracks presence regardless of field type. - // - // When proto3_optional is true, this field must be belong to a oneof to - // signal to old proto3 clients that presence is tracked for this field. This - // oneof is known as a "synthetic" oneof, and this field must be its sole - // member (each proto3 optional field gets its own synthetic oneof). Synthetic - // oneofs exist in the descriptor only, and do not generate any API. Synthetic - // oneofs must be ordered after all "real" oneofs. - // - // For message fields, proto3_optional doesn't create any semantic change, - // since non-repeated message fields always track presence. However it still - // indicates the semantic detail of whether the user wrote "optional" or not. - // This can be useful for round-tripping the .proto file. For consistency we - // give message fields a synthetic oneof also, even though it is not required - // to track presence. This is especially important because the parser can't - // tell if a field is a message or an enum, so it must always create a - // synthetic oneof. - // - // Proto2 optional fields do not set this flag, because they already indicate - // optional with `LABEL_OPTIONAL`. - optional bool proto3_optional = 17; + // If true, this is a proto3 "optional". When a proto3 field is optional, it + // tracks presence regardless of field type. + // + // When proto3_optional is true, this field must be belong to a oneof to + // signal to old proto3 clients that presence is tracked for this field. This + // oneof is known as a "synthetic" oneof, and this field must be its sole + // member (each proto3 optional field gets its own synthetic oneof). Synthetic + // oneofs exist in the descriptor only, and do not generate any API. Synthetic + // oneofs must be ordered after all "real" oneofs. + // + // For message fields, proto3_optional doesn't create any semantic change, + // since non-repeated message fields always track presence. However it still + // indicates the semantic detail of whether the user wrote "optional" or not. + // This can be useful for round-tripping the .proto file. For consistency we + // give message fields a synthetic oneof also, even though it is not required + // to track presence. This is especially important because the parser can't + // tell if a field is a message or an enum, so it must always create a + // synthetic oneof. + // + // Proto2 optional fields do not set this flag, because they already indicate + // optional with `LABEL_OPTIONAL`. + optional bool proto3_optional = 17; } // Describes a oneof. -message OneofDescriptorProto { - optional string name = 1; - optional OneofOptions options = 2; +message OneofDescriptorProto +{ + optional string name = 1; + optional OneofOptions options = 2; } // Describes an enum type. -message EnumDescriptorProto { - optional string name = 1; +message EnumDescriptorProto +{ + optional string name = 1; - repeated EnumValueDescriptorProto value = 2; + repeated EnumValueDescriptorProto value = 2; - optional EnumOptions options = 3; + optional EnumOptions options = 3; - // Range of reserved numeric values. Reserved values may not be used by - // entries in the same enum. Reserved ranges may not overlap. - // - // Note that this is distinct from DescriptorProto.ReservedRange in that it - // is inclusive such that it can appropriately represent the entire int32 - // domain. - message EnumReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Inclusive. - } + // Range of reserved numeric values. Reserved values may not be used by + // entries in the same enum. Reserved ranges may not overlap. + // + // Note that this is distinct from DescriptorProto.ReservedRange in that it + // is inclusive such that it can appropriately represent the entire int32 + // domain. + message EnumReservedRange + { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Inclusive. + } - // Range of reserved numeric values. Reserved numeric values may not be used - // by enum values in the same enum declaration. Reserved ranges may not - // overlap. - repeated EnumReservedRange reserved_range = 4; + // Range of reserved numeric values. Reserved numeric values may not be used + // by enum values in the same enum declaration. Reserved ranges may not + // overlap. + repeated EnumReservedRange reserved_range = 4; - // Reserved enum value names, which may not be reused. A given name may only - // be reserved once. - repeated string reserved_name = 5; + // Reserved enum value names, which may not be reused. A given name may only + // be reserved once. + repeated string reserved_name = 5; } // Describes a value within an enum. -message EnumValueDescriptorProto { - optional string name = 1; - optional int32 number = 2; +message EnumValueDescriptorProto +{ + optional string name = 1; + optional int32 number = 2; - optional EnumValueOptions options = 3; + optional EnumValueOptions options = 3; } // Describes a service. -message ServiceDescriptorProto { - optional string name = 1; - repeated MethodDescriptorProto method = 2; +message ServiceDescriptorProto +{ + optional string name = 1; + repeated MethodDescriptorProto method = 2; - optional ServiceOptions options = 3; + optional ServiceOptions options = 3; } // Describes a method of a service. -message MethodDescriptorProto { - optional string name = 1; +message MethodDescriptorProto +{ + optional string name = 1; - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - optional string input_type = 2; - optional string output_type = 3; + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + optional string input_type = 2; + optional string output_type = 3; - optional MethodOptions options = 4; + optional MethodOptions options = 4; - // Identifies if client streams multiple client messages - optional bool client_streaming = 5 [default = false]; - // Identifies if server streams multiple server messages - optional bool server_streaming = 6 [default = false]; + // Identifies if client streams multiple client messages + optional bool client_streaming = 5 [ default = false ]; + // Identifies if server streams multiple server messages + optional bool server_streaming = 6 [ default = false ]; } - // =================================================================== // Options @@ -338,424 +347,423 @@ message MethodDescriptorProto { // If this turns out to be popular, a web service will be set up // to automatically assign option numbers. -message FileOptions { +message FileOptions +{ + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + optional string java_package = 1; - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - optional string java_package = 1; + // Controls the name of the wrapper Java class generated for the .proto file. + // That class will always contain the .proto file's getDescriptor() method as + // well as any top-level extensions defined in the .proto file. + // If java_multiple_files is disabled, then all the other classes from the + // .proto file will be nested inside the single wrapper outer class. + optional string java_outer_classname = 8; + // If enabled, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the wrapper class + // named by java_outer_classname. However, the wrapper class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + optional bool java_multiple_files = 10 [ default = false ]; - // Controls the name of the wrapper Java class generated for the .proto file. - // That class will always contain the .proto file's getDescriptor() method as - // well as any top-level extensions defined in the .proto file. - // If java_multiple_files is disabled, then all the other classes from the - // .proto file will be nested inside the single wrapper outer class. - optional string java_outer_classname = 8; + // This option does nothing. + optional bool java_generate_equals_and_hash = 20 [ deprecated = true ]; - // If enabled, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the wrapper class - // named by java_outer_classname. However, the wrapper class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - optional bool java_multiple_files = 10 [default = false]; + // If set true, then the Java2 code generator will generate code that + // throws an exception whenever an attempt is made to assign a non-UTF-8 + // byte sequence to a string field. + // Message reflection will do the same. + // However, an extension field still accepts non-UTF-8 byte sequences. + // This option has no effect on when used with the lite runtime. + optional bool java_string_check_utf8 = 27 [ default = false ]; - // This option does nothing. - optional bool java_generate_equals_and_hash = 20 [deprecated=true]; + // Generated classes can be optimized for speed or code size. + enum OptimizeMode + { + SPEED = 1; // Generate complete code for parsing, serialization, + // etc. + CODE_SIZE = 2; // Use ReflectionOps to implement these methods. + LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. + } + optional OptimizeMode optimize_for = 9 [ default = SPEED ]; - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - optional bool java_string_check_utf8 = 27 [default = false]; + // Sets the Go package where structs generated from this .proto will be + // placed. If omitted, the Go package will be derived from the following: + // - The basename of the package import path, if provided. + // - Otherwise, the package statement in the .proto file, if present. + // - Otherwise, the basename of the .proto file, without extension. + optional string go_package = 11; + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of google.protobuf. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + optional bool cc_generic_services = 16 [ default = false ]; + optional bool java_generic_services = 17 [ default = false ]; + optional bool py_generic_services = 18 [ default = false ]; + optional bool php_generic_services = 42 [ default = false ]; - // Generated classes can be optimized for speed or code size. - enum OptimizeMode { - SPEED = 1; // Generate complete code for parsing, serialization, - // etc. - CODE_SIZE = 2; // Use ReflectionOps to implement these methods. - LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. - } - optional OptimizeMode optimize_for = 9 [default = SPEED]; + // Is this file deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for everything in the file, or it will be completely ignored; in the very + // least, this is a formalization for deprecating files. + optional bool deprecated = 23 [ default = false ]; - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - optional string go_package = 11; + // Enables the use of arenas for the proto messages in this file. This applies + // only to generated classes for C++. + optional bool cc_enable_arenas = 31 [ default = true ]; + // Sets the objective c class prefix which is prepended to all objective c + // generated classes from this .proto. There is no default. + optional string objc_class_prefix = 36; + // Namespace for generated classes; defaults to the package. + optional string csharp_namespace = 37; + // By default Swift generators will take the proto package and CamelCase it + // replacing '.' with underscore and use that to prefix the types/symbols + // defined. When this options is provided, they will use this value instead + // to prefix the types/symbols defined. + optional string swift_prefix = 39; - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - optional bool cc_generic_services = 16 [default = false]; - optional bool java_generic_services = 17 [default = false]; - optional bool py_generic_services = 18 [default = false]; - optional bool php_generic_services = 42 [default = false]; + // Sets the php class prefix which is prepended to all php generated classes + // from this .proto. Default is empty. + optional string php_class_prefix = 40; - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - optional bool deprecated = 23 [default = false]; + // Use this option to change the namespace of php generated classes. Default + // is empty. When this option is empty, the package name will be used for + // determining the namespace. + optional string php_namespace = 41; - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - optional bool cc_enable_arenas = 31 [default = true]; + // Use this option to change the namespace of php generated metadata classes. + // Default is empty. When this option is empty, the proto file name will be + // used for determining the namespace. + optional string php_metadata_namespace = 44; + // Use this option to change the package of ruby generated classes. Default + // is empty. When this option is not set, the package name will be used for + // determining the ruby package. + optional string ruby_package = 45; - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - optional string objc_class_prefix = 36; + // The parser stores options it doesn't recognize here. + // See the documentation for the "Options" section above. + repeated UninterpretedOption uninterpreted_option = 999; - // Namespace for generated classes; defaults to the package. - optional string csharp_namespace = 37; + // Clients can define custom options in extensions of this message. + // See the documentation for the "Options" section above. + extensions 1000 to max; - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - optional string swift_prefix = 39; - - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - optional string php_class_prefix = 40; - - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - optional string php_namespace = 41; - - // Use this option to change the namespace of php generated metadata classes. - // Default is empty. When this option is empty, the proto file name will be - // used for determining the namespace. - optional string php_metadata_namespace = 44; - - // Use this option to change the package of ruby generated classes. Default - // is empty. When this option is not set, the package name will be used for - // determining the ruby package. - optional string ruby_package = 45; - - - // The parser stores options it doesn't recognize here. - // See the documentation for the "Options" section above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. - // See the documentation for the "Options" section above. - extensions 1000 to max; - - reserved 38; + reserved 38; } -message MessageOptions { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - optional bool message_set_wire_format = 1 [default = false]; +message MessageOptions +{ + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + optional bool message_set_wire_format = 1 [ default = false ]; - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - optional bool no_standard_descriptor_accessor = 2 [default = false]; + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + optional bool no_standard_descriptor_accessor = 2 [ default = false ]; - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - optional bool deprecated = 3 [default = false]; + // Is this message deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the message, or it will be completely ignored; in the very least, + // this is a formalization for deprecating messages. + optional bool deprecated = 3 [ default = false ]; - reserved 4, 5, 6; + reserved 4, 5, 6; - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementations still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - optional bool map_entry = 7; + // Whether the message is an automatically generated map entry type for the + // maps field. + // + // For maps fields: + // map map_field = 1; + // The parsed descriptor looks like: + // message MapFieldEntry { + // option map_entry = true; + // optional KeyType key = 1; + // optional ValueType value = 2; + // } + // repeated MapFieldEntry map_field = 1; + // + // Implementations may choose not to generate the map_entry=true message, but + // use a native map in the target language to hold the keys and values. + // The reflection APIs in such implementations still need to work as + // if the field is a repeated message field. + // + // NOTE: Do not set the option in .proto files. Always use the maps syntax + // instead. The option should only be implicitly set by the proto compiler + // parser. + optional bool map_entry = 7; - reserved 8; // javalite_serializable - reserved 9; // javanano_as_lite + reserved 8; // javalite_serializable + reserved 9; // javanano_as_lite + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; } -message FieldOptions { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - optional CType ctype = 1 [default = STRING]; - enum CType { - // Default mode. - STRING = 0; +message FieldOptions +{ + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is not yet implemented in the open source + // release -- sorry, we'll try to include it in a future version! + optional CType ctype = 1 [ default = STRING ]; + enum CType + { + // Default mode. + STRING = 0; - CORD = 1; + CORD = 1; - STRING_PIECE = 2; - } - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - optional bool packed = 2; + STRING_PIECE = 2; + } + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. In proto3, only explicit setting it to + // false will avoid using packed encoding. + optional bool packed = 2; - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - optional JSType jstype = 6 [default = JS_NORMAL]; - enum JSType { - // Use the default type. - JS_NORMAL = 0; + // The jstype option determines the JavaScript type used for values of the + // field. The option is permitted only for 64 bit integral and fixed types + // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + // is represented as JavaScript string, which avoids loss of precision that + // can happen when a large value is converted to a floating point JavaScript. + // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + // use the JavaScript "number" type. The behavior of the default option + // JS_NORMAL is implementation dependent. + // + // This option is an enum to permit additional types to be added, e.g. + // goog.math.Integer. + optional JSType jstype = 6 [ default = JS_NORMAL ]; + enum JSType + { + // Use the default type. + JS_NORMAL = 0; - // Use JavaScript strings. - JS_STRING = 1; + // Use JavaScript strings. + JS_STRING = 1; - // Use JavaScript numbers. - JS_NUMBER = 2; - } + // Use JavaScript numbers. + JS_NUMBER = 2; + } - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - // - // As of 2021, lazy does no correctness checks on the byte stream during - // parsing. This may lead to crashes if and when an invalid byte stream is - // finally parsed upon access. - // - // TODO(b/211906113): Enable validation on lazy fields. - optional bool lazy = 5 [default = false]; + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // + // Note that implementations may choose not to check required fields within + // a lazy sub-message. That is, calling IsInitialized() on the outer message + // may return true even if the inner message has missing required fields. + // This is necessary because otherwise the inner message would have to be + // parsed in order to perform the check, defeating the purpose of lazy + // parsing. An implementation which chooses not to check required fields + // must be consistent about it. That is, for any particular sub-message, the + // implementation must either *always* check its required fields, or *never* + // check its required fields, regardless of whether or not the message has + // been parsed. + // + // As of 2021, lazy does no correctness checks on the byte stream during + // parsing. This may lead to crashes if and when an invalid byte stream is + // finally parsed upon access. + // + // TODO(b/211906113): Enable validation on lazy fields. + optional bool lazy = 5 [ default = false ]; - // unverified_lazy does no correctness checks on the byte stream. This should - // only be used where lazy with verification is prohibitive for performance - // reasons. - optional bool unverified_lazy = 15 [default = false]; + // unverified_lazy does no correctness checks on the byte stream. This should + // only be used where lazy with verification is prohibitive for performance + // reasons. + optional bool unverified_lazy = 15 [ default = false ]; - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - optional bool deprecated = 3 [default = false]; + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + optional bool deprecated = 3 [ default = false ]; - // For Google-internal migration only. Do not use. - optional bool weak = 10 [default = false]; + // For Google-internal migration only. Do not use. + optional bool weak = 10 [ default = false ]; + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; - - reserved 4; // removed jtype + reserved 4; // removed jtype } -message OneofOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; +message OneofOptions +{ + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; } -message EnumOptions { +message EnumOptions +{ + // Set this option to true to allow mapping different tag names to the same + // value. + optional bool allow_alias = 2; - // Set this option to true to allow mapping different tag names to the same - // value. - optional bool allow_alias = 2; + // Is this enum deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum, or it will be completely ignored; in the very least, this + // is a formalization for deprecating enums. + optional bool deprecated = 3 [ default = false ]; - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - optional bool deprecated = 3 [default = false]; + reserved 5; // javanano_as_lite - reserved 5; // javanano_as_lite + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; } -message EnumValueOptions { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - optional bool deprecated = 1 [default = false]; +message EnumValueOptions +{ + // Is this enum value deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum value, or it will be completely ignored; in the very least, + // this is a formalization for deprecating enum values. + optional bool deprecated = 1 [ default = false ]; - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; } -message ServiceOptions { +message ServiceOptions +{ + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. + // Is this service deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the service, or it will be completely ignored; in the very least, + // this is a formalization for deprecating services. + optional bool deprecated = 33 [ default = false ]; - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - optional bool deprecated = 33 [default = false]; + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; } -message MethodOptions { +message MethodOptions +{ + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. + // Is this method deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the method, or it will be completely ignored; in the very least, + // this is a formalization for deprecating methods. + optional bool deprecated = 33 [ default = false ]; - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - optional bool deprecated = 33 [default = false]; + // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + // or neither? HTTP based RPC implementation may choose GET verb for safe + // methods, and PUT verb for idempotent methods instead of the default POST. + enum IdempotencyLevel + { + IDEMPOTENCY_UNKNOWN = 0; + NO_SIDE_EFFECTS = 1; // implies idempotent + IDEMPOTENT = 2; // idempotent, but may have side effects + } + optional IdempotencyLevel idempotency_level = 34 [ default = IDEMPOTENCY_UNKNOWN ]; - // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, - // or neither? HTTP based RPC implementation may choose GET verb for safe - // methods, and PUT verb for idempotent methods instead of the default POST. - enum IdempotencyLevel { - IDEMPOTENCY_UNKNOWN = 0; - NO_SIDE_EFFECTS = 1; // implies idempotent - IDEMPOTENT = 2; // idempotent, but may have side effects - } - optional IdempotencyLevel idempotency_level = 34 - [default = IDEMPOTENCY_UNKNOWN]; + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; } - // A message representing a option the parser does not recognize. This only // appears in options protos created by the compiler::Parser class. // DescriptorPool resolves these when building Descriptor objects. Therefore, // options protos in descriptor objects (e.g. returned by Descriptor::options(), // or produced by Descriptor::CopyTo()) will never have UninterpretedOptions // in them. -message UninterpretedOption { - // The name of the uninterpreted option. Each string represents a segment in - // a dot-separated name. is_extension is true iff a segment represents an - // extension (denoted with parentheses in options specs in .proto files). - // E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents - // "foo.(bar.baz).moo". - message NamePart { - required string name_part = 1; - required bool is_extension = 2; - } - repeated NamePart name = 2; +message UninterpretedOption +{ + // The name of the uninterpreted option. Each string represents a segment in + // a dot-separated name. is_extension is true iff a segment represents an + // extension (denoted with parentheses in options specs in .proto files). + // E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + // "foo.(bar.baz).moo". + message NamePart + { + required string name_part = 1; + required bool is_extension = 2; + } + repeated NamePart name = 2; - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - optional string identifier_value = 3; - optional uint64 positive_int_value = 4; - optional int64 negative_int_value = 5; - optional double double_value = 6; - optional bytes string_value = 7; - optional string aggregate_value = 8; + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; } // =================================================================== @@ -763,159 +771,163 @@ message UninterpretedOption { // Encapsulates information about the original source file from which a // FileDescriptorProto was generated. -message SourceCodeInfo { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendant. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - repeated Location location = 1; - message Location { - // Identifies which part of the FileDescriptorProto was defined at this - // location. +message SourceCodeInfo +{ + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition occurs. - // For example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - repeated int32 path = 1 [packed = true]; + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendant. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + repeated Location location = 1; + message Location + { + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition occurs. + // For example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + repeated int32 path = 1 [ packed = true ]; - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - repeated int32 span = 2 [packed = true]; + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + repeated int32 span = 2 [ packed = true ]; - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to moo. - // // - // // Another line attached to moo. - // optional double moo = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to moo or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - optional string leading_comments = 3; - optional string trailing_comments = 4; - repeated string leading_detached_comments = 6; - } + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // leading_detached_comments will keep paragraphs of comments that appear + // before (but not connected to) the current element. Each paragraph, + // separated by empty lines, will be one comment element in the repeated + // field. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to moo. + // // + // // Another line attached to moo. + // optional double moo = 4; + // + // // Detached comment for corge. This is not leading or trailing comments + // // to moo or corge because there are blank lines separating it from + // // both. + // + // // Detached comment for corge paragraph 2. + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + // + // // ignored detached comments. + optional string leading_comments = 3; + optional string trailing_comments = 4; + repeated string leading_detached_comments = 6; + } } // Describes the relationship between generated code and its original source // file. A GeneratedCodeInfo message is associated with only one generated // source file, but may contain references to different source .proto files. -message GeneratedCodeInfo { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - repeated Annotation annotation = 1; - message Annotation { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - repeated int32 path = 1 [packed = true]; +message GeneratedCodeInfo +{ + // An Annotation connects some span of text in generated code to an element + // of its generating .proto file. + repeated Annotation annotation = 1; + message Annotation + { + // Identifies the element in the original source .proto file. This field + // is formatted the same as SourceCodeInfo.Location.path. + repeated int32 path = 1 [ packed = true ]; - // Identifies the filesystem path to the original source .proto. - optional string source_file = 2; + // Identifies the filesystem path to the original source .proto. + optional string source_file = 2; - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - optional int32 begin = 3; + // Identifies the starting offset in bytes in the generated code + // that relates to the identified object. + optional int32 begin = 3; - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - optional int32 end = 4; - } + // Identifies the ending offset in bytes in the generated code that + // relates to the identified offset. The end offset should be one past + // the last relevant byte (so the length of the text = end - begin). + optional int32 end = 4; + } } diff --git a/src/scripting/autonative.h b/src/scripting/autonative.h index a4b92177..886c0d5d 100644 --- a/src/scripting/autonative.h +++ b/src/scripting/autonative.h @@ -20,29 +20,31 @@ #include "core/globals.h" #include "scripting/script_engine.h" -#define REGISTER_NATIVE(name, func) \ - counterstrikesharp::ScriptEngine::RegisterNativeHandler(#name, func); +#define REGISTER_NATIVE(name, func) counterstrikesharp::ScriptEngine::RegisterNativeHandler(#name, func); -#define REGISTER_NATIVES(name, method) \ - class Natives##name : public counterstrikesharp::GlobalClass { \ - public: \ - void OnAllInitialized() override method \ - }; \ - \ +#define REGISTER_NATIVES(name, method) \ + class Natives##name : public counterstrikesharp::GlobalClass \ + { \ + public: \ + void OnAllInitialized() override method \ + }; \ + \ Natives##name g_natives_##name; #define CREATE_GETTER_FUNCTION(object_name, parameter_type, parameter_name, from_type, getter) \ - static parameter_type object_name##Get##parameter_name(ScriptContext &script_context) { \ + static parameter_type object_name##Get##parameter_name(ScriptContext& script_context) \ + { \ auto obj = script_context.GetArgument(0); \ return getter; \ } #define CREATE_STATIC_GETTER_FUNCTION(parameter_name, parameter_type, getter) \ - static parameter_type Get##parameter_name(ScriptContext &script_context) { return getter; } + static parameter_type Get##parameter_name(ScriptContext& script_context) { return getter; } #define CREATE_SETTER_FUNCTION(type_name, get_type, name, from_type, setter) \ - static void type_name##Set##name(ScriptContext &script_context) { \ + static void type_name##Set##name(ScriptContext& script_context) \ + { \ auto obj = script_context.GetArgument(0); \ auto value = script_context.GetArgument(1); \ setter; \ - } \ No newline at end of file + } diff --git a/src/scripting/dotnet_host.cpp b/src/scripting/dotnet_host.cpp index 855a9d70..16fb389b 100644 --- a/src/scripting/dotnet_host.cpp +++ b/src/scripting/dotnet_host.cpp @@ -26,13 +26,13 @@ #include #include -#define STR(s) L##s -#define CH(c) L##c +#define STR(s) L##s +#define CH(c) L##c #define DIR_SEPARATOR L'\\' #else -#define STR(s) s -#define CH(c) c +#define STR(s) s +#define CH(c) c #define DIR_SEPARATOR '/' #include @@ -99,8 +99,7 @@ bool load_hostfxr() std::string base_dir = counterstrikesharp::utils::GetRootDirectory(); namespace css = counterstrikesharp; #if _WIN32 - std::wstring buffer = - std::wstring(css::widen(base_dir) + L"\\dotnet\\host\\fxr\\8.0.3\\hostfxr.dll"); + std::wstring buffer = std::wstring(css::widen(base_dir) + L"\\dotnet\\host\\fxr\\8.0.3\\hostfxr.dll"); CSSHARP_CORE_INFO("Loading hostfxr from {0}", css::narrow(buffer).c_str()); #else std::string buffer = std::string(base_dir + "/dotnet/host/fxr/8.0.3/libhostfxr.so"); @@ -109,21 +108,21 @@ bool load_hostfxr() // Load hostfxr and get desired exports void* lib = load_library(buffer.c_str()); - init_fptr = (hostfxr_initialize_for_runtime_config_fn)get_export( - lib, "hostfxr_initialize_for_runtime_config"); - if (init_fptr == nullptr) { - CSSHARP_CORE_CRITICAL( - "unable to get export function: \"hostfxr_initialize_for_runtime_config\""); + init_fptr = (hostfxr_initialize_for_runtime_config_fn)get_export(lib, "hostfxr_initialize_for_runtime_config"); + if (init_fptr == nullptr) + { + CSSHARP_CORE_CRITICAL("unable to get export function: \"hostfxr_initialize_for_runtime_config\""); return false; } - get_delegate_fptr = - (hostfxr_get_runtime_delegate_fn)get_export(lib, "hostfxr_get_runtime_delegate"); - if (!get_delegate_fptr) { + get_delegate_fptr = (hostfxr_get_runtime_delegate_fn)get_export(lib, "hostfxr_get_runtime_delegate"); + if (!get_delegate_fptr) + { CSSHARP_CORE_CRITICAL("unable to get export function: \"hostfxr_get_runtime_delegate\""); return false; } close_fptr = (hostfxr_close_fn)get_export(lib, "hostfxr_close"); - if (!close_fptr) { + if (!close_fptr) + { CSSHARP_CORE_CRITICAL("unable to get export function: \"hostfxr_close\""); return false; } @@ -139,16 +138,17 @@ load_assembly_and_get_function_pointer_fn get_dotnet_load_assembly(const char_t* // Load .NET Core void* load_assembly_and_get_function_pointer = nullptr; int rc = init_fptr(config_path, nullptr, &cxt); - if (rc != 0 || cxt == nullptr) { + if (rc != 0 || cxt == nullptr) + { CSSHARP_CORE_CRITICAL("Init failed: {0:x}", rc); close_fptr(cxt); return nullptr; } // Get the load assembly function pointer - rc = get_delegate_fptr(cxt, hdt_load_assembly_and_get_function_pointer, - &load_assembly_and_get_function_pointer); - if (rc != 0 || load_assembly_and_get_function_pointer == nullptr) { + rc = get_delegate_fptr(cxt, hdt_load_assembly_and_get_function_pointer, &load_assembly_and_get_function_pointer); + if (rc != 0 || load_assembly_and_get_function_pointer == nullptr) + { CSSHARP_CORE_ERROR("Get delegate failed: {0:x}", rc); } @@ -168,54 +168,51 @@ bool CDotNetManager::Initialize() CSSHARP_CORE_INFO("Loading .NET runtime..."); - if (!load_hostfxr()) { + if (!load_hostfxr()) + { CSSHARP_CORE_ERROR("Failed to initialize .NET runtime."); return false; } CSSHARP_CORE_INFO(".NET Runtime Initialised."); namespace css = counterstrikesharp; #if _WIN32 - const auto wide_str = - std::wstring(css::widen(base_dir) + L"\\api\\CounterStrikeSharp.API.runtimeconfig.json"); - CSSHARP_CORE_INFO("Loading CSS API, Runtime config: {}", - counterstrikesharp::narrow(wide_str).c_str()); + const auto wide_str = std::wstring(css::widen(base_dir) + L"\\api\\CounterStrikeSharp.API.runtimeconfig.json"); + CSSHARP_CORE_INFO("Loading CSS API, Runtime config: {}", counterstrikesharp::narrow(wide_str).c_str()); #else - std::string wide_str = - std::string((base_dir + "/api/CounterStrikeSharp.API.runtimeconfig.json").c_str()); + std::string wide_str = std::string((base_dir + "/api/CounterStrikeSharp.API.runtimeconfig.json").c_str()); CSSHARP_CORE_INFO("Loading CSS API, Runtime Config: {}", wide_str); #endif const auto load_assembly_and_get_function_pointer = get_dotnet_load_assembly(wide_str.c_str()); - if (load_assembly_and_get_function_pointer == nullptr) { + if (load_assembly_and_get_function_pointer == nullptr) + { CSSHARP_CORE_ERROR("Failed to load CSS API."); return false; } #if _WIN32 - const auto dotnetlib_path = - std::wstring(css::widen(base_dir) + L"\\api\\CounterStrikeSharp.API.dll"); + const auto dotnetlib_path = std::wstring(css::widen(base_dir) + L"\\api\\CounterStrikeSharp.API.dll"); CSSHARP_CORE_INFO("CSS API DLL: {}", counterstrikesharp::narrow(dotnetlib_path)); #else - const std::string dotnetlib_path = - std::string((base_dir + "/api/CounterStrikeSharp.API.dll").c_str()); + const std::string dotnetlib_path = std::string((base_dir + "/api/CounterStrikeSharp.API.dll").c_str()); #endif const auto dotnet_type = STR("CounterStrikeSharp.API.Bootstrap, CounterStrikeSharp.API"); // Namespace, assembly name typedef int(CORECLR_DELEGATE_CALLTYPE * custom_entry_point_fn)(); custom_entry_point_fn entry_point = nullptr; - const int rc = load_assembly_and_get_function_pointer( - dotnetlib_path.c_str(), dotnet_type, STR("Run"), UNMANAGEDCALLERSONLY_METHOD, - nullptr, reinterpret_cast(&entry_point)); - if (entry_point == nullptr) { + const int rc = load_assembly_and_get_function_pointer(dotnetlib_path.c_str(), dotnet_type, STR("Run"), UNMANAGEDCALLERSONLY_METHOD, + nullptr, reinterpret_cast(&entry_point)); + if (entry_point == nullptr) + { CSSHARP_CORE_ERROR("Trying to get entry point \"Bootstrap::Run\" but failed."); return false; } - assert(rc == 0 && entry_point != nullptr && - "Failure: load_assembly_and_get_function_pointer()"); + assert(rc == 0 && entry_point != nullptr && "Failure: load_assembly_and_get_function_pointer()"); - if (const int invoke_result_code = entry_point(); invoke_result_code == 0) { + if (const int invoke_result_code = entry_point(); invoke_result_code == 0) + { CSSHARP_CORE_ERROR("Bootstrap::Run return failure."); return false; } diff --git a/src/scripting/dotnet_host.h b/src/scripting/dotnet_host.h index 703c8ee1..f61cc7a9 100644 --- a/src/scripting/dotnet_host.h +++ b/src/scripting/dotnet_host.h @@ -21,29 +21,30 @@ #include #include -class PluginContext { +class PluginContext +{ friend class CDotNetManager; -public: - PluginContext(std::string dll_path) - : m_dll_path(dll_path) {} + public: + PluginContext(std::string dll_path) : m_dll_path(dll_path) {} -private: + private: std::string m_dll_path; }; -class CDotNetManager { +class CDotNetManager +{ friend class PluginContext; -public: + public: CDotNetManager(); ~CDotNetManager(); bool Initialize(); - void UnloadPlugin(PluginContext *context); + void UnloadPlugin(PluginContext* context); void Shutdown(); - PluginContext *FindContext(std::string path); + PluginContext* FindContext(std::string path); -private: + private: std::vector> m_app_domains; -}; \ No newline at end of file +}; diff --git a/src/scripting/natives/natives_callbacks.cpp b/src/scripting/natives/natives_callbacks.cpp index 07612355..ea14a7a5 100644 --- a/src/scripting/natives/natives_callbacks.cpp +++ b/src/scripting/natives/natives_callbacks.cpp @@ -20,15 +20,17 @@ namespace counterstrikesharp { -static bool AddListener(ScriptContext &script_context) { - auto name = script_context.GetArgument(0); +static bool AddListener(ScriptContext& script_context) +{ + auto name = script_context.GetArgument(0); auto callback = script_context.GetArgument(1); return globals::callbackManager.TryAddFunction(name, callback); } -static bool RemoveListener(ScriptContext &script_context) { - auto name = script_context.GetArgument(0); +static bool RemoveListener(ScriptContext& script_context) +{ + auto name = script_context.GetArgument(0); auto callback = script_context.GetArgument(1); return globals::callbackManager.TryRemoveFunction(name, callback); @@ -38,4 +40,4 @@ REGISTER_NATIVES(callbacks, { ScriptEngine::RegisterNativeHandler("ADD_LISTENER", AddListener); ScriptEngine::RegisterNativeHandler("REMOVE_LISTENER", RemoveListener); }) -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/scripting/natives/natives_dynamichooks.cpp b/src/scripting/natives/natives_dynamichooks.cpp index a053c48b..276e7c3e 100644 --- a/src/scripting/natives/natives_dynamichooks.cpp +++ b/src/scripting/natives/natives_dynamichooks.cpp @@ -1,283 +1,288 @@ -/* - * This file is part of CounterStrikeSharp. - * CounterStrikeSharp is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * CounterStrikeSharp is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with CounterStrikeSharp. If not, see . * - */ - -// clang-format off -#include "mm_plugin.h" -#include "core/timer_system.h" -#include "scripting/autonative.h" -#include "scripting/script_engine.h" -#include "core/function.h" -#include "pch.h" -#include "dynohook/core.h" -#include "dynohook/manager.h" - -// clang-format on - -namespace counterstrikesharp { - -void DHookGetReturn(ScriptContext& script_context) -{ - auto hook = script_context.GetArgument(0); - auto dataType = script_context.GetArgument(1); - if (hook == nullptr) { - script_context.ThrowNativeError("Invalid hook"); - } - - switch (dataType) { - case DATA_TYPE_BOOL: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_CHAR: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_UCHAR: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_SHORT: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_USHORT: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_INT: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_UINT: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_LONG: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_ULONG: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_LONG_LONG: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_ULONG_LONG: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_FLOAT: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_DOUBLE: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_POINTER: - script_context.SetResult(hook->getReturnValue()); - break; - case DATA_TYPE_STRING: - script_context.SetResult(hook->getReturnValue()); - break; - default: - assert(!"Unknown function parameter type!"); - break; - } -} - -void DHookSetReturn(ScriptContext& script_context) -{ - auto hook = script_context.GetArgument(0); - auto dataType = script_context.GetArgument(1); - if (hook == nullptr) { - script_context.ThrowNativeError("Invalid hook"); - } - - auto valueIndex = 2; - - switch (dataType) { - case DATA_TYPE_BOOL: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_CHAR: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_UCHAR: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_SHORT: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_USHORT: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_INT: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_UINT: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_LONG: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_ULONG: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_LONG_LONG: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_ULONG_LONG: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_FLOAT: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_DOUBLE: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_POINTER: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_STRING: - hook->setReturnValue(script_context.GetArgument(valueIndex)); - break; - default: - assert(!"Unknown function parameter type!"); - break; - } -} - -void DHookGetParam(ScriptContext& script_context) -{ - auto hook = script_context.GetArgument(0); - auto dataType = script_context.GetArgument(1); - auto paramIndex = script_context.GetArgument(2); - if (hook == nullptr) { - script_context.ThrowNativeError("Invalid hook"); - } - - switch (dataType) { - case DATA_TYPE_BOOL: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_CHAR: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_UCHAR: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_SHORT: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_USHORT: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_INT: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_UINT: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_LONG: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_ULONG: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_LONG_LONG: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_ULONG_LONG: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_FLOAT: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_DOUBLE: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_POINTER: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - case DATA_TYPE_STRING: - script_context.SetResult(hook->getArgument(paramIndex)); - break; - default: - assert(!"Unknown function parameter type!"); - break; - } -} - -void DHookSetParam(ScriptContext& script_context) -{ - auto hook = script_context.GetArgument(0); - auto dataType = script_context.GetArgument(1); - auto paramIndex = script_context.GetArgument(2); - if (hook == nullptr) { - script_context.ThrowNativeError("Invalid hook"); - } - - auto valueIndex = 3; - - switch (dataType) { - case DATA_TYPE_BOOL: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_CHAR: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_UCHAR: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_SHORT: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_USHORT: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_INT: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_UINT: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_LONG: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_ULONG: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_LONG_LONG: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_ULONG_LONG: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_FLOAT: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_DOUBLE: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_POINTER: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - case DATA_TYPE_STRING: - hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); - break; - default: - assert(!"Unknown function parameter type!"); - break; - } -} - -REGISTER_NATIVES(dynamichooks, { - ScriptEngine::RegisterNativeHandler("DYNAMIC_HOOK_GET_RETURN", DHookGetReturn); - ScriptEngine::RegisterNativeHandler("DYNAMIC_HOOK_SET_RETURN", DHookSetReturn); - ScriptEngine::RegisterNativeHandler("DYNAMIC_HOOK_GET_PARAM", DHookGetParam); - ScriptEngine::RegisterNativeHandler("DYNAMIC_HOOK_SET_PARAM", DHookSetParam); -}) -} // namespace counterstrikesharp +/* + * This file is part of CounterStrikeSharp. + * CounterStrikeSharp is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CounterStrikeSharp is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CounterStrikeSharp. If not, see . * + */ + +#include "mm_plugin.h" +#include "core/timer_system.h" +#include "scripting/autonative.h" +#include "scripting/script_engine.h" +#include "core/function.h" +#include "pch.h" +#include "dynohook/core.h" +#include "dynohook/manager.h" + +namespace counterstrikesharp { + +void DHookGetReturn(ScriptContext& script_context) +{ + auto hook = script_context.GetArgument(0); + auto dataType = script_context.GetArgument(1); + if (hook == nullptr) + { + script_context.ThrowNativeError("Invalid hook"); + } + + switch (dataType) + { + case DATA_TYPE_BOOL: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_CHAR: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_UCHAR: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_SHORT: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_USHORT: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_INT: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_UINT: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_LONG: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_ULONG: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_LONG_LONG: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_ULONG_LONG: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_FLOAT: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_DOUBLE: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_POINTER: + script_context.SetResult(hook->getReturnValue()); + break; + case DATA_TYPE_STRING: + script_context.SetResult(hook->getReturnValue()); + break; + default: + assert(!"Unknown function parameter type!"); + break; + } +} + +void DHookSetReturn(ScriptContext& script_context) +{ + auto hook = script_context.GetArgument(0); + auto dataType = script_context.GetArgument(1); + if (hook == nullptr) + { + script_context.ThrowNativeError("Invalid hook"); + } + + auto valueIndex = 2; + + switch (dataType) + { + case DATA_TYPE_BOOL: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_CHAR: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_UCHAR: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_SHORT: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_USHORT: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_INT: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_UINT: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_LONG: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_ULONG: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_LONG_LONG: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_ULONG_LONG: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_FLOAT: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_DOUBLE: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_POINTER: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_STRING: + hook->setReturnValue(script_context.GetArgument(valueIndex)); + break; + default: + assert(!"Unknown function parameter type!"); + break; + } +} + +void DHookGetParam(ScriptContext& script_context) +{ + auto hook = script_context.GetArgument(0); + auto dataType = script_context.GetArgument(1); + auto paramIndex = script_context.GetArgument(2); + if (hook == nullptr) + { + script_context.ThrowNativeError("Invalid hook"); + } + + switch (dataType) + { + case DATA_TYPE_BOOL: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_CHAR: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_UCHAR: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_SHORT: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_USHORT: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_INT: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_UINT: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_LONG: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_ULONG: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_LONG_LONG: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_ULONG_LONG: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_FLOAT: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_DOUBLE: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_POINTER: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + case DATA_TYPE_STRING: + script_context.SetResult(hook->getArgument(paramIndex)); + break; + default: + assert(!"Unknown function parameter type!"); + break; + } +} + +void DHookSetParam(ScriptContext& script_context) +{ + auto hook = script_context.GetArgument(0); + auto dataType = script_context.GetArgument(1); + auto paramIndex = script_context.GetArgument(2); + if (hook == nullptr) + { + script_context.ThrowNativeError("Invalid hook"); + } + + auto valueIndex = 3; + + switch (dataType) + { + case DATA_TYPE_BOOL: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_CHAR: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_UCHAR: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_SHORT: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_USHORT: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_INT: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_UINT: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_LONG: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_ULONG: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_LONG_LONG: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_ULONG_LONG: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_FLOAT: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_DOUBLE: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_POINTER: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + case DATA_TYPE_STRING: + hook->setArgument(paramIndex, script_context.GetArgument(valueIndex)); + break; + default: + assert(!"Unknown function parameter type!"); + break; + } +} + +REGISTER_NATIVES(dynamichooks, { + ScriptEngine::RegisterNativeHandler("DYNAMIC_HOOK_GET_RETURN", DHookGetReturn); + ScriptEngine::RegisterNativeHandler("DYNAMIC_HOOK_SET_RETURN", DHookSetReturn); + ScriptEngine::RegisterNativeHandler("DYNAMIC_HOOK_GET_PARAM", DHookGetParam); + ScriptEngine::RegisterNativeHandler("DYNAMIC_HOOK_SET_PARAM", DHookSetParam); +}) +} // namespace counterstrikesharp diff --git a/src/scripting/natives/natives_engine.cpp b/src/scripting/natives/natives_engine.cpp index e6c9ec9c..57888602 100644 --- a/src/scripting/natives/natives_engine.cpp +++ b/src/scripting/natives/natives_engine.cpp @@ -20,7 +20,6 @@ #include #include -// clang-format off #include "mm_plugin.h" #include "core/timer_system.h" #include "core/utils.h" @@ -32,7 +31,6 @@ #include "core/managers/player_manager.h" #include "core/managers/server_manager.h" #include "core/tick_scheduler.h" -// clang-format on #if _WIN32 #undef GetCurrentTime diff --git a/src/scripting/natives/natives_events.cpp b/src/scripting/natives/natives_events.cpp index 192955e3..7ae64e8b 100644 --- a/src/scripting/natives/natives_events.cpp +++ b/src/scripting/natives/natives_events.cpp @@ -20,44 +20,49 @@ #include "scripting/autonative.h" #include "igameevents.h" - namespace counterstrikesharp { -std::vector managed_game_events; +std::vector managed_game_events; -static void HookEvent(ScriptContext &script_context) { - const char *name = script_context.GetArgument(0); +static void HookEvent(ScriptContext& script_context) +{ + const char* name = script_context.GetArgument(0); auto callback = script_context.GetArgument(1); auto post = script_context.GetArgument(2); globals::eventManager.HookEvent(name, callback, post); } -static void UnhookEvent(ScriptContext &script_context) { - const char *name = script_context.GetArgument(0); +static void UnhookEvent(ScriptContext& script_context) +{ + const char* name = script_context.GetArgument(0); auto callback = script_context.GetArgument(1); auto post = script_context.GetArgument(2); globals::eventManager.UnhookEvent(name, callback, post); } -static IGameEvent *CreateEvent(ScriptContext &script_context) { - auto name = script_context.GetArgument(0); +static IGameEvent* CreateEvent(ScriptContext& script_context) +{ + auto name = script_context.GetArgument(0); bool force = script_context.GetArgument(1); auto pEvent = globals::gameEventManager->CreateEvent(name, force); - if (pEvent != nullptr) { + if (pEvent != nullptr) + { managed_game_events.push_back(pEvent); } return pEvent; } -static void FireEvent(ScriptContext &script_context) { - auto game_event = script_context.GetArgument(0); +static void FireEvent(ScriptContext& script_context) +{ + auto game_event = script_context.GetArgument(0); bool dont_broadcast = script_context.GetArgument(1); - if (!game_event) { + if (!game_event) + { script_context.ThrowNativeError("Invalid game event"); return; } @@ -66,17 +71,19 @@ static void FireEvent(ScriptContext &script_context) { managed_game_events.erase(std::remove(managed_game_events.begin(), managed_game_events.end(), game_event), managed_game_events.end()); } - -static void FireEventToClient(ScriptContext& script_context) { +static void FireEventToClient(ScriptContext& script_context) +{ auto game_event = script_context.GetArgument(0); int entityIndex = script_context.GetArgument(1); - if (!game_event) { + if (!game_event) + { script_context.ThrowNativeError("Invalid game event"); return; } IGameEventListener2* pListener = globals::GetLegacyGameEventListener(CPlayerSlot(entityIndex - 1)); - if (!pListener) { + if (!pListener) + { script_context.ThrowNativeError("Could not get player event listener"); return; } @@ -84,21 +91,25 @@ static void FireEventToClient(ScriptContext& script_context) { pListener->FireGameEvent(game_event); } -static void FreeEvent(ScriptContext& script_context) { +static void FreeEvent(ScriptContext& script_context) +{ auto game_event = script_context.GetArgument(0); - if (!game_event) { - script_context.ThrowNativeError("Invalid game event"); - return; + if (!game_event) + { + script_context.ThrowNativeError("Invalid game event"); + return; } globals::gameEventManager->FreeEvent(game_event); managed_game_events.erase(std::remove(managed_game_events.begin(), managed_game_events.end(), game_event), managed_game_events.end()); } -static const char *GetEventName(ScriptContext &script_context) { - IGameEvent *game_event = script_context.GetArgument(0); +static const char* GetEventName(ScriptContext& script_context) +{ + IGameEvent* game_event = script_context.GetArgument(0); - if (!game_event) { + if (!game_event) + { script_context.ThrowNativeError("Invalid game event"); return nullptr; } @@ -106,11 +117,13 @@ static const char *GetEventName(ScriptContext &script_context) { return game_event->GetName(); } -static bool GetEventBool(ScriptContext &script_context) { - IGameEvent *game_event = script_context.GetArgument(0); - const char *key_name = script_context.GetArgument(1); +static bool GetEventBool(ScriptContext& script_context) +{ + IGameEvent* game_event = script_context.GetArgument(0); + const char* key_name = script_context.GetArgument(1); - if (!game_event) { + if (!game_event) + { script_context.ThrowNativeError("Invalid game event"); return false; } @@ -118,11 +131,13 @@ static bool GetEventBool(ScriptContext &script_context) { return game_event->GetBool(key_name); } -static int GetEventInt(ScriptContext &script_context) { - IGameEvent *game_event = script_context.GetArgument(0); - const char *key_name = script_context.GetArgument(1); +static int GetEventInt(ScriptContext& script_context) +{ + IGameEvent* game_event = script_context.GetArgument(0); + const char* key_name = script_context.GetArgument(1); - if (!game_event) { + if (!game_event) + { script_context.ThrowNativeError("Invalid game event"); return -1; } @@ -130,11 +145,13 @@ static int GetEventInt(ScriptContext &script_context) { return game_event->GetInt(key_name); } -static float GetEventFloat(ScriptContext &script_context) { - IGameEvent *game_event = script_context.GetArgument(0); - const char *key_name = script_context.GetArgument(1); +static float GetEventFloat(ScriptContext& script_context) +{ + IGameEvent* game_event = script_context.GetArgument(0); + const char* key_name = script_context.GetArgument(1); - if (!game_event) { + if (!game_event) + { script_context.ThrowNativeError("Invalid game event"); return -1; } @@ -142,11 +159,13 @@ static float GetEventFloat(ScriptContext &script_context) { return game_event->GetFloat(key_name); } -static const char *GetEventString(ScriptContext &script_context) { - IGameEvent *game_event = script_context.GetArgument(0); - const char *key_name = script_context.GetArgument(1); +static const char* GetEventString(ScriptContext& script_context) +{ + IGameEvent* game_event = script_context.GetArgument(0); + const char* key_name = script_context.GetArgument(1); - if (!game_event) { + if (!game_event) + { script_context.ThrowNativeError("Invalid game event"); return nullptr; } @@ -154,51 +173,61 @@ static const char *GetEventString(ScriptContext &script_context) { return game_event->GetString(key_name); } -static void SetEventBool(ScriptContext &script_context) { - IGameEvent *game_event = script_context.GetArgument(0); - const char *key_name = script_context.GetArgument(1); +static void SetEventBool(ScriptContext& script_context) +{ + IGameEvent* game_event = script_context.GetArgument(0); + const char* key_name = script_context.GetArgument(1); const bool value = script_context.GetArgument(2); - if (game_event) { + if (game_event) + { game_event->SetBool(key_name, value); } } -static void SetEventInt(ScriptContext &script_context) { - IGameEvent *game_event = script_context.GetArgument(0); - const char *key_name = script_context.GetArgument(1); +static void SetEventInt(ScriptContext& script_context) +{ + IGameEvent* game_event = script_context.GetArgument(0); + const char* key_name = script_context.GetArgument(1); const int value = script_context.GetArgument(2); - if (game_event) { + if (game_event) + { game_event->SetInt(key_name, value); } } -static void SetEventFloat(ScriptContext &script_context) { - IGameEvent *game_event = script_context.GetArgument(0); - const char *key_name = script_context.GetArgument(1); +static void SetEventFloat(ScriptContext& script_context) +{ + IGameEvent* game_event = script_context.GetArgument(0); + const char* key_name = script_context.GetArgument(1); const float value = script_context.GetArgument(2); - if (game_event) { + if (game_event) + { game_event->SetFloat(key_name, value); } } -static void SetEventString(ScriptContext &script_context) { - IGameEvent *game_event = script_context.GetArgument(0); - const char *key_name = script_context.GetArgument(1); - const char *value = script_context.GetArgument(2); +static void SetEventString(ScriptContext& script_context) +{ + IGameEvent* game_event = script_context.GetArgument(0); + const char* key_name = script_context.GetArgument(1); + const char* value = script_context.GetArgument(2); - if (game_event) { + if (game_event) + { game_event->SetString(key_name, value); } } -static void *GetPlayerController(ScriptContext &scriptContext) { - IGameEvent *gameEvent = scriptContext.GetArgument(0); - const char *keyName = scriptContext.GetArgument(1); +static void* GetPlayerController(ScriptContext& scriptContext) +{ + IGameEvent* gameEvent = scriptContext.GetArgument(0); + const char* keyName = scriptContext.GetArgument(1); - if (gameEvent == nullptr) { + if (gameEvent == nullptr) + { scriptContext.ThrowNativeError("Invalid game event"); return nullptr; } @@ -206,41 +235,49 @@ static void *GetPlayerController(ScriptContext &scriptContext) { return gameEvent->GetPlayerController(keyName); } -static void SetPlayerController(ScriptContext &scriptContext) { - IGameEvent *gameEvent = scriptContext.GetArgument(0); - const char *keyName = scriptContext.GetArgument(1); - auto *value = scriptContext.GetArgument(2); +static void SetPlayerController(ScriptContext& scriptContext) +{ + IGameEvent* gameEvent = scriptContext.GetArgument(0); + const char* keyName = scriptContext.GetArgument(1); + auto* value = scriptContext.GetArgument(2); - if (gameEvent != nullptr) { + if (gameEvent != nullptr) + { gameEvent->SetPlayer(keyName, value); } } -static void SetEntity(ScriptContext &scriptContext) { - IGameEvent *gameEvent = scriptContext.GetArgument(0); - const char *keyName = scriptContext.GetArgument(1); - auto *value = scriptContext.GetArgument(2); +static void SetEntity(ScriptContext& scriptContext) +{ + IGameEvent* gameEvent = scriptContext.GetArgument(0); + const char* keyName = scriptContext.GetArgument(1); + auto* value = scriptContext.GetArgument(2); - if (gameEvent != nullptr) { + if (gameEvent != nullptr) + { gameEvent->SetEntity(keyName, value); } } -static void SetEntityIndex(ScriptContext &scriptContext) { - IGameEvent *gameEvent = scriptContext.GetArgument(0); - const char *keyName = scriptContext.GetArgument(1); +static void SetEntityIndex(ScriptContext& scriptContext) +{ + IGameEvent* gameEvent = scriptContext.GetArgument(0); + const char* keyName = scriptContext.GetArgument(1); auto index = scriptContext.GetArgument(2); - if (gameEvent != nullptr) { + if (gameEvent != nullptr) + { gameEvent->SetEntity(keyName, CEntityIndex{ index }); } } -static void *GetPlayerPawn(ScriptContext& scriptContext) { - IGameEvent *gameEvent = scriptContext.GetArgument(0); - const char *keyName = scriptContext.GetArgument(1); +static void* GetPlayerPawn(ScriptContext& scriptContext) +{ + IGameEvent* gameEvent = scriptContext.GetArgument(0); + const char* keyName = scriptContext.GetArgument(1); - if (gameEvent == nullptr) { + if (gameEvent == nullptr) + { scriptContext.ThrowNativeError("Invalid game event"); return nullptr; } @@ -248,11 +285,13 @@ static void *GetPlayerPawn(ScriptContext& scriptContext) { return gameEvent->GetPlayerPawn(keyName); } -static uint64 GetUint64(ScriptContext &scriptContext) { - IGameEvent *gameEvent = scriptContext.GetArgument(0); - const char *keyName = scriptContext.GetArgument(1); +static uint64 GetUint64(ScriptContext& scriptContext) +{ + IGameEvent* gameEvent = scriptContext.GetArgument(0); + const char* keyName = scriptContext.GetArgument(1); - if (gameEvent == nullptr) { + if (gameEvent == nullptr) + { scriptContext.ThrowNativeError("Invalid game event"); return 0; } @@ -260,18 +299,21 @@ static uint64 GetUint64(ScriptContext &scriptContext) { return gameEvent->GetUint64(keyName); } -static void SetUint64(ScriptContext &scriptContext) { - IGameEvent *gameEvent = scriptContext.GetArgument(0); - const char *keyName = scriptContext.GetArgument(1); +static void SetUint64(ScriptContext& scriptContext) +{ + IGameEvent* gameEvent = scriptContext.GetArgument(0); + const char* keyName = scriptContext.GetArgument(1); auto value = scriptContext.GetArgument(2); - if (gameEvent != nullptr) { + if (gameEvent != nullptr) + { gameEvent->SetUint64(keyName, value); } } -static int LoadEventsFromFile(ScriptContext &script_context) { - auto [path, searchAll] = script_context.GetArguments(); +static int LoadEventsFromFile(ScriptContext& script_context) +{ + auto [path, searchAll] = script_context.GetArguments(); return globals::gameEventManager->LoadEventsFromFile(path, searchAll); } @@ -304,8 +346,7 @@ REGISTER_NATIVES(events, { ScriptEngine::RegisterNativeHandler("GET_EVENT_UINT64", GetUint64); ScriptEngine::RegisterNativeHandler("SET_EVENT_UINT64", SetUint64); - ScriptEngine::RegisterNativeHandler("LOAD_EVENTS_FROM_FILE", LoadEventsFromFile); }) -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/scripting/natives/natives_metamod.cpp b/src/scripting/natives/natives_metamod.cpp index 8d918bcc..1f8b0abe 100644 --- a/src/scripting/natives/natives_metamod.cpp +++ b/src/scripting/natives/natives_metamod.cpp @@ -26,7 +26,5 @@ static void* MetaFactory(ScriptContext& script_context) return ptr; } -REGISTER_NATIVES(metamod, { - ScriptEngine::RegisterNativeHandler("META_FACTORY", MetaFactory); -}) +REGISTER_NATIVES(metamod, { ScriptEngine::RegisterNativeHandler("META_FACTORY", MetaFactory); }) } // namespace counterstrikesharp diff --git a/src/scripting/natives/natives_schema.cpp b/src/scripting/natives/natives_schema.cpp index db86451f..f0620b45 100644 --- a/src/scripting/natives/natives_schema.cpp +++ b/src/scripting/natives/natives_schema.cpp @@ -57,12 +57,10 @@ int GetSchemaClassSize(ScriptContext& script_context) { auto className = script_context.GetArgument(0); - CSchemaSystemTypeScope* pType = - globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT); + CSchemaSystemTypeScope* pType = globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT); SchemaClassInfoData_t* pClassInfo = pType->FindDeclaredClass(className).Get(); - if (!pClassInfo) - return -1; + if (!pClassInfo) return -1; return pClassInfo->m_nSize; } @@ -78,70 +76,56 @@ void GetSchemaValueByName(ScriptContext& script_context) const auto m_key = schema::GetOffset(className, classKey, memberName, memberKey); - switch (returnType) { - case DATA_TYPE_BOOL: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_CHAR: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_UCHAR: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_SHORT: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_USHORT: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_INT: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_UINT: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_LONG: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_ULONG: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_LONG_LONG: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_ULONG_LONG: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_FLOAT: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_DOUBLE: - script_context.SetResult(*reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_POINTER: - script_context.SetResult(reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - case DATA_TYPE_STRING: - script_context.SetResult(reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset)); - break; - default: - assert(!"Unknown function return type!"); - break; + switch (returnType) + { + case DATA_TYPE_BOOL: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_CHAR: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_UCHAR: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_SHORT: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_USHORT: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_INT: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_UINT: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_LONG: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_ULONG: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_LONG_LONG: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_ULONG_LONG: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_FLOAT: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_DOUBLE: + script_context.SetResult(*reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_POINTER: + script_context.SetResult(reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + case DATA_TYPE_STRING: + script_context.SetResult(reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset)); + break; + default: + assert(!"Unknown function return type!"); + break; } } @@ -152,7 +136,9 @@ void SetSchemaValueByName(ScriptContext& script_context) auto className = script_context.GetArgument(2); auto memberName = script_context.GetArgument(3); - if (globals::coreConfig->FollowCS2ServerGuidelines && std::find(schema::CS2BadList.begin(), schema::CS2BadList.end(), memberName) != schema::CS2BadList.end()) { + if (globals::coreConfig->FollowCS2ServerGuidelines && + std::find(schema::CS2BadList.begin(), schema::CS2BadList.end(), memberName) != schema::CS2BadList.end()) + { CSSHARP_CORE_ERROR("Cannot set '{}::{}' with \"FollowCS2ServerGuidelines\" option enabled.", className, memberName); return; } @@ -162,76 +148,68 @@ void SetSchemaValueByName(ScriptContext& script_context) const auto m_key = schema::GetOffset(className, classKey, memberName, memberKey); - switch (dataType) { - case DATA_TYPE_BOOL: - *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_CHAR: - *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_UCHAR: - *reinterpret_cast>((uintptr_t)(instancePointer) + - m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_SHORT: - *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_USHORT: - *reinterpret_cast>((uintptr_t)(instancePointer) + - m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_INT: - *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_UINT: - *reinterpret_cast>((uintptr_t)(instancePointer) + - m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_LONG: - *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_ULONG: - *reinterpret_cast>((uintptr_t)(instancePointer) + - m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_LONG_LONG: - *reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument(4); - break; - case DATA_TYPE_ULONG_LONG: - *reinterpret_cast>( - (uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument(4); - break; - case DATA_TYPE_FLOAT: - *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_DOUBLE: - *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_POINTER: - *reinterpret_cast((uintptr_t)(instancePointer) + m_key.offset) = - script_context.GetArgument(4); - break; - case DATA_TYPE_STRING: { - auto duplicated = strdup(script_context.GetArgument(4)); - *reinterpret_cast((uintptr_t)(instancePointer) + m_key.offset) = - duplicated; - break; - } - default: - assert(!"Unknown function data type!"); - break; + switch (dataType) + { + case DATA_TYPE_BOOL: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument(4); + break; + case DATA_TYPE_CHAR: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument(4); + break; + case DATA_TYPE_UCHAR: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = + script_context.GetArgument(4); + break; + case DATA_TYPE_SHORT: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = + script_context.GetArgument(4); + break; + case DATA_TYPE_USHORT: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = + script_context.GetArgument(4); + break; + case DATA_TYPE_INT: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument(4); + break; + case DATA_TYPE_UINT: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = + script_context.GetArgument(4); + break; + case DATA_TYPE_LONG: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument(4); + break; + case DATA_TYPE_ULONG: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = + script_context.GetArgument(4); + break; + case DATA_TYPE_LONG_LONG: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = + script_context.GetArgument(4); + break; + case DATA_TYPE_ULONG_LONG: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = + script_context.GetArgument(4); + break; + case DATA_TYPE_FLOAT: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = + script_context.GetArgument(4); + break; + case DATA_TYPE_DOUBLE: + *reinterpret_cast>((uintptr_t)(instancePointer) + m_key.offset) = + script_context.GetArgument(4); + break; + case DATA_TYPE_POINTER: + *reinterpret_cast((uintptr_t)(instancePointer) + m_key.offset) = script_context.GetArgument(4); + break; + case DATA_TYPE_STRING: + { + auto duplicated = strdup(script_context.GetArgument(4)); + *reinterpret_cast((uintptr_t)(instancePointer) + m_key.offset) = duplicated; + break; + } + default: + assert(!"Unknown function data type!"); + break; } } @@ -242,4 +220,4 @@ REGISTER_NATIVES(schema, { ScriptEngine::RegisterNativeHandler("SET_SCHEMA_VALUE_BY_NAME", SetSchemaValueByName); ScriptEngine::RegisterNativeHandler("GET_SCHEMA_CLASS_SIZE", GetSchemaClassSize); }) -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp diff --git a/src/scripting/natives/natives_server.cpp b/src/scripting/natives/natives_server.cpp index 98f0ea9a..0ae7f1d0 100644 --- a/src/scripting/natives/natives_server.cpp +++ b/src/scripting/natives/natives_server.cpp @@ -20,18 +20,13 @@ namespace counterstrikesharp { -static void *GetEconItemSystem(ScriptContext& scriptContext) { - return globals::serverManager.GetEconItemSystem(); -} +static void* GetEconItemSystem(ScriptContext& scriptContext) { return globals::serverManager.GetEconItemSystem(); } -static bool IsServerPaused(ScriptContext& scriptContext) -{ - return globals::serverManager.IsPaused(); -} +static bool IsServerPaused(ScriptContext& scriptContext) { return globals::serverManager.IsPaused(); } REGISTER_NATIVES(server, { ScriptEngine::RegisterNativeHandler("GET_ECON_ITEM_SYSTEM", GetEconItemSystem); ScriptEngine::RegisterNativeHandler("IS_SERVER_PAUSED", IsServerPaused); }) -} \ No newline at end of file +} // namespace counterstrikesharp diff --git a/src/scripting/natives/natives_timers.cpp b/src/scripting/natives/natives_timers.cpp index eaf7bc33..847205b2 100644 --- a/src/scripting/natives/natives_timers.cpp +++ b/src/scripting/natives/natives_timers.cpp @@ -21,7 +21,8 @@ namespace counterstrikesharp { -timers::Timer *CreateTimer(ScriptContext &script_context) { +timers::Timer* CreateTimer(ScriptContext& script_context) +{ auto interval = script_context.GetArgument(0); auto callback = script_context.GetArgument(1); auto flags = script_context.GetArgument(2); @@ -29,8 +30,9 @@ timers::Timer *CreateTimer(ScriptContext &script_context) { return globals::timerSystem.CreateTimer(interval, callback, flags); } -void KillTimer(ScriptContext &script_context) { - auto timer = script_context.GetArgument(0); +void KillTimer(ScriptContext& script_context) +{ + auto timer = script_context.GetArgument(0); globals::timerSystem.KillTimer(timer); } @@ -38,4 +40,4 @@ REGISTER_NATIVES(timers, { ScriptEngine::RegisterNativeHandler("CREATE_TIMER", CreateTimer); ScriptEngine::RegisterNativeHandler("KILL_TIMER", KillTimer); }) -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/scripting/natives/natives_usermessages.cpp b/src/scripting/natives/natives_usermessages.cpp index 5757080d..987870be 100644 --- a/src/scripting/natives/natives_usermessages.cpp +++ b/src/scripting/natives/natives_usermessages.cpp @@ -13,8 +13,6 @@ * You should have received a copy of the GNU General Public License * along with CounterStrikeSharp. If not, see . * */ -// clang-format off - #include "core/UserMessage.h" #include "core/globals.h" #include "core/log.h" @@ -24,8 +22,6 @@ #include "core/recipientfilters.h" -// clang-format on - namespace counterstrikesharp { #define GET_MESSAGE_OR_ERR() \ @@ -620,13 +616,16 @@ static void UserMessageSend(ScriptContext& scriptContext) CRecipientFilter filter{}; filter.AddRecipientsFromMask(message->GetRecipientMask() ? *message->GetRecipientMask() : 0); - // This is for calling send in a UM hook, if calling normal send using the UM instance from the UM hook, it will cause an inifinite loop, then crashing the server - static void (IGameEventSystem::*PostEventAbstract)(CSplitScreenSlot, bool, IRecipientFilter*, INetworkMessageInternal*, const CNetMessage*, unsigned long) = &IGameEventSystem::PostEventAbstract; + // This is for calling send in a UM hook, if calling normal send using the UM instance from the UM hook, it will cause an inifinite + // loop, then crashing the server + static void (IGameEventSystem::*PostEventAbstract)(CSplitScreenSlot, bool, IRecipientFilter*, INetworkMessageInternal*, + const CNetMessage*, unsigned long) = &IGameEventSystem::PostEventAbstract; if (message->IsManuallyAllocated()) globals::gameEventSystem->PostEventAbstract(0, false, &filter, message->GetSerializableMessage(), message->GetProtobufMessage(), 0); else - SH_CALL(globals::gameEventSystem, PostEventAbstract)(0, false, &filter, message->GetSerializableMessage(), message->GetProtobufMessage(), 0); + SH_CALL(globals::gameEventSystem, PostEventAbstract)(0, false, &filter, message->GetSerializableMessage(), + message->GetProtobufMessage(), 0); } static void UserMessageDelete(ScriptContext& scriptContext) diff --git a/src/scripting/script_engine.cpp b/src/scripting/script_engine.cpp index 56647d67..fea53f5d 100644 --- a/src/scripting/script_engine.cpp +++ b/src/scripting/script_engine.cpp @@ -37,7 +37,8 @@ namespace counterstrikesharp { std::stack errors; -void ScriptContext::ThrowNativeError(const char *msg, ...) { +void ScriptContext::ThrowNativeError(const char* msg, ...) +{ va_list arglist; char dest[256]; va_start(arglist, msg); @@ -49,13 +50,15 @@ void ScriptContext::ThrowNativeError(const char *msg, ...) { auto error_string = std::string(buff); errors.push(error_string); - const char *ptr = errors.top().c_str(); + const char* ptr = errors.top().c_str(); this->SetResult(ptr); *this->m_has_error = 1; } -void ScriptContext::Reset() { - if (*m_has_error) { +void ScriptContext::Reset() +{ + if (*m_has_error) + { errors.pop(); } @@ -63,36 +66,43 @@ void ScriptContext::Reset() { m_numArguments = 0; *m_has_error = 0; - for (int i = 0; i < 32; i++) { + for (int i = 0; i < 32; i++) + { m_native_context->arguments[i] = 0; } m_native_context->result = 0; } -tl::optional ScriptEngine::GetNativeHandler(uint64_t nativeIdentifier) { +tl::optional ScriptEngine::GetNativeHandler(uint64_t nativeIdentifier) +{ auto it = g_registeredHandlers.find(nativeIdentifier); - if (it != g_registeredHandlers.end()) { + if (it != g_registeredHandlers.end()) + { return it->second; } return tl::optional(); } -tl::optional ScriptEngine::GetNativeHandler(std::string identifier) { +tl::optional ScriptEngine::GetNativeHandler(std::string identifier) +{ auto it = g_registeredHandlers.find(hash_string(identifier.c_str())); - if (it != g_registeredHandlers.end()) { + if (it != g_registeredHandlers.end()) + { return it->second; } return tl::optional(); } -bool ScriptEngine::CallNativeHandler(uint64_t nativeIdentifier, ScriptContext &context) { +bool ScriptEngine::CallNativeHandler(uint64_t nativeIdentifier, ScriptContext& context) +{ auto h = GetNativeHandler(nativeIdentifier); - if (h) { + if (h) + { (*h)(context); return true; @@ -101,27 +111,30 @@ bool ScriptEngine::CallNativeHandler(uint64_t nativeIdentifier, ScriptContext &c return false; } -void ScriptEngine::RegisterNativeHandlerInt(uint64_t nativeIdentifier, TNativeHandler function) { +void ScriptEngine::RegisterNativeHandlerInt(uint64_t nativeIdentifier, TNativeHandler function) +{ g_registeredHandlers[nativeIdentifier] = function; } -void ScriptEngine::InvokeNative(counterstrikesharp::fxNativeContext &context) { +void ScriptEngine::InvokeNative(counterstrikesharp::fxNativeContext& context) +{ if (context.nativeIdentifier == 0) return; - auto nativeHandler = - counterstrikesharp::ScriptEngine::GetNativeHandler(context.nativeIdentifier); + auto nativeHandler = counterstrikesharp::ScriptEngine::GetNativeHandler(context.nativeIdentifier); - if (nativeHandler) { + if (nativeHandler) + { counterstrikesharp::ScriptContextRaw scriptContext(context); (*nativeHandler)(scriptContext); - } else { - CSSHARP_CORE_WARN("Native Handler was requested but not found: {0:x}", - context.nativeIdentifier); + } + else + { + CSSHARP_CORE_WARN("Native Handler was requested but not found: {0:x}", context.nativeIdentifier); assert(false); } } ScriptContextRaw ScriptEngine::m_context; -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/scripting/script_engine.h b/src/scripting/script_engine.h index 2448e253..5e6b5596 100644 --- a/src/scripting/script_engine.h +++ b/src/scripting/script_engine.h @@ -33,41 +33,46 @@ namespace counterstrikesharp { -enum HookResult { +enum HookResult +{ Continue = 0, Changed = 1, Handled = 3, Stop = 4, }; -enum HookMode { +enum HookMode +{ Pre = 0, Post = 1, }; -inline uint32_t hash_string(const char *string) { - unsigned long result = 5381; - - for (size_t i = 0; i < strlen(string); i++) { - result = ((result << 5) + result) ^ string[i]; - } - - return result; -} - -template -constexpr uint32_t hash_string_const(char const (&string)[N]) +inline uint32_t hash_string(const char* string) { unsigned long result = 5381; - for (size_t i = 0; i < N-1; i++) { + for (size_t i = 0; i < strlen(string); i++) + { result = ((result << 5) + result) ^ string[i]; } return result; } -struct fxNativeContext { +template constexpr uint32_t hash_string_const(char const (&string)[N]) +{ + unsigned long result = 5381; + + for (size_t i = 0; i < N - 1; i++) + { + result = ((result << 5) + result) ^ string[i]; + } + + return result; +} + +struct fxNativeContext +{ int numArguments; int numResults; int hasError; @@ -77,76 +82,83 @@ struct fxNativeContext { uint64_t result; }; -typedef void (*CallbackT)(fxNativeContext *); +typedef void (*CallbackT)(fxNativeContext*); -class ScriptContext { -public: - enum { MaxArguments = 32, ArgumentSize = sizeof(uint64_t) }; +class ScriptContext +{ + public: + enum + { + MaxArguments = 32, + ArgumentSize = sizeof(uint64_t) + }; -protected: - void *m_argumentBuffer; + protected: + void* m_argumentBuffer; int m_numArguments; int m_numResults; - int *m_has_error; - uint64_t *m_nativeIdentifier; - void *m_result; + int* m_has_error; + uint64_t* m_nativeIdentifier; + void* m_result; - fxNativeContext *m_native_context; + fxNativeContext* m_native_context; -public: + public: inline ScriptContext() = default; -public: - void ThrowNativeError(const char *msg, ...); + public: + void ThrowNativeError(const char* msg, ...); bool HasError() { return *m_has_error == 1; } void Reset(); -public: - template - struct index {}; + public: + template struct index + { + }; - template - struct gen_seq : gen_seq {}; + template struct gen_seq : gen_seq + { + }; - template - struct gen_seq<0, Is...> : index {}; + template struct gen_seq<0, Is...> : index + { + }; - template - inline const std::tuple GetArguments() { - return GetArgumentsImpl(gen_seq()); - } + template inline const std::tuple GetArguments() { return GetArgumentsImpl(gen_seq()); } - template - inline const std::tuple GetArgumentsImpl(index) { + template inline const std::tuple GetArgumentsImpl(index) + { return std::make_tuple(GetArgument(Is)...); } - template - inline const T &GetArgument(int index) { - auto functionData = (uint64_t *)m_argumentBuffer; + template inline const T& GetArgument(int index) + { + auto functionData = (uint64_t*)m_argumentBuffer; - return *reinterpret_cast(&functionData[index]); + return *reinterpret_cast(&functionData[index]); } - template - inline void SetArgument(int index, const T &value) { - auto functionData = (uint64_t *)m_argumentBuffer; + template inline void SetArgument(int index, const T& value) + { + auto functionData = (uint64_t*)m_argumentBuffer; static_assert(sizeof(T) <= ArgumentSize, "Argument size of T"); - if (sizeof(T) < ArgumentSize) { - *reinterpret_cast(&functionData[index]) = 0; + if (sizeof(T) < ArgumentSize) + { + *reinterpret_cast(&functionData[index]) = 0; } - *reinterpret_cast(&functionData[index]) = value; + *reinterpret_cast(&functionData[index]) = value; } - template - inline const T &CheckArgument(int index) { - const auto &argument = GetArgument(index); + template inline const T& CheckArgument(int index) + { + const auto& argument = GetArgument(index); - if (argument == T()) { + if (argument == T()) + { throw std::runtime_error("Argument at index %d was null."); } @@ -155,56 +167,61 @@ public: inline int GetArgumentCount() { return m_numArguments; } - template - inline void Push(const T &value) { - auto functionData = (uint64_t *)m_argumentBuffer; + template inline void Push(const T& value) + { + auto functionData = (uint64_t*)m_argumentBuffer; static_assert(sizeof(T) <= ArgumentSize, "Argument size of T"); - if (sizeof(T) < ArgumentSize) { - *reinterpret_cast(&functionData[m_numArguments]) = 0; + if (sizeof(T) < ArgumentSize) + { + *reinterpret_cast(&functionData[m_numArguments]) = 0; } - *reinterpret_cast(&functionData[m_numArguments]) = value; + *reinterpret_cast(&functionData[m_numArguments]) = value; m_numArguments++; m_native_context->numArguments++; } - inline void PushString(const char *value) { - auto functionData = (uint64_t *)m_argumentBuffer; + inline void PushString(const char* value) + { + auto functionData = (uint64_t*)m_argumentBuffer; - *reinterpret_cast(&functionData[m_numArguments]) = value; + *reinterpret_cast(&functionData[m_numArguments]) = value; } - template - inline void SetResult(const T &value) { - auto functionData = (uint64_t *)m_result; + template inline void SetResult(const T& value) + { + auto functionData = (uint64_t*)m_result; - if (sizeof(T) < ArgumentSize) { - *reinterpret_cast(&functionData[0]) = 0; + if (sizeof(T) < ArgumentSize) + { + *reinterpret_cast(&functionData[0]) = 0; } - *reinterpret_cast(&functionData[0]) = value; + *reinterpret_cast(&functionData[0]) = value; m_numResults = 1; m_numArguments = 0; } - template - inline T GetResult() { - auto functionData = (uint64_t *)m_result; + template inline T GetResult() + { + auto functionData = (uint64_t*)m_result; - return *reinterpret_cast(functionData); + return *reinterpret_cast(functionData); } - inline void *GetArgumentBuffer() { return m_argumentBuffer; } + inline void* GetArgumentBuffer() { return m_argumentBuffer; } inline int GetNumArguments() { return m_native_context->numArguments; } }; -class ScriptContextRaw : public ScriptContext { -public: - inline ScriptContextRaw(fxNativeContext &context) { +class ScriptContextRaw : public ScriptContext +{ + public: + inline ScriptContextRaw(fxNativeContext& context) + { m_argumentBuffer = context.arguments; m_numArguments = context.numArguments; @@ -215,31 +232,33 @@ public: m_result = &context.result; } - inline ScriptContextRaw() { + inline ScriptContextRaw() + { m_numResults = 0; m_numArguments = 0; } }; -using TNativeHandler = std::function; +using TNativeHandler = std::function; -template -using TypedTNativeHandler = T(ScriptContext &); +template using TypedTNativeHandler = T(ScriptContext&); -class ScriptEngine { -public: +class ScriptEngine +{ + public: static tl::optional GetNativeHandler(uint64_t nativeIdentifier); static tl::optional GetNativeHandler(std::string name); - static bool CallNativeHandler(uint64_t nativeIdentifier, ScriptContext &context); + static bool CallNativeHandler(uint64_t nativeIdentifier, ScriptContext& context); static void RegisterNativeHandlerInt(uint64_t nativeIdentifier, TNativeHandler function); - template - static void RegisterNativeHandler(const char *nativeName, TypedTNativeHandler function) { - auto lambda = [=](counterstrikesharp::ScriptContext &context) { + template static void RegisterNativeHandler(const char* nativeName, TypedTNativeHandler function) + { + auto lambda = [=](counterstrikesharp::ScriptContext& context) { auto value = function(context); - if (!context.HasError()) { + if (!context.HasError()) + { context.SetResult(value); } }; @@ -247,13 +266,14 @@ public: RegisterNativeHandlerInt(hash_string(nativeName), lambda); } - static void RegisterNativeHandler(const char *nativeName, TypedTNativeHandler function) { + static void RegisterNativeHandler(const char* nativeName, TypedTNativeHandler function) + { RegisterNativeHandlerInt(hash_string(nativeName), function); } - static void InvokeNative(counterstrikesharp::fxNativeContext &context); + static void InvokeNative(counterstrikesharp::fxNativeContext& context); -private: + private: static ScriptContextRaw m_context; }; -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/utils/string.h b/src/utils/string.h index 1141a541..eed8fe0f 100644 --- a/src/utils/string.h +++ b/src/utils/string.h @@ -23,7 +23,8 @@ std::wstring widen(const std::string& str) { std::wostringstream wstm; const auto& ctfacet = std::use_facet>(wstm.getloc()); - for (size_t i = 0; i < str.size(); ++i) { + for (size_t i = 0; i < str.size(); ++i) + { wstm << ctfacet.widen(str[i]); } return wstm.str(); @@ -39,9 +40,10 @@ std::string narrow(const std::wstring& str) // Correct code. const auto& ctfacet = std::use_facet>(stm.getloc()); - for (size_t i = 0; i < str.size(); ++i) { + for (size_t i = 0; i < str.size(); ++i) + { stm << ctfacet.narrow(str[i], 0); } return stm.str(); } -} \ No newline at end of file +} // namespace counterstrikesharp diff --git a/src/utils/virtual.h b/src/utils/virtual.h index 5f52a2e1..e9552a2e 100644 --- a/src/utils/virtual.h +++ b/src/utils/virtual.h @@ -23,31 +23,34 @@ #define CALL_VIRTUAL(retType, idx, ...) vmt::CallVirtual(idx, __VA_ARGS__) namespace vmt { -template -inline T GetVMethod(uint32 uIndex, void *pClass) { - if (!pClass) { +template inline T GetVMethod(uint32 uIndex, void* pClass) +{ + if (!pClass) + { return T(); } - void **pVTable = *static_cast(pClass); - if (!pVTable) { + void** pVTable = *static_cast(pClass); + if (!pVTable) + { return T(); } return reinterpret_cast(pVTable[uIndex]); } -template -inline T CallVirtual(uint32 uIndex, void *pClass, Args... args) { +template inline T CallVirtual(uint32 uIndex, void* pClass, Args... args) +{ #ifdef _WIN32 - auto pFunc = GetVMethod(uIndex, pClass); + auto pFunc = GetVMethod(uIndex, pClass); #else - auto pFunc = GetVMethod(uIndex, pClass); + auto pFunc = GetVMethod(uIndex, pClass); #endif - if (!pFunc) { + if (!pFunc) + { return T(); } return pFunc(pClass, args...); } -} // namespace vmt \ No newline at end of file +} // namespace vmt