diff --git a/src/core/engine_trace.cpp b/src/core/engine_trace.cpp index 75544175e..1e4f67fe0 100644 --- a/src/core/engine_trace.cpp +++ b/src/core/engine_trace.cpp @@ -18,13 +18,11 @@ #include "core/log.h" -namespace counterstrikesharp -{ +namespace counterstrikesharp { CTraceFilterHitAll g_HitAllFilter; -bool CSimpleTraceFilter::ShouldHitEntity(IHandleEntity *pServerEntity, int contentsMask) -{ +bool CSimpleTraceFilter::ShouldHitEntity(IHandleEntity *pServerEntity, int contentsMask) { // int index = ExcIndexFromBaseHandle(pServerEntity->GetRefEHandle()); // if (index == m_index_to_exclude) // return false; @@ -32,9 +30,7 @@ bool CSimpleTraceFilter::ShouldHitEntity(IHandleEntity *pServerEntity, int conte return true; } -TraceType_t TraceFilterProxy::GetTraceType() const -{ - +TraceType_t TraceFilterProxy::GetTraceType() const { auto nativeContext = fxNativeContext{}; auto scriptContext = ScriptContextRaw(nativeContext); @@ -43,8 +39,7 @@ TraceType_t TraceFilterProxy::GetTraceType() const return scriptContext.GetResult(); } -bool TraceFilterProxy::ShouldHitEntity(IHandleEntity *pServerEntity, int contentsMask) -{ +bool TraceFilterProxy::ShouldHitEntity(IHandleEntity *pServerEntity, int contentsMask) { return true; // auto entity = ExcIndexFromBaseHandle(pServerEntity->GetRefEHandle()); // if (entity < 0) @@ -67,14 +62,8 @@ bool TraceFilterProxy::ShouldHitEntity(IHandleEntity *pServerEntity, int content return true;*/ } -void TraceFilterProxy::SetShouldHitEntityCallback(CallbackT cb) -{ - m_cb_should_hit_entity = cb; -} +void TraceFilterProxy::SetShouldHitEntityCallback(CallbackT cb) { m_cb_should_hit_entity = cb; } -void TraceFilterProxy::SetGetTraceTypeCallback(CallbackT cb) -{ - m_cb_get_trace_type = cb; -} +void TraceFilterProxy::SetGetTraceTypeCallback(CallbackT cb) { m_cb_get_trace_type = cb; } -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/core/engine_trace.h b/src/core/engine_trace.h index e62a1c82a..12993e503 100644 --- a/src/core/engine_trace.h +++ b/src/core/engine_trace.h @@ -20,46 +20,33 @@ #include "scripting/callback_manager.h" -namespace counterstrikesharp -{ -class TraceFilterProxy : public ITraceFilter -{ - public: - TraceFilterProxy() - { - } +namespace counterstrikesharp { +class TraceFilterProxy : public ITraceFilter { +public: + TraceFilterProxy() {} bool ShouldHitEntity(IHandleEntity *pServerEntity, int contentsMask); TraceType_t GetTraceType() const; void SetShouldHitEntityCallback(CallbackT cb); void SetGetTraceTypeCallback(CallbackT cb); - private: +private: CallbackT m_cb_should_hit_entity; CallbackT m_cb_get_trace_type; }; -class CSimpleTraceFilter : public ITraceFilter -{ - public: - CSimpleTraceFilter(int index) : m_index_to_exclude(index) - { - } +class CSimpleTraceFilter : public ITraceFilter { +public: + CSimpleTraceFilter(int index) + : m_index_to_exclude(index) {} bool ShouldHitEntity(IHandleEntity *pServerEntity, int contentsMask); - TraceType_t GetTraceType() const - { - return TRACE_EVERYTHING; - } + TraceType_t GetTraceType() const { return TRACE_EVERYTHING; } - private: +private: int m_index_to_exclude = -1; }; -enum RayType -{ - RayType_EndPoint, - RayType_Infinite -}; +enum RayType { RayType_EndPoint, RayType_Infinite }; -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/core/global_listener.h b/src/core/global_listener.h index 6f3f17acd..c921ec321 100644 --- a/src/core/global_listener.h +++ b/src/core/global_listener.h @@ -31,50 +31,34 @@ #pragma once -namespace counterstrikesharp -{ -class GlobalClass -{ - public: +namespace counterstrikesharp { +class GlobalClass { +public: virtual ~GlobalClass() = default; - GlobalClass() - { + GlobalClass() { m_pGlobalClassNext = GlobalClass::head; GlobalClass::head = this; } - public: - virtual void OnStartup() - { - } - virtual void OnShutdown() - { - } - virtual void OnAllInitialized() - { - } - virtual void OnAllInitialized_Post() - { - } - virtual void OnLevelChange(const char *mapName) - { - } - virtual void OnLevelEnd() - { - } +public: + virtual void OnStartup() {} + virtual void OnShutdown() {} + virtual void OnAllInitialized() {} + virtual void OnAllInitialized_Post() {} + virtual void OnLevelChange(const char *mapName) {} + virtual void OnLevelEnd() {} - public: +public: GlobalClass *m_pGlobalClassNext; static GlobalClass *head; }; -} // namespace counterstrikesharp +} // namespace counterstrikesharp -#define CALL_GLOBAL_LISTENER(func) \ - GlobalClass *pBase = GlobalClass::head; \ - pBase = GlobalClass::head; \ - while (pBase) \ - { \ - pBase->func; \ - pBase = pBase->m_pGlobalClassNext; \ +#define CALL_GLOBAL_LISTENER(func) \ + GlobalClass *pBase = GlobalClass::head; \ + pBase = GlobalClass::head; \ + while (pBase) { \ + pBase->func; \ + pBase = pBase->m_pGlobalClassNext; \ } \ No newline at end of file diff --git a/src/core/globals.cpp b/src/core/globals.cpp index 99e12eb58..86b25a0af 100644 --- a/src/core/globals.cpp +++ b/src/core/globals.cpp @@ -14,11 +14,9 @@ #include "utils/virtual.h" #include -namespace counterstrikesharp -{ +namespace counterstrikesharp { -namespace globals -{ +namespace globals { IVEngineServer *engine = nullptr; IGameEventManager2 *gameEventManager = nullptr; IGameEventSystem *gameEventSystem = nullptr; @@ -47,7 +45,7 @@ CGlobalEntityList *globalEntityList = nullptr; CounterStrikeSharpMMPlugin *mmPlugin = nullptr; SourceHook::Impl::CSourceHookImpl source_hook_impl; SourceHook::ISourceHook *source_hook = &source_hook_impl; -ISmmAPI* ismm = nullptr; +ISmmAPI *ismm = nullptr; // Custom Managers CallbackManager callbackManager; @@ -55,23 +53,20 @@ EventManager eventManager; PlayerManager playerManager; TimerSystem timerSystem; -void Initialize() -{ +void Initialize() { gameEventManager = (IGameEventManager2 *)(CALL_VIRTUAL(uintptr_t, 91, server) - 8); CSSHARP_CORE_TRACE("[GLOBALS] globals::gameEventManager: {0}", (void *)gameEventManager); } int source_hook_pluginid = 0; -CGlobalVars *getGlobalVars() -{ +CGlobalVars *getGlobalVars() { INetworkGameServer *server = networkServerService->GetIGameServer(); - if (!server) - return nullptr; + if (!server) return nullptr; return networkServerService->GetIGameServer()->GetGlobals(); } -} // namespace globals -} // namespace counterstrikesharp +} // namespace globals +} // namespace counterstrikesharp diff --git a/src/core/globals.h b/src/core/globals.h index 4e1bfc0f9..660d8af97 100644 --- a/src/core/globals.h +++ b/src/core/globals.h @@ -27,8 +27,7 @@ class ICvar; class IGameEventSystem; class CounterStrikeSharpMMPlugin; -namespace counterstrikesharp -{ +namespace counterstrikesharp { class EntityListener; class EventManager; class UserMessageManager; @@ -41,8 +40,7 @@ class TimerSystem; class ChatCommands; class HookManager; -namespace globals -{ +namespace globals { extern IVEngineServer *engine; extern IGameEventManager2 *gameEventManager; @@ -90,9 +88,9 @@ void Initialize(); // and active) otherwise that'll be nullptr! CGlobalVars *getGlobalVars(); -} // namespace globals +} // namespace globals -} // namespace counterstrikesharp +} // namespace counterstrikesharp #undef SH_GLOB_SHPTR #define SH_GLOB_SHPTR counterstrikesharp::globals::source_hook diff --git a/src/core/log.cpp b/src/core/log.cpp index 26af38488..3f7bd99b7 100644 --- a/src/core/log.cpp +++ b/src/core/log.cpp @@ -3,31 +3,28 @@ #include #include -namespace counterstrikesharp -{ +namespace counterstrikesharp { std::shared_ptr Log::m_core_logger; -void Log::Init() -{ +void Log::Init() { std::vector logSinks; auto ansiColorSink = std::make_shared(); ansiColorSink->set_color(spdlog::level::trace, ansiColorSink->yellow); logSinks.emplace_back(ansiColorSink); - logSinks.emplace_back(std::make_shared("counterstrikesharp.log", true)); + logSinks.emplace_back( + std::make_shared("counterstrikesharp.log", true)); logSinks[0]->set_pattern("%^[%T.%e] %n: %v%$"); logSinks[1]->set_pattern("[%T.%e] [%l] %n: %v"); - m_core_logger = std::make_shared("CSSharp", begin(logSinks), end(logSinks)); spdlog::register_logger(m_core_logger); m_core_logger->set_level(spdlog::level::trace); m_core_logger->flush_on(spdlog::level::info); } -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 edfbd84bb..3b7544cb4 100644 --- a/src/core/log.h +++ b/src/core/log.h @@ -5,23 +5,18 @@ #include #include -namespace counterstrikesharp -{ -class Log -{ - public: +namespace counterstrikesharp { +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__) diff --git a/src/core/managers/event_manager.cpp b/src/core/managers/event_manager.cpp index 0afd8ba8b..eea5a1f48 100644 --- a/src/core/managers/event_manager.cpp +++ b/src/core/managers/event_manager.cpp @@ -36,31 +36,22 @@ SH_DECL_HOOK2(IGameEventManager2, FireEvent, SH_NOATTRIB, 0, bool, IGameEvent *, bool); -namespace counterstrikesharp -{ +namespace counterstrikesharp { -EventManager::EventManager() -{ -} +EventManager::EventManager() {} -EventManager::~EventManager() -{ -} +EventManager::~EventManager() {} -void EventManager::OnStartup() -{ -} +void EventManager::OnStartup() {} -void EventManager::OnAllInitialized() -{ - SH_ADD_HOOK(IGameEventManager2, FireEvent, globals::gameEventManager, SH_MEMBER(this, &EventManager::OnFireEvent), - false); +void EventManager::OnAllInitialized() { + SH_ADD_HOOK(IGameEventManager2, FireEvent, globals::gameEventManager, + SH_MEMBER(this, &EventManager::OnFireEvent), false); SH_ADD_HOOK(IGameEventManager2, FireEvent, globals::gameEventManager, SH_MEMBER(this, &EventManager::OnFireEvent_Post), true); } -void EventManager::OnShutdown() -{ +void EventManager::OnShutdown() { SH_REMOVE_HOOK(IGameEventManager2, FireEvent, globals::gameEventManager, SH_MEMBER(this, &EventManager::OnFireEvent), false); SH_REMOVE_HOOK(IGameEventManager2, FireEvent, globals::gameEventManager, @@ -69,16 +60,12 @@ void EventManager::OnShutdown() globals::gameEventManager->RemoveListener(this); } -void EventManager::FireGameEvent(IGameEvent *event) -{ -} +void EventManager::FireGameEvent(IGameEvent *event) {} -bool EventManager::HookEvent(const char *name, CallbackT callback, bool post) -{ +bool EventManager::HookEvent(const char *name, CallbackT callback, bool post) { EventHook *p_hook; - if (!globals::gameEventManager->FindListener(this, name)) - { + if (!globals::gameEventManager->FindListener(this, name)) { globals::gameEventManager->AddListener(this, name, true); } @@ -86,17 +73,13 @@ bool EventManager::HookEvent(const char *name, CallbackT callback, bool post) auto search = m_hooks.find(name); // If hook struct is not found - if (search == m_hooks.end()) - { + if (search == m_hooks.end()) { p_hook = new EventHook(); - if (post) - { + if (post) { p_hook->PostHook = globals::callbackManager.CreateCallback(name); p_hook->PostHook->AddListener(callback); - } - else - { + } else { p_hook->PreHook = globals::callbackManager.CreateCallback(name); p_hook->PreHook->AddListener(callback); } @@ -106,25 +89,18 @@ bool EventManager::HookEvent(const char *name, CallbackT callback, bool post) m_hooks[name] = p_hook; return true; - } - else - { + } else { p_hook = search->second; } - if (post) - { - if (!p_hook->PostHook) - { + if (post) { + if (!p_hook->PostHook) { p_hook->PostHook = globals::callbackManager.CreateCallback(""); } p_hook->PostHook->AddListener(callback); - } - else - { - if (!p_hook->PreHook) - { + } else { + if (!p_hook->PreHook) { p_hook->PreHook = globals::callbackManager.CreateCallback(""); ; } @@ -135,41 +111,32 @@ bool EventManager::HookEvent(const char *name, CallbackT callback, bool post) return true; } -bool EventManager::UnhookEvent(const char *name, CallbackT callback, bool post) -{ +bool EventManager::UnhookEvent(const char *name, CallbackT callback, bool post) { EventHook *p_hook; ScriptCallback *p_callback; auto search = m_hooks.find(name); - if (search == m_hooks.end()) - { + if (search == m_hooks.end()) { return false; } p_hook = search->second; - if (post) - { + if (post) { p_callback = p_hook->PostHook; - } - else - { + } else { p_callback = p_hook->PreHook; } // Remove from function list - if (p_callback == nullptr) - { + if (p_callback == nullptr) { return false; } p_callback = nullptr; - if (post) - { + if (post) { p_hook->PostHook = nullptr; - } - else - { + } else { p_hook->PreHook = nullptr; } @@ -180,25 +147,21 @@ bool EventManager::UnhookEvent(const char *name, CallbackT callback, bool post) return true; } -bool EventManager::OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast) -{ +bool EventManager::OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast) { EventHook *p_hook; const char *name; - if (!pEvent) - { + if (!pEvent) { RETURN_META_VALUE(MRES_IGNORED, false); } name = pEvent->GetName(); auto search = m_hooks.find(name); - if (search != m_hooks.end()) - { + if (search != m_hooks.end()) { auto p_callback = search->second->PreHook; - if (p_callback) - { + if (p_callback) { CSSHARP_CORE_INFO("Pushing event `{0}` pointer: {1}", name, (void *)pEvent); p_callback->ScriptContext().Reset(); p_callback->ScriptContext().SetArgument(0, pEvent); @@ -211,8 +174,7 @@ bool EventManager::OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast) RETURN_META_VALUE(MRES_IGNORED, true); } -bool EventManager::OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast) -{ +bool EventManager::OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast) { RETURN_META_VALUE(MRES_IGNORED, true); } -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/core/managers/event_manager.h b/src/core/managers/event_manager.h index 4c3a19a92..b0dbf1c8b 100644 --- a/src/core/managers/event_manager.h +++ b/src/core/managers/event_manager.h @@ -43,16 +43,13 @@ class CUtlString; #include "core/globals.h" #include "scripting/script_engine.h" -namespace counterstrikesharp -{ +namespace counterstrikesharp { class ScriptCallback; class PluginFunction; -} // namespace counterstrikesharp +} // namespace counterstrikesharp -struct EventHook -{ - EventHook() - { +struct EventHook { + EventHook() { PreHook = nullptr; PostHook = nullptr; } @@ -61,33 +58,31 @@ struct EventHook std::string name; }; -namespace counterstrikesharp -{ +namespace counterstrikesharp { -class EventManager : public IGameEventListener2, public GlobalClass -{ - public: +class EventManager : public IGameEventListener2, public GlobalClass { +public: EventManager(); ~EventManager(); - public: // GlobalClass +public: // GlobalClass void OnShutdown() override; void OnAllInitialized() override; void OnStartup() override; - public: // IGameEventListener2 +public: // IGameEventListener2 void FireGameEvent(IGameEvent *event) override; - public: +public: bool UnhookEvent(const char *name, CallbackT callback, bool post); bool HookEvent(const char *name, CallbackT callback, bool post); - private: +private: bool OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast); bool OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast); - private: +private: std::map m_hooks; }; -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/core/managers/player_manager.cpp b/src/core/managers/player_manager.cpp index 207b2d5f6..c673b75a5 100644 --- a/src/core/managers/player_manager.cpp +++ b/src/core/managers/player_manager.cpp @@ -40,27 +40,50 @@ #include "scripting/callback_manager.h" #include -SH_DECL_HOOK4_void(IServerGameClients, ClientActive, SH_NOATTRIB, 0, CPlayerSlot, bool, const char *, uint64); -SH_DECL_HOOK5_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, CPlayerSlot, int, const char *, uint64, +SH_DECL_HOOK4_void( + IServerGameClients, ClientActive, SH_NOATTRIB, 0, CPlayerSlot, bool, const char *, uint64); +SH_DECL_HOOK5_void(IServerGameClients, + ClientDisconnect, + SH_NOATTRIB, + 0, + CPlayerSlot, + int, + const char *, + uint64, const char *); -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_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, CPlayerSlot, const CCommand &); - -namespace counterstrikesharp -{ - -void PlayerManager::OnStartup() -{ -} - -void PlayerManager::OnAllInitialized() -{ +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 &); + +namespace counterstrikesharp { + +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, @@ -76,14 +99,15 @@ void PlayerManager::OnAllInitialized() 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_activate_callback = globals::callbackManager.CreateCallback("OnMapStart"); } -void PlayerManager::OnShutdown() -{ +void PlayerManager::OnShutdown() { SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false); SH_REMOVE_HOOK(IServerGameClients, ClientConnect, globals::serverGameClients, @@ -105,16 +129,19 @@ void PlayerManager::OnShutdown() globals::callbackManager.ReleaseCallback(m_on_activate_callback); } -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); +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); int client = slot.Get(); CPlayer *pPlayer = &m_players[client]; - if (pPlayer->IsConnected()) - { + if (pPlayer->IsConnected()) { OnClientDisconnect(slot, 0, pszName, xuid, pszNetworkID); OnClientDisconnect_Post(slot, 0, pszName, xuid, pszNetworkID); } @@ -127,22 +154,23 @@ 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) - { -// auto cancel = m_on_client_connect_callback->ScriptContext().GetArgument(0); -// auto cancelReason = m_on_client_connect_callback->ScriptContext().GetArgument(1); -// -// CSSHARP_CORE_TRACE("On Client Connect Callback Results: {}, {}", cancel, cancelReason); -// -// if (cancel) -// { -// pRejectReason->AppendFormat("%s", cancelReason); -// -// if (!pPlayer->IsFakeClient()) -// { -// RETURN_META_VALUE(MRES_SUPERCEDE, false); -// } -// } + 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); + // + // CSSHARP_CORE_TRACE("On Client Connect Callback Results: {}, {}", cancel, + // cancelReason); + // + // if (cancel) + // { + // pRejectReason->AppendFormat("%s", cancelReason); + // + // if (!pPlayer->IsFakeClient()) + // { + // RETURN_META_VALUE(MRES_SUPERCEDE, false); + // } + // } } m_user_id_lookup[globals::engine->GetPlayerUserId(slot).Get()] = client; @@ -150,47 +178,50 @@ 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) -{ - CSSHARP_CORE_TRACE("[PlayerManager][OnClientConnect_Post] - {}, {}, {}", slot.Get(), pszName, pszNetworkID); +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); 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) -{ - CSSHARP_CORE_TRACE("[PlayerManager][OnClientPutInServer] - {}, {}, {}", slot.Get(), pszName, type); - +void PlayerManager::OnClientPutInServer(CPlayerSlot slot, + char const *pszName, + int type, + uint64 xuid) { + 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; } @@ -216,38 +247,41 @@ void PlayerManager::OnClientPutInServer(CPlayerSlot slot, char const *pszName, i m_on_client_put_in_server_callback->Execute(); } -void PlayerManager::OnClientDisconnect(CPlayerSlot slot, /* ENetworkDisconnectionReason */ int reason, - const char *pszName, uint64 xuid, const char *pszNetworkID) -{ - CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect] - {}, {}, {}", slot.Get(), pszName, pszNetworkID); +void PlayerManager::OnClientDisconnect(CPlayerSlot slot, + /* ENetworkDisconnectionReason */ int reason, + const char *pszName, + uint64 xuid, + const char *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->Execute(); } - if (pPlayer->WasCountedAsInGame()) - { + if (pPlayer->WasCountedAsInGame()) { m_player_count--; } // globals::entityListener.HandleEntityDeleted(pPlayer->GetBaseEntity(), client); } -void PlayerManager::OnClientDisconnect_Post(CPlayerSlot slot, /* ENetworkDisconnectionReason */ int reason, - const char *pszName, uint64 xuid, const char *pszNetworkID) const -{ - CSSHARP_CORE_TRACE("[PlayerManager][OnClientDisconnect_Post] - {}, {}, {}", slot.Get(), pszName, pszNetworkID); +void PlayerManager::OnClientDisconnect_Post(CPlayerSlot slot, + /* ENetworkDisconnectionReason */ int reason, + const char *pszName, + uint64 xuid, + const char *pszNetworkID) const { + 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; } @@ -259,37 +293,33 @@ void PlayerManager::OnClientDisconnect_Post(CPlayerSlot slot, /* ENetworkDisconn m_on_client_disconnect_post_callback->Execute(); } -void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax) const -{ +void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax) const { m_on_activate_callback->ScriptContext().Reset(); m_on_activate_callback->ScriptContext().Push(globals::getGlobalVars()->mapname); m_on_activate_callback->Execute(); } -void PlayerManager::OnLevelEnd() -{ +void PlayerManager::OnLevelEnd() { CSSHARP_CORE_TRACE("[PlayerManager][OnLevelEnd]"); - for (int i = 1; i <= m_max_clients; i++) - { - if (m_players[i].IsConnected()) - { - OnClientDisconnect(m_players[i].m_slot, 0, m_players[i].GetName(), 0, m_players[i].GetIpAddress()); - OnClientDisconnect_Post(m_players[i].m_slot, 0, m_players[i].GetName(), 0, m_players[i].GetIpAddress()); + for (int i = 1; i <= m_max_clients; i++) { + if (m_players[i].IsConnected()) { + OnClientDisconnect(m_players[i].m_slot, 0, m_players[i].GetName(), 0, + m_players[i].GetIpAddress()); + OnClientDisconnect_Post(m_players[i].m_slot, 0, m_players[i].GetName(), 0, + m_players[i].GetIpAddress()); } } m_player_count = 0; } -void PlayerManager::OnClientCommand(CPlayerSlot slot, const CCommand &args) const -{ +void PlayerManager::OnClientCommand(CPlayerSlot slot, const CCommand &args) const { CSSHARP_CORE_TRACE("[PlayerManager][OnClientCommand] - {}, {}", slot.Get(), args.ArgS()); int client = slot.Get(); CPlayer *pPlayer = &m_players[client]; - if (!pPlayer->IsConnected()) - { + if (!pPlayer->IsConnected()) { return; } @@ -302,25 +332,14 @@ void PlayerManager::OnClientCommand(CPlayerSlot slot, const CCommand &args) cons // } } -int PlayerManager::ListenClient() const -{ - return m_listen_client; -} +int PlayerManager::ListenClient() const { return m_listen_client; } -int PlayerManager::NumPlayers() const -{ - return m_player_count; -} +int PlayerManager::NumPlayers() const { return m_player_count; } -int PlayerManager::MaxClients() const -{ - return m_max_clients; -} +int PlayerManager::MaxClients() const { return m_max_clients; } -CPlayer *PlayerManager::GetPlayerByIndex(int client) const -{ - if (client > m_max_clients || client < 1) - { +CPlayer *PlayerManager::GetPlayerByIndex(int client) const { + if (client > m_max_clients || client < 1) { return nullptr; } @@ -366,80 +385,49 @@ CPlayer *PlayerManager::GetPlayerByIndex(int client) const // return nullptr; // } -void PlayerManager::InvalidatePlayer(CPlayer *pPlayer) 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(); } -CPlayer::CPlayer() -{ -} +CPlayer::CPlayer() {} -void CPlayer::Initialize(const char *name, const char *ip, CPlayerSlot slot) -{ +void CPlayer::Initialize(const char *name, const char *ip, CPlayerSlot slot) { m_is_connected = true; m_slot = slot; m_name = std::string(name); m_ip_address = std::string(ip); } -IPlayerInfo *CPlayer::GetPlayerInfo() const -{ - return m_info; -} +IPlayerInfo *CPlayer::GetPlayerInfo() const { return m_info; } -const char *CPlayer::GetName() const -{ - return strdup(m_name.c_str()); -} +const char *CPlayer::GetName() const { return strdup(m_name.c_str()); } -const char *CPlayer::GetAuthString() -{ - return ""; -} +const char *CPlayer::GetAuthString() { return ""; } -bool CPlayer::IsConnected() const -{ - return m_is_connected; -} +bool CPlayer::IsConnected() const { return m_is_connected; } -bool CPlayer::IsFakeClient() const -{ - return m_is_fake_client; -} +bool CPlayer::IsFakeClient() const { return m_is_fake_client; } -bool CPlayer::IsAuthorized() const -{ - return m_is_authorized; -} +bool CPlayer::IsAuthorized() const { return m_is_authorized; } -bool CPlayer::IsAuthStringValidated() const -{ - if (!IsFakeClient()) - { +bool CPlayer::IsAuthStringValidated() const { + if (!IsFakeClient()) { return globals::engine->IsClientFullyAuthenticated(m_slot); } } -void CPlayer::Authorize() -{ - m_is_authorized = true; -} +void CPlayer::Authorize() { m_is_authorized = true; } -void CPlayer::PrintToConsole(const char *message) const -{ - if (m_is_connected == false || m_is_fake_client == true) - { +void CPlayer::PrintToConsole(const char *message) const { + 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; } @@ -461,18 +449,11 @@ void CPlayer::PrintToConsole(const char *message) const // globals::user_message_manager.SendCenterMessage(m_i_index, message); // } -void CPlayer::SetName(const char *name) -{ - m_name = strdup(name); -} +void CPlayer::SetName(const char *name) { m_name = strdup(name); } -INetChannelInfo *CPlayer::GetNetInfo() const -{ - return globals::engine->GetPlayerNetInfo(m_slot); -} +INetChannelInfo *CPlayer::GetNetInfo() const { return globals::engine->GetPlayerNetInfo(m_slot); } -PlayerManager::PlayerManager() -{ +PlayerManager::PlayerManager() { m_max_clients = 64; m_players = new CPlayer[66]; m_player_count = 0; @@ -480,125 +461,75 @@ PlayerManager::PlayerManager() memset(m_user_id_lookup, 0, sizeof(int) * (USHRT_MAX + 1)); } -bool CPlayer::WasCountedAsInGame() const -{ - return m_is_in_game; -} +bool CPlayer::WasCountedAsInGame() const { return m_is_in_game; } -int CPlayer::GetUserId() -{ - if (m_user_id == -1) - { +int CPlayer::GetUserId() { + if (m_user_id == -1) { m_user_id = globals::engine->GetPlayerUserId(m_slot).Get(); } return m_user_id; } -bool CPlayer::IsInGame() const -{ - return m_is_in_game; // && (m_p_edict->GetUnknown() != nullptr); +bool CPlayer::IsInGame() const { + return m_is_in_game; // && (m_p_edict->GetUnknown() != nullptr); } -void CPlayer::Kick(const char *kickReason) -{ +void CPlayer::Kick(const char *kickReason) { char buffer[255]; sprintf(buffer, "kickid %d %s\n", GetUserId(), kickReason); globals::engine->ServerCommand(buffer); } -const char *CPlayer::GetWeaponName() const -{ - return m_info->GetWeaponName(); -} +const char *CPlayer::GetWeaponName() const { return m_info->GetWeaponName(); } -void CPlayer::ChangeTeam(int team) const -{ - m_info->ChangeTeam(team); -} +void CPlayer::ChangeTeam(int team) const { m_info->ChangeTeam(team); } -int CPlayer::GetTeam() const -{ - return m_info->GetTeamIndex(); -} +int CPlayer::GetTeam() const { return m_info->GetTeamIndex(); } -int CPlayer::GetArmor() const -{ - return m_info->GetArmorValue(); -} +int CPlayer::GetArmor() const { return m_info->GetArmorValue(); } -int CPlayer::GetFrags() const -{ - return m_info->GetFragCount(); -} +int CPlayer::GetFrags() const { return m_info->GetFragCount(); } -int CPlayer::GetDeaths() const -{ - return m_info->GetDeathCount(); -} +int CPlayer::GetDeaths() const { return m_info->GetDeathCount(); } -const char *CPlayer::GetKeyValue(const char *key) const -{ +const char *CPlayer::GetKeyValue(const char *key) const { return globals::engine->GetClientConVarValue(m_slot, key); } -Vector CPlayer::GetMaxSize() const -{ - return m_info->GetPlayerMaxs(); -} +Vector CPlayer::GetMaxSize() const { return m_info->GetPlayerMaxs(); } -Vector CPlayer::GetMinSize() const -{ - return m_info->GetPlayerMins(); -} +Vector CPlayer::GetMinSize() const { return m_info->GetPlayerMins(); } -int CPlayer::GetMaxHealth() const -{ - return m_info->GetMaxHealth(); -} +int CPlayer::GetMaxHealth() const { return m_info->GetMaxHealth(); } -const char *CPlayer::GetIpAddress() const -{ - return m_ip_address.c_str(); -} +const char *CPlayer::GetIpAddress() const { return m_ip_address.c_str(); } -const char *CPlayer::GetModelName() const -{ - return m_info->GetModelName(); -} +const char *CPlayer::GetModelName() const { return m_info->GetModelName(); } -int CPlayer::GetUserId() const -{ - return m_user_id; -} +int CPlayer::GetUserId() const { return m_user_id; } -float CPlayer::GetTimeConnected() const -{ - if (!IsConnected() || IsFakeClient()) - { +float CPlayer::GetTimeConnected() const { + if (!IsConnected() || IsFakeClient()) { return 0; } return GetNetInfo()->GetTimeConnected(); } -float CPlayer::GetLatency() const -{ +float CPlayer::GetLatency() const { return GetNetInfo()->GetLatency(FLOW_INCOMING) + GetNetInfo()->GetLatency(FLOW_OUTGOING); } -void CPlayer::Connect() -{ - if (m_is_in_game) - { +void CPlayer::Connect() { + if (m_is_in_game) { return; } m_is_in_game = true; } -void CPlayer::Disconnect() -{ +void CPlayer::Disconnect() { m_is_connected = false; m_is_in_game = false; m_name.clear(); @@ -609,24 +540,16 @@ void CPlayer::Disconnect() m_ip_address.clear(); } -QAngle CPlayer::GetAbsAngles() const -{ - return m_info->GetAbsAngles(); -} +QAngle CPlayer::GetAbsAngles() const { return m_info->GetAbsAngles(); } -Vector CPlayer::GetAbsOrigin() const -{ - return m_info->GetAbsOrigin(); -} +Vector CPlayer::GetAbsOrigin() const { return m_info->GetAbsOrigin(); } -bool CPlayer::IsAlive() const -{ - if (!IsInGame()) - { +bool CPlayer::IsAlive() const { + if (!IsInGame()) { return false; } return !m_info->IsDead(); } -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/core/managers/player_manager.h b/src/core/managers/player_manager.h index c6314df36..b1f1d68ba 100644 --- a/src/core/managers/player_manager.h +++ b/src/core/managers/player_manager.h @@ -41,19 +41,17 @@ class INetChannelInfo; class IPlayerInfo; struct edict_t; -namespace counterstrikesharp -{ +namespace counterstrikesharp { class ScriptCallback; class CBaseEntityWrapper; -class CPlayer -{ +class CPlayer { friend class PlayerManager; - public: +public: CPlayer(); - public: +public: void Initialize(const char *name, const char *ip, CPlayerSlot slot); void Connect(); void Disconnect(); @@ -63,7 +61,7 @@ class CPlayer bool IsAuthStringValidated() const; void Authorize(); - public: +public: const char *GetName() const; const char *GetAuthString(); bool IsConnected() const; @@ -94,7 +92,7 @@ class CPlayer float GetTimeConnected() const; float GetLatency() const; - public: +public: std::string m_name; IPlayerInfo *m_info = nullptr; std::string m_auth_id; @@ -109,23 +107,36 @@ class CPlayer INetChannelInfo *GetNetInfo() const; }; -class PlayerManager : public GlobalClass -{ +class PlayerManager : public GlobalClass { friend class CPlayer; - public: +public: PlayerManager(); void OnStartup() override; void OnAllInitialized() override; - bool OnClientConnect(CPlayerSlot slot, const char *pszName, uint64 xuid, const char *pszNetworkID, bool unk1, + 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, + 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 */ int reason, const char *pszName, - uint64 xuid, const char *pszNetworkID); - void OnClientDisconnect_Post(CPlayerSlot slot, /* ENetworkDisconnectionReason */ int reason, const char *pszName, - uint64 xuid, const char *pszNetworkID) const; + void OnClientDisconnect(CPlayerSlot slot, + /* ENetworkDisconnectionReason */ int reason, + const char *pszName, + uint64 xuid, + const char *pszNetworkID); + void OnClientDisconnect_Post(CPlayerSlot slot, + /* ENetworkDisconnectionReason */ int reason, + const char *pszName, + uint64 xuid, + const char *pszNetworkID) const; void OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax) const; void OnThink(bool last_tick) const; void OnShutdown() override; @@ -133,13 +144,13 @@ class PlayerManager : public GlobalClass void OnClientCommand(CPlayerSlot slot, const CCommand &args) const; int ListenClient() const; - public: +public: int NumPlayers() const; int MaxClients() const; CPlayer *GetPlayerByIndex(int client) const; CPlayer *GetClientOfUserId(int user_id) const; - private: +private: void InvalidatePlayer(CPlayer *pPlayer) const; CPlayer *m_players; @@ -157,4 +168,4 @@ class PlayerManager : public GlobalClass ScriptCallback *m_on_activate_callback; }; -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/core/memory.cpp b/src/core/memory.cpp index b42a5df6b..063d9440e 100644 --- a/src/core/memory.cpp +++ b/src/core/memory.cpp @@ -1,23 +1,23 @@ /** -* ============================================================================= -* CS2Fixes -* Copyright (C) 2023 Source2ZE -* ============================================================================= -* -* This program is free software; you can redistribute it and/or modify it under -* the terms of the GNU General Public License, version 3.0, as published by the -* Free Software Foundation. -* -* This program 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 -* this program. If not, see . -* -* This file has been modified for use in CounterStrikeSharp. -*/ + * ============================================================================= + * CS2Fixes + * Copyright (C) 2023 Source2ZE + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program 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 + * this program. If not, see . + * + * This file has been modified for use in CounterStrikeSharp. + */ #include #include @@ -25,93 +25,82 @@ #include #include -struct ModuleInfo -{ - const char *path; // in - uint8_t *base; // out - uint size; // out +struct ModuleInfo { + const char *path; // in + uint8_t *base; // out + uint size; // out }; #define PAGE_SIZE 4096 #define PAGE_ALIGN_UP(x) ((x + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)) // https://github.com/alliedmodders/sourcemod/blob/master/core/logic/MemoryUtils.cpp#L502-L587 -int GetModuleInformation(void *hModule, void **base, size_t *length) -{ - struct link_map *dlmap = (struct link_map *)hModule; - Dl_info info; - Elf64_Ehdr *file; - Elf64_Phdr *phdr; - uint16_t phdrCount; - - if (!dladdr((void *)dlmap->l_addr, &info)) - { - return 1; - } - - if (!info.dli_fbase || !info.dli_fname) - { - return 2; - } - - /* This is for our insane sanity checks :o */ - uintptr_t baseAddr = reinterpret_cast(info.dli_fbase); - file = reinterpret_cast(baseAddr); - - /* Check ELF magic */ - if (memcmp(ELFMAG, file->e_ident, SELFMAG) != 0) - { - return 3; - } - - /* Check ELF version */ - if (file->e_ident[EI_VERSION] != EV_CURRENT) - { - return 4; - } - - /* Check ELF endianness */ - if (file->e_ident[EI_DATA] != ELFDATA2LSB) - { - return 5; - } - - /* Check ELF architecture */ - if (file->e_ident[EI_CLASS] != ELFCLASS64 || file->e_machine != EM_X86_64) - { - return 6; - } - - /* For our purposes, this must be a dynamic library/shared object */ - if (file->e_type != ET_DYN) - { - return 7; - } - - phdrCount = file->e_phnum; - phdr = reinterpret_cast(baseAddr + file->e_phoff); - - for (uint16_t i = 0; i < phdrCount; i++) - { - Elf64_Phdr &hdr = phdr[i]; - - /* We only really care about the segment with executable code */ - if (hdr.p_type == PT_LOAD && hdr.p_flags == (PF_X | PF_R)) - { - /* From glibc, elf/dl-load.c: - * c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1) - * & ~(GLRO(dl_pagesize) - 1)); - * - * In glibc, the segment file size is aligned up to the nearest page size and - * added to the virtual address of the segment. We just want the size here. - */ - // lib.memorySize = PAGE_ALIGN_UP(hdr.p_filesz); - *length = PAGE_ALIGN_UP(hdr.p_filesz); - *base = (void *)(baseAddr + hdr.p_paddr); - - break; - } - } - - return 0; +int GetModuleInformation(void *hModule, void **base, size_t *length) { + struct link_map *dlmap = (struct link_map *)hModule; + Dl_info info; + Elf64_Ehdr *file; + Elf64_Phdr *phdr; + uint16_t phdrCount; + + if (!dladdr((void *)dlmap->l_addr, &info)) { + return 1; + } + + if (!info.dli_fbase || !info.dli_fname) { + return 2; + } + + /* This is for our insane sanity checks :o */ + uintptr_t baseAddr = reinterpret_cast(info.dli_fbase); + file = reinterpret_cast(baseAddr); + + /* Check ELF magic */ + if (memcmp(ELFMAG, file->e_ident, SELFMAG) != 0) { + return 3; + } + + /* Check ELF version */ + if (file->e_ident[EI_VERSION] != EV_CURRENT) { + return 4; + } + + /* Check ELF endianness */ + if (file->e_ident[EI_DATA] != ELFDATA2LSB) { + return 5; + } + + /* Check ELF architecture */ + if (file->e_ident[EI_CLASS] != ELFCLASS64 || file->e_machine != EM_X86_64) { + return 6; + } + + /* For our purposes, this must be a dynamic library/shared object */ + if (file->e_type != ET_DYN) { + return 7; + } + + phdrCount = file->e_phnum; + phdr = reinterpret_cast(baseAddr + file->e_phoff); + + for (uint16_t i = 0; i < phdrCount; i++) { + Elf64_Phdr &hdr = phdr[i]; + + /* We only really care about the segment with executable code */ + if (hdr.p_type == PT_LOAD && hdr.p_flags == (PF_X | PF_R)) { + /* From glibc, elf/dl-load.c: + * c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1) + * & ~(GLRO(dl_pagesize) - 1)); + * + * In glibc, the segment file size is aligned up to the nearest page size and + * added to the virtual address of the segment. We just want the size here. + */ + // lib.memorySize = PAGE_ALIGN_UP(hdr.p_filesz); + *length = PAGE_ALIGN_UP(hdr.p_filesz); + *base = (void *)(baseAddr + hdr.p_paddr); + + break; + } + } + + return 0; } \ No newline at end of file diff --git a/src/core/timer_system.cpp b/src/core/timer_system.cpp index 9f1730595..ab94e979b 100644 --- a/src/core/timer_system.cpp +++ b/src/core/timer_system.cpp @@ -38,56 +38,46 @@ #include "core/log.h" #include "scripting/callback_manager.h" -namespace counterstrikesharp -{ -namespace timers -{ +namespace counterstrikesharp { +namespace timers { double universal_time = 0.0f; double timer_next_think = 0.0f; -} // namespace timers +} // namespace timers timers::Timer::Timer(float interval, float exec_time, CallbackT callback, int flags) - : m_interval(interval), m_exec_time(exec_time), m_flags(flags), m_kill_me(false), m_in_exec(false) -{ + : m_interval(interval), + m_exec_time(exec_time), + m_flags(flags), + m_kill_me(false), + m_in_exec(false) { m_callback = globals::callbackManager.CreateCallback("Timer"); m_callback->AddListener(callback); } -timers::Timer::~Timer() -{ - globals::callbackManager.ReleaseCallback(m_callback); -} +timers::Timer::~Timer() { globals::callbackManager.ReleaseCallback(m_callback); } -TimerSystem::TimerSystem() -{ +TimerSystem::TimerSystem() { m_has_map_ticked = false; m_has_map_simulated = false; m_last_ticked_time = 0.0f; } -void TimerSystem::OnAllInitialized() -{ +void TimerSystem::OnAllInitialized() { m_on_tick_callback_ = globals::callbackManager.CreateCallback("OnTick"); } -void TimerSystem::OnLevelEnd() -{ +void TimerSystem::OnLevelEnd() { m_has_map_simulated = false; m_has_map_ticked = false; } -void TimerSystem::OnGameFrame(bool simulating) -{ - if (simulating && m_has_map_ticked) - { +void TimerSystem::OnGameFrame(bool simulating) { + if (simulating && m_has_map_ticked) { timers::universal_time += globals::getGlobalVars()->curtime - m_last_ticked_time; - if (!m_has_map_simulated) - { + if (!m_has_map_simulated) { m_has_map_simulated = true; } - } - else - { + } else { timers::universal_time += globals::getGlobalVars()->interval_per_tick; } @@ -95,39 +85,30 @@ void TimerSystem::OnGameFrame(bool simulating) m_has_map_ticked = true; // Handle timer tick - if (timers::universal_time >= timers::timer_next_think) - { + if (timers::universal_time >= timers::timer_next_think) { RunFrame(); timers::timer_next_think = CalculateNextThink(timers::timer_next_think, 0.1f); } - if (m_on_tick_callback_->GetFunctionCount()) - { + if (m_on_tick_callback_->GetFunctionCount()) { m_on_tick_callback_->ScriptContext().Reset(); m_on_tick_callback_->Execute(); } } -double TimerSystem::CalculateNextThink(double last_think_time, float interval) -{ - if (timers::universal_time - last_think_time - interval <= 0.1) - { +double TimerSystem::CalculateNextThink(double last_think_time, float interval) { + if (timers::universal_time - last_think_time - interval <= 0.1) { return last_think_time + interval; - } - else - { + } else { return timers::universal_time + interval; } } -void TimerSystem::RunFrame() -{ - for (int i = m_once_off_timers.size() - 1; i >= 0; i--) - { +void TimerSystem::RunFrame() { + for (int i = m_once_off_timers.size() - 1; i >= 0; i--) { auto timer = m_once_off_timers[i]; - if (timers::universal_time >= timer->m_exec_time) - { + if (timers::universal_time >= timer->m_exec_time) { timer->m_in_exec = true; timer->m_callback->ScriptContext().Reset(); timer->m_callback->Execute(); @@ -137,17 +118,14 @@ void TimerSystem::RunFrame() } } - for (int i = m_repeat_timers.size() - 1; i >= 0; i--) - { + for (int i = m_repeat_timers.size() - 1; i >= 0; i--) { auto timer = m_repeat_timers[i]; - if (timers::universal_time >= timer->m_exec_time) - { + if (timers::universal_time >= timer->m_exec_time) { timer->m_in_exec = true; timer->m_callback->ScriptContext().Reset(); timer->m_callback->Execute(); - if (timer->m_kill_me) - { + if (timer->m_kill_me) { m_repeat_timers.erase(m_repeat_timers.begin() + i); delete timer; continue; @@ -159,33 +137,26 @@ void TimerSystem::RunFrame() } } -void TimerSystem::RemoveMapChangeTimers() -{ - for (auto timer : m_once_off_timers) - { - if (timer->m_flags & TIMER_FLAG_NO_MAPCHANGE) - { +void TimerSystem::RemoveMapChangeTimers() { + for (auto timer : m_once_off_timers) { + if (timer->m_flags & TIMER_FLAG_NO_MAPCHANGE) { KillTimer(timer); } } - for (auto timer : m_repeat_timers) - { - if (timer->m_flags & TIMER_FLAG_NO_MAPCHANGE) - { + for (auto timer : m_repeat_timers) { + if (timer->m_flags & TIMER_FLAG_NO_MAPCHANGE) { KillTimer(timer); } } } -timers::Timer *TimerSystem::CreateTimer(float interval, CallbackT callback, int flags) -{ +timers::Timer *TimerSystem::CreateTimer(float interval, CallbackT callback, int flags) { float exec_time = timers::universal_time + interval; auto timer = new timers::Timer(interval, exec_time, callback, flags); - if (flags & TIMER_FLAG_REPEAT) - { + if (flags & TIMER_FLAG_REPEAT) { m_repeat_timers.push_back(timer); return timer; } @@ -194,29 +165,24 @@ timers::Timer *TimerSystem::CreateTimer(float interval, CallbackT callback, int return timer; } -void TimerSystem::KillTimer(timers::Timer *timer) -{ - if (!timer) - return; +void TimerSystem::KillTimer(timers::Timer *timer) { + if (!timer) return; if (std::find(m_repeat_timers.begin(), m_repeat_timers.end(), timer) == m_repeat_timers.end() && - std::find(m_once_off_timers.begin(), m_once_off_timers.end(), timer) == m_once_off_timers.end()) - { + std::find(m_once_off_timers.begin(), m_once_off_timers.end(), timer) == + m_once_off_timers.end()) { return; } - if (timer->m_kill_me) - return; + if (timer->m_kill_me) return; // If were executing, make sure it doesn't run again next time. - if (timer->m_in_exec) - { + if (timer->m_in_exec) { timer->m_kill_me = true; return; } - if (timer->m_flags & TIMER_FLAG_REPEAT) - { + if (timer->m_flags & TIMER_FLAG_REPEAT) { auto it = std::remove_if(m_repeat_timers.begin(), m_repeat_timers.end(), [timer](timers::Timer *i) { return timer == i; }); @@ -224,9 +190,7 @@ void TimerSystem::KillTimer(timers::Timer *timer) if ((success = it != m_repeat_timers.end())) m_repeat_timers.erase(it, m_repeat_timers.end()); delete timer; - } - else - { + } else { auto it = std::remove_if(m_once_off_timers.begin(), m_once_off_timers.end(), [timer](timers::Timer *i) { return timer == i; }); @@ -237,8 +201,5 @@ void TimerSystem::KillTimer(timers::Timer *timer) } } -double TimerSystem::GetTickedTime() -{ - return timers::universal_time; -} -} // namespace counterstrikesharp +double TimerSystem::GetTickedTime() { return timers::universal_time; } +} // namespace counterstrikesharp diff --git a/src/core/timer_system.h b/src/core/timer_system.h index 6019854ca..1a42a459e 100644 --- a/src/core/timer_system.h +++ b/src/core/timer_system.h @@ -36,21 +36,18 @@ #include "core/global_listener.h" #include "scripting/script_engine.h" -namespace counterstrikesharp -{ +namespace counterstrikesharp { class TimerSystem; class ScriptCallback; -namespace timers -{ +namespace timers { #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(); @@ -62,13 +59,12 @@ class Timer 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 OnLevelEnd() override; @@ -80,7 +76,7 @@ class TimerSystem : public GlobalClass void KillTimer(timers::Timer *timer); double GetTickedTime(); - private: +private: bool m_has_map_ticked = false; bool m_has_map_simulated = false; float m_last_ticked_time = 0.0f; @@ -89,4 +85,4 @@ class TimerSystem : public GlobalClass 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 d26e0108b..4d5ccf044 100644 --- a/src/core/utils.h +++ b/src/core/utils.h @@ -5,17 +5,13 @@ #include "core/globals.h" -namespace counterstrikesharp -{ -namespace utils -{ +namespace counterstrikesharp { +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()); @@ -24,14 +20,8 @@ inline std::string GameDirectory() return gameDirectory; } -inline std::string PluginDirectory() -{ - return GameDirectory() + "/addons/counterstrikesharp"; -} +inline std::string PluginDirectory() { return GameDirectory() + "/addons/counterstrikesharp"; } -inline std::string ConfigDirectory() -{ - return PluginDirectory() + "/config"; -} -} // namespace utils -} // namespace counterstrikesharp +inline std::string ConfigDirectory() { return PluginDirectory() + "/config"; } +} // namespace utils +} // namespace counterstrikesharp diff --git a/src/mm_plugin.cpp b/src/mm_plugin.cpp index 593ffd604..f0df763d5 100644 --- a/src/mm_plugin.cpp +++ b/src/mm_plugin.cpp @@ -29,24 +29,24 @@ counterstrikesharp::GlobalClass *counterstrikesharp::GlobalClass::head = nullptr; -extern "C" void InvokeNative(counterstrikesharp::fxNativeContext &context) -{ - if (context.nativeIdentifier == 0) - return; +extern "C" void InvokeNative(counterstrikesharp::fxNativeContext &context) { + if (context.nativeIdentifier == 0) return; counterstrikesharp::ScriptEngine::InvokeNative(context); } -class GameSessionConfiguration_t -{ -}; +class GameSessionConfiguration_t {}; -namespace counterstrikesharp -{ +namespace counterstrikesharp { SH_DECL_HOOK3_void(IServerGameDLL, GameFrame, SH_NOATTRIB, 0, bool, bool, bool); -SH_DECL_HOOK3_void(INetworkServerService, StartupServer, SH_NOATTRIB, 0, const GameSessionConfiguration_t &, - ISource2WorldSession *, const char *); +SH_DECL_HOOK3_void(INetworkServerService, + StartupServer, + SH_NOATTRIB, + 0, + const GameSessionConfiguration_t &, + ISource2WorldSession *, + const char *); CounterStrikeSharpMMPlugin gPlugin; @@ -55,14 +55,13 @@ CounterStrikeSharpMMPlugin gPlugin; ConVar sample_cvar("sample_cvar", "42", 0); #endif -CON_COMMAND_F(sample_command, "Sample command", FCVAR_NONE) -{ +CON_COMMAND_F(sample_command, "Sample command", FCVAR_NONE) { globals::callbackManager.PrintCallbackDebug(); } PLUGIN_EXPOSE(CounterStrikeSharpMMPlugin, gPlugin); -bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late) -{ +bool CounterStrikeSharpMMPlugin::Load( + PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late) { PLUGIN_SAVEVARS(); globals::ismm = ismm; @@ -70,14 +69,17 @@ bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI *ismm, char *error, s CSSHARP_CORE_INFO("Initializing"); - GET_V_IFACE_CURRENT(GetEngineFactory, globals::engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER); + GET_V_IFACE_CURRENT(GetEngineFactory, globals::engine, IVEngineServer, + INTERFACEVERSION_VENGINESERVER); GET_V_IFACE_CURRENT(GetEngineFactory, globals::cvars, ICvar, CVAR_INTERFACE_VERSION); - GET_V_IFACE_ANY(GetServerFactory, globals::server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL); + GET_V_IFACE_ANY(GetServerFactory, globals::server, IServerGameDLL, + INTERFACEVERSION_SERVERGAMEDLL); GET_V_IFACE_ANY(GetServerFactory, globals::serverGameClients, IServerGameClients, INTERFACEVERSION_SERVERGAMECLIENTS); GET_V_IFACE_ANY(GetEngineFactory, globals::networkServerService, INetworkServerService, NETWORKSERVERSERVICE_INTERFACE_VERSION); - GET_V_IFACE_ANY(GetEngineFactory, globals::gameEventSystem, IGameEventSystem, GAMEEVENTSYSTEM_INTERFACE_VERSION); + GET_V_IFACE_ANY(GetEngineFactory, globals::gameEventSystem, IGameEventSystem, + GAMEEVENTSYSTEM_INTERFACE_VERSION); globals::Initialize(); @@ -86,13 +88,12 @@ bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI *ismm, char *error, s CALL_GLOBAL_LISTENER(OnAllInitialized()); - SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, globals::server, this, &CounterStrikeSharpMMPlugin::Hook_GameFrame, - true); + SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, globals::server, this, + &CounterStrikeSharpMMPlugin::Hook_GameFrame, true); SH_ADD_HOOK_MEMFUNC(INetworkServerService, StartupServer, globals::networkServerService, this, &CounterStrikeSharpMMPlugin::Hook_StartupServer, true); - if (!globals::dotnetManager.Initialize()) - { + if (!globals::dotnetManager.Initialize()) { CSSHARP_CORE_ERROR("Failed to initialize .NET runtime"); } @@ -105,35 +106,30 @@ bool CounterStrikeSharpMMPlugin::Load(PluginId id, ISmmAPI *ismm, char *error, s return true; } -void CounterStrikeSharpMMPlugin::Hook_StartupServer(const GameSessionConfiguration_t &config, ISource2WorldSession *, - const char *) -{ -} +void CounterStrikeSharpMMPlugin::Hook_StartupServer(const GameSessionConfiguration_t &config, + ISource2WorldSession *, + const char *) {} -bool CounterStrikeSharpMMPlugin::Unload(char *error, size_t maxlen) -{ +bool CounterStrikeSharpMMPlugin::Unload(char *error, size_t maxlen) { SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, globals::server, this, &CounterStrikeSharpMMPlugin::Hook_GameFrame, true); - SH_REMOVE_HOOK_MEMFUNC(INetworkServerService, StartupServer, globals::networkServerService, this, - &CounterStrikeSharpMMPlugin::Hook_StartupServer, true); + SH_REMOVE_HOOK_MEMFUNC(INetworkServerService, StartupServer, globals::networkServerService, + this, &CounterStrikeSharpMMPlugin::Hook_StartupServer, true); return true; } -void CounterStrikeSharpMMPlugin::AllPluginsLoaded() -{ +void CounterStrikeSharpMMPlugin::AllPluginsLoaded() { /* This is where we'd do stuff that relies on the mod or other plugins * being initialized (for example, cvars added and events registered). */ } -void CounterStrikeSharpMMPlugin::AddTaskForNextFrame(std::function &&task) -{ +void CounterStrikeSharpMMPlugin::AddTaskForNextFrame(std::function &&task) { m_nextTasks.push_back(std::forward(task)); } -void CounterStrikeSharpMMPlugin::Hook_GameFrame(bool simulating, bool bFirstTick, bool bLastTick) -{ +void CounterStrikeSharpMMPlugin::Hook_GameFrame(bool simulating, bool bFirstTick, bool bLastTick) { /** * simulating: * *********** @@ -142,14 +138,12 @@ void CounterStrikeSharpMMPlugin::Hook_GameFrame(bool simulating, bool bFirstTick */ globals::timerSystem.OnGameFrame(simulating); - if (m_nextTasks.empty()) - return; + if (m_nextTasks.empty()) return; CSSHARP_CORE_TRACE("Executing queued tasks of size: {0} on tick number {1}", m_nextTasks.size(), globals::getGlobalVars()->tickcount); - for (int i = 0; i < m_nextTasks.size(); i++) - { + for (int i = 0; i < m_nextTasks.size(); i++) { m_nextTasks[i](); } @@ -159,26 +153,25 @@ void CounterStrikeSharpMMPlugin::Hook_GameFrame(bool simulating, bool bFirstTick // Potentially might not work static ScriptCallback *on_map_end_callback; static bool NewLevelStarted = false; -void CounterStrikeSharpMMPlugin::OnLevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, - char const *pLandmarkName, bool loadGame, bool background) -{ +void CounterStrikeSharpMMPlugin::OnLevelInit(char const *pMapName, + char const *pMapEntities, + char const *pOldLevel, + char const *pLandmarkName, + bool loadGame, + bool background) { CSSHARP_CORE_TRACE("name={0},mapname={1}", "LevelInit", pMapName); NewLevelStarted = true; - if (!on_map_end_callback) - { + if (!on_map_end_callback) { on_map_end_callback = globals::callbackManager.CreateCallback("OnMapEnd"); } } -void CounterStrikeSharpMMPlugin::OnLevelShutdown() -{ - if (NewLevelStarted) - { +void CounterStrikeSharpMMPlugin::OnLevelShutdown() { + if (NewLevelStarted) { CALL_GLOBAL_LISTENER(OnLevelEnd()); - if (on_map_end_callback && on_map_end_callback->GetFunctionCount()) - { + if (on_map_end_callback && on_map_end_callback->GetFunctionCount()) { on_map_end_callback->ScriptContext().Reset(); on_map_end_callback->Execute(); } @@ -190,53 +183,27 @@ void CounterStrikeSharpMMPlugin::OnLevelShutdown() } } -bool CounterStrikeSharpMMPlugin::Pause(char *error, size_t maxlen) -{ - return true; -} +bool CounterStrikeSharpMMPlugin::Pause(char *error, size_t maxlen) { return true; } -bool CounterStrikeSharpMMPlugin::Unpause(char *error, size_t maxlen) -{ - return true; -} +bool CounterStrikeSharpMMPlugin::Unpause(char *error, size_t maxlen) { return true; } -const char *CounterStrikeSharpMMPlugin::GetLicense() -{ - return "GNU GPLv3"; -} +const char *CounterStrikeSharpMMPlugin::GetLicense() { return "GNU GPLv3"; } -const char *CounterStrikeSharpMMPlugin::GetVersion() -{ - return "0.1.0"; -} +const char *CounterStrikeSharpMMPlugin::GetVersion() { return "0.1.0"; } -const char *CounterStrikeSharpMMPlugin::GetDate() -{ - return __DATE__; -} +const char *CounterStrikeSharpMMPlugin::GetDate() { return __DATE__; } -const char *CounterStrikeSharpMMPlugin::GetLogTag() -{ - return "CSSHARP"; -} +const char *CounterStrikeSharpMMPlugin::GetLogTag() { return "CSSHARP"; } -const char *CounterStrikeSharpMMPlugin::GetAuthor() -{ - return "Roflmuffin"; -} +const char *CounterStrikeSharpMMPlugin::GetAuthor() { return "Roflmuffin"; } -const char *CounterStrikeSharpMMPlugin::GetDescription() -{ +const char *CounterStrikeSharpMMPlugin::GetDescription() { return "Counter Strike .NET Scripting Runtime"; } -const char *CounterStrikeSharpMMPlugin::GetName() -{ - return "CounterStrikeSharp"; -} +const char *CounterStrikeSharpMMPlugin::GetName() { return "CounterStrikeSharp"; } -const char *CounterStrikeSharpMMPlugin::GetURL() -{ +const char *CounterStrikeSharpMMPlugin::GetURL() { return "https://github.com/roflmuffin/CounterStrikeSharp"; } -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/mm_plugin.h b/src/mm_plugin.h index 1c23817b5..52d5cf389 100644 --- a/src/mm_plugin.h +++ b/src/mm_plugin.h @@ -15,36 +15,40 @@ */ #ifndef _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_ -#define _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_ + #define _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_ -#include -#include -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include + #include + #include -namespace counterstrikesharp -{ -class CounterStrikeSharpMMPlugin : public ISmmPlugin, public IMetamodListener -{ - public: +namespace counterstrikesharp { +class CounterStrikeSharpMMPlugin : public ISmmPlugin, public IMetamodListener { +public: bool Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late) override; bool Unload(char *error, size_t maxlen) override; bool Pause(char *error, size_t maxlen) override; bool Unpause(char *error, size_t maxlen) override; void AllPluginsLoaded() override; - public: // hooks - void OnLevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, - bool loadGame, bool background) override; +public: // hooks + void OnLevelInit(char const *pMapName, + char const *pMapEntities, + char const *pOldLevel, + char const *pLandmarkName, + bool loadGame, + bool background) override; void OnLevelShutdown() override; void Hook_GameFrame(bool simulating, bool bFirstTick, bool bLastTick); - void Hook_StartupServer(const GameSessionConfiguration_t& config, ISource2WorldSession*, const char*); + void Hook_StartupServer(const GameSessionConfiguration_t &config, + ISource2WorldSession *, + const char *); void AddTaskForNextFrame(std::function &&task); - public: +public: const char *GetAuthor() override; const char *GetName() override; const char *GetDescription() override; @@ -54,7 +58,7 @@ class CounterStrikeSharpMMPlugin : public ISmmPlugin, public IMetamodListener const char *GetDate() override; const char *GetLogTag() override; - private: +private: std::vector> m_nextTasks; }; @@ -62,7 +66,7 @@ extern CounterStrikeSharpMMPlugin gPlugin; PLUGIN_GLOBALVARS(); -#endif //_INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_ +#endif //_INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_ #pragma clang diagnostic pop } \ No newline at end of file diff --git a/src/scripting/autonative.h b/src/scripting/autonative.h index be2528a51..a4b921778 100644 --- a/src/scripting/autonative.h +++ b/src/scripting/autonative.h @@ -20,34 +20,29 @@ #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) \ - { \ - auto obj = script_context.GetArgument(0); \ - return getter; \ +#define CREATE_GETTER_FUNCTION(object_name, parameter_type, parameter_name, from_type, getter) \ + 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; \ - } +#define CREATE_STATIC_GETTER_FUNCTION(parameter_name, parameter_type, 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) \ - { \ - auto obj = script_context.GetArgument(0); \ - auto value = script_context.GetArgument(1); \ - setter; \ +#define CREATE_SETTER_FUNCTION(type_name, get_type, name, from_type, setter) \ + 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/callback_manager.cpp b/src/scripting/callback_manager.cpp index 680a51706..fdad6e6d9 100644 --- a/src/scripting/callback_manager.cpp +++ b/src/scripting/callback_manager.cpp @@ -18,61 +18,46 @@ #include "core/log.h" #include -namespace counterstrikesharp -{ +namespace counterstrikesharp { -ScriptCallback::ScriptCallback(const char *name) : m_root_context(fxNativeContext{}) -{ +ScriptCallback::ScriptCallback(const char *name) + : m_root_context(fxNativeContext{}) { m_script_context_raw = ScriptContextRaw(m_root_context); m_name = std::string(name); } -ScriptCallback::~ScriptCallback() -{ - m_functions.clear(); -} +ScriptCallback::~ScriptCallback() { m_functions.clear(); } -void ScriptCallback::AddListener(CallbackT plugin_function) -{ +void ScriptCallback::AddListener(CallbackT plugin_function) { m_functions.push_back(plugin_function); } -bool ScriptCallback::RemoveListener(CallbackT pluginFunction) -{ +bool ScriptCallback::RemoveListener(CallbackT pluginFunction) { bool success; - m_functions.erase(std::remove(m_functions.begin(), m_functions.end(), pluginFunction), m_functions.end()); + m_functions.erase(std::remove(m_functions.begin(), m_functions.end(), pluginFunction), + m_functions.end()); return success; } -void ScriptCallback::Execute(bool resetContext) -{ - for (auto method_to_call : m_functions) - { - if (method_to_call) - { +void ScriptCallback::Execute(bool resetContext) { + for (auto method_to_call : m_functions) { + if (method_to_call) { method_to_call(&ScriptContextStruct()); } } - if (resetContext) - { + if (resetContext) { ResetContext(); } } -void ScriptCallback::ResetContext() -{ - ScriptContext().Reset(); -} +void ScriptCallback::ResetContext() { ScriptContext().Reset(); } -CallbackManager::CallbackManager() -{ -} +CallbackManager::CallbackManager() {} -ScriptCallback *CallbackManager::CreateCallback(const char *name) -{ +ScriptCallback *CallbackManager::CreateCallback(const char *name) { CSSHARP_CORE_TRACE("Creating callback {0}", name); auto *callback = new ScriptCallback(name); m_managed.push_back(callback); @@ -80,13 +65,10 @@ ScriptCallback *CallbackManager::CreateCallback(const char *name) return callback; } -ScriptCallback *CallbackManager::FindCallback(const char *name) -{ - for (auto it = m_managed.begin(); it != m_managed.end(); ++it) - { +ScriptCallback *CallbackManager::FindCallback(const char *name) { + for (auto it = m_managed.begin(); it != m_managed.end(); ++it) { ScriptCallback *marshal = *it; - if (strcmp(marshal->GetName().c_str(), name) == 0) - { + if (strcmp(marshal->GetName().c_str(), name) == 0) { return marshal; } } @@ -94,22 +76,18 @@ ScriptCallback *CallbackManager::FindCallback(const char *name) return nullptr; } -void CallbackManager::ReleaseCallback(ScriptCallback *callback) -{ +void CallbackManager::ReleaseCallback(ScriptCallback *callback) { bool success; - auto it = - std::remove_if(m_managed.begin(), m_managed.end(), [callback](ScriptCallback *i) { return callback == i; }); + auto it = std::remove_if(m_managed.begin(), m_managed.end(), + [callback](ScriptCallback *i) { return callback == i; }); - if ((success = it != m_managed.end())) - m_managed.erase(it, m_managed.end()); + if ((success = it != m_managed.end())) m_managed.erase(it, m_managed.end()); delete callback; } -bool CallbackManager::TryAddFunction(const char *name, CallbackT pCallable) -{ +bool CallbackManager::TryAddFunction(const char *name, CallbackT pCallable) { auto *fwd = FindCallback(name); - if (fwd) - { + if (fwd) { fwd->AddListener(pCallable); return true; } @@ -117,11 +95,9 @@ bool CallbackManager::TryAddFunction(const char *name, CallbackT pCallable) return false; } -bool CallbackManager::TryRemoveFunction(const char *name, CallbackT pCallable) -{ +bool CallbackManager::TryRemoveFunction(const char *name, CallbackT pCallable) { auto *fwd = FindCallback(name); - if (fwd) - { + if (fwd) { bool success = fwd->RemoveListener(pCallable); return success; } @@ -129,12 +105,10 @@ bool CallbackManager::TryRemoveFunction(const char *name, CallbackT pCallable) return false; } -void CallbackManager::PrintCallbackDebug() -{ +void CallbackManager::PrintCallbackDebug() { CSSHARP_CORE_INFO("----CALLBACKS----"); - for (auto it : m_managed) - { + for (auto it : m_managed) { CSSHARP_CORE_INFO("{0} ({0})\n", it->GetName().c_str(), 1); } } -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/scripting/callback_manager.h b/src/scripting/callback_manager.h index 3eca983fd..3a1714cfa 100644 --- a/src/scripting/callback_manager.h +++ b/src/scripting/callback_manager.h @@ -22,48 +22,33 @@ #include "core/globals.h" #include "scripting/script_engine.h" -namespace counterstrikesharp -{ +namespace counterstrikesharp { -class ScriptCallback -{ - public: +class ScriptCallback { +public: ScriptCallback(const char *name); ~ScriptCallback(); void AddListener(CallbackT plugin_function); bool RemoveListener(CallbackT plugin_function); - std::string GetName() - { - return m_name; - } - unsigned int GetFunctionCount() - { - return m_functions.size(); - } + std::string GetName() { return m_name; } + unsigned int GetFunctionCount() { return m_functions.size(); } void Execute(bool resetContext = true); void ResetContext(); - ScriptContextRaw &ScriptContext() - { - return m_script_context_raw; - } - fxNativeContext &ScriptContextStruct() - { - return m_root_context; - } + ScriptContextRaw &ScriptContext() { return m_script_context_raw; } + fxNativeContext &ScriptContextStruct() { return m_root_context; } - private: +private: std::vector m_functions; std::string m_name; ScriptContextRaw m_script_context_raw; fxNativeContext m_root_context; }; -class CallbackManager : public GlobalClass -{ - public: +class CallbackManager : public GlobalClass { +public: CallbackManager(); - public: +public: ScriptCallback *CreateCallback(const char *name); ScriptCallback *FindCallback(const char *name); void ReleaseCallback(ScriptCallback *callback); @@ -71,8 +56,8 @@ class CallbackManager : public GlobalClass bool TryRemoveFunction(const char *name, CallbackT pCallable); void PrintCallbackDebug(); - private: +private: std::vector m_managed; }; -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/scripting/dotnet_host.cpp b/src/scripting/dotnet_host.cpp index d10652d88..4cdeb35a1 100644 --- a/src/scripting/dotnet_host.cpp +++ b/src/scripting/dotnet_host.cpp @@ -7,15 +7,15 @@ #include #ifdef WIN32 -#include -#include + #include + #include -#define STR(s) L##s -#define CH(c) L##c -#define DIR_SEPARATOR L'\\' + #define STR(s) L##s + #define CH(c) L##c + #define DIR_SEPARATOR L'\\' #else -#include + #include #endif #include @@ -26,8 +26,7 @@ std::wstring_convert> converter; -namespace -{ +namespace { hostfxr_initialize_for_runtime_config_fn init_fptr; hostfxr_get_runtime_delegate_fn get_delegate_fptr; hostfxr_close_fn close_fptr; @@ -35,37 +34,32 @@ hostfxr_handle cxt; bool load_hostfxr(); load_assembly_and_get_function_pointer_fn get_dotnet_load_assembly(const char_t *assembly); -} // namespace +} // namespace -namespace -{ +namespace { // Forward declarations void *load_library(const char_t *); void *get_export(void *, const char *); #ifdef _WINDOWS -void *load_library(const char_t *path) -{ +void *load_library(const char_t *path) { HMODULE h = ::LoadLibraryW(path); assert(h != nullptr); return (void *)h; } -void *get_export(void *h, const char *name) -{ +void *get_export(void *h, const char *name) { void *f = ::GetProcAddress((HMODULE)h, name); assert(f != nullptr); return f; } #else -void *load_library(const char_t *path) -{ +void *load_library(const char_t *path) { void *h = dlopen(path, RTLD_LAZY | RTLD_LOCAL); assert(h != nullptr); return h; } -void *get_export(void *h, const char *name) -{ +void *get_export(void *h, const char *name) { void *f = dlsym(h, name); assert(f != nullptr); return f; @@ -74,8 +68,7 @@ void *get_export(void *h, const char *name) // // Using the nethost library, discover the location of hostfxr and get exports -bool load_hostfxr() -{ +bool load_hostfxr() { std::string baseDir = counterstrikesharp::utils::PluginDirectory(); std::string buffer = std::string(baseDir + "/dotnet/host/fxr/7.0.11/libhostfxr.so"); @@ -84,8 +77,10 @@ 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"); - get_delegate_fptr = (hostfxr_get_runtime_delegate_fn)get_export(lib, "hostfxr_get_runtime_delegate"); + init_fptr = (hostfxr_initialize_for_runtime_config_fn)get_export( + lib, "hostfxr_initialize_for_runtime_config"); + get_delegate_fptr = + (hostfxr_get_runtime_delegate_fn)get_export(lib, "hostfxr_get_runtime_delegate"); close_fptr = (hostfxr_close_fn)get_export(lib, "hostfxr_close"); return (init_fptr && get_delegate_fptr && close_fptr); @@ -94,20 +89,19 @@ bool load_hostfxr() // // Load and initialize .NET Core and get desired function pointer for scenario -load_assembly_and_get_function_pointer_fn get_dotnet_load_assembly(const char_t *config_path) -{ +load_assembly_and_get_function_pointer_fn get_dotnet_load_assembly(const char_t *config_path) { // 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) { std::cerr << "Init failed: " << std::hex << std::showbase << rc << std::endl; 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); + 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) std::cerr << "Get delegate failed: " << std::hex << std::showbase << rc << std::endl; @@ -115,48 +109,45 @@ load_assembly_and_get_function_pointer_fn get_dotnet_load_assembly(const char_t return (load_assembly_and_get_function_pointer_fn)load_assembly_and_get_function_pointer; } -} // namespace +} // namespace -CDotNetManager::CDotNetManager() -{ -} +CDotNetManager::CDotNetManager() {} -CDotNetManager::~CDotNetManager() -{ -} +CDotNetManager::~CDotNetManager() {} -bool CDotNetManager::Initialize() -{ +bool CDotNetManager::Initialize() { std::string baseDir = counterstrikesharp::utils::PluginDirectory(); - if (!load_hostfxr()) - { + if (!load_hostfxr()) { CSSHARP_CORE_ERROR("Failed to initialize .NET"); return false; } CSSHARP_CORE_INFO(".NET Runtime Initialised."); - std::string wideStr = std::string((baseDir + "/api/CounterStrikeSharp.API.runtimeconfig.json").c_str()); + std::string wideStr = + std::string((baseDir + "/api/CounterStrikeSharp.API.runtimeconfig.json").c_str()); load_assembly_and_get_function_pointer_fn load_assembly_and_get_function_pointer = nullptr; load_assembly_and_get_function_pointer = get_dotnet_load_assembly(wideStr.c_str()); - assert(load_assembly_and_get_function_pointer != nullptr && "Failure: get_dotnet_load_assembly()"); + assert(load_assembly_and_get_function_pointer != nullptr && + "Failure: get_dotnet_load_assembly()"); - const std::string dotnetlib_path = std::string((baseDir + "/api/CounterStrikeSharp.API.dll").c_str()); + const std::string dotnetlib_path = + std::string((baseDir + "/api/CounterStrikeSharp.API.dll").c_str()); const char_t *dotnet_type = "CounterStrikeSharp.API.Core.Helpers, CounterStrikeSharp.API"; // Namespace, assembly name - typedef int(CORECLR_DELEGATE_CALLTYPE * custom_entry_point_fn)(); custom_entry_point_fn entry_point = nullptr; - int rc = load_assembly_and_get_function_pointer(dotnetlib_path.c_str(), dotnet_type, "LoadAllPlugins", - UNMANAGEDCALLERSONLY_METHOD, nullptr, (void **)&entry_point); - assert(rc == 0 && entry_point != nullptr && "Failure: load_assembly_and_get_function_pointer()"); + int rc = load_assembly_and_get_function_pointer(dotnetlib_path.c_str(), dotnet_type, + "LoadAllPlugins", UNMANAGEDCALLERSONLY_METHOD, + nullptr, (void **)&entry_point); + assert(rc == 0 && entry_point != nullptr && + "Failure: load_assembly_and_get_function_pointer()"); const bool success = entry_point(); - if (!success) - { + if (!success) { CSSHARP_CORE_ERROR("Failed to initialize .NET"); return false; } @@ -165,16 +156,10 @@ bool CDotNetManager::Initialize() return true; } -void CDotNetManager::UnloadPlugin(PluginContext *context) -{ -} +void CDotNetManager::UnloadPlugin(PluginContext *context) {} -void CDotNetManager::Shutdown() -{ +void CDotNetManager::Shutdown() { // CoreCLR does not currently supporting unloading... :( } -PluginContext *CDotNetManager::FindContext(std::string path) -{ - return nullptr; -} +PluginContext *CDotNetManager::FindContext(std::string path) { return nullptr; } diff --git a/src/scripting/dotnet_host.h b/src/scripting/dotnet_host.h index 4473e049d..768b143b8 100644 --- a/src/scripting/dotnet_host.h +++ b/src/scripting/dotnet_host.h @@ -5,24 +5,21 @@ #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(); @@ -31,6 +28,6 @@ class CDotNetManager void Shutdown(); 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 189f10376..076123558 100644 --- a/src/scripting/natives/natives_callbacks.cpp +++ b/src/scripting/natives/natives_callbacks.cpp @@ -18,19 +18,16 @@ #include "scripting/autonative.h" #include "scripting/script_engine.h" -namespace counterstrikesharp -{ +namespace counterstrikesharp { -static bool AddListener(ScriptContext &script_context) -{ +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) -{ +static bool RemoveListener(ScriptContext &script_context) { auto name = script_context.GetArgument(0); auto callback = script_context.GetArgument(1); @@ -41,4 +38,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_engine.cpp b/src/scripting/natives/natives_engine.cpp index 31081d5a0..72b4f8fd3 100644 --- a/src/scripting/natives/natives_engine.cpp +++ b/src/scripting/natives/natives_engine.cpp @@ -32,55 +32,38 @@ #include "core/log.h" // clang-format on -namespace counterstrikesharp -{ +namespace counterstrikesharp { -const char *GetMapName(ScriptContext &script_context) -{ - if (globals::getGlobalVars() == nullptr) - return nullptr; +const char *GetMapName(ScriptContext &script_context) { + if (globals::getGlobalVars() == nullptr) return nullptr; return globals::getGlobalVars()->mapname.ToCStr(); } -const char *GetGameDirectory(ScriptContext &script_context) -{ +const char *GetGameDirectory(ScriptContext &script_context) { return strdup(Plat_GetGameDirectory()); } -bool IsMapValid(ScriptContext &script_context) -{ +bool IsMapValid(ScriptContext &script_context) { auto mapname = script_context.GetArgument(0); return globals::engine->IsMapValid(mapname) != 0; } -float GetTickInterval(ScriptContext &script_context) -{ +float GetTickInterval(ScriptContext &script_context) { return globals::getGlobalVars()->interval_per_tick; } -float GetCurrentTime(ScriptContext &script_context) -{ - return globals::getGlobalVars()->curtime; -} +float GetCurrentTime(ScriptContext &script_context) { return globals::getGlobalVars()->curtime; } -int GetTickCount(ScriptContext &script_context) -{ - return globals::getGlobalVars()->tickcount; -} +int GetTickCount(ScriptContext &script_context) { return globals::getGlobalVars()->tickcount; } -float GetGameFrameTime(ScriptContext &script_context) -{ +float GetGameFrameTime(ScriptContext &script_context) { return globals::getGlobalVars()->frametime; } -double GetEngineTime(ScriptContext &script_context) -{ - return Plat_FloatTime(); -} +double GetEngineTime(ScriptContext &script_context) { return Plat_FloatTime(); } -void ServerCommand(ScriptContext &script_context) -{ +void ServerCommand(ScriptContext &script_context) { auto command = script_context.GetArgument(0); auto clean_command = std::string(command); @@ -88,28 +71,24 @@ void ServerCommand(ScriptContext &script_context) globals::engine->ServerCommand(clean_command.c_str()); } -void PrecacheModel(ScriptContext &script_context) -{ +void PrecacheModel(ScriptContext &script_context) { auto name = script_context.GetArgument(0); globals::engine->PrecacheGeneric(name); } -bool PrecacheSound(ScriptContext &script_context) -{ +bool PrecacheSound(ScriptContext &script_context) { auto [name, preload] = script_context.GetArguments(); return globals::engineSound->PrecacheSound(name, preload); } -bool IsSoundPrecached(ScriptContext &script_context) -{ +bool IsSoundPrecached(ScriptContext &script_context) { auto name = script_context.GetArgument(0); return globals::engineSound->IsSoundPrecached(name); } -float GetSoundDuration(ScriptContext &script_context) -{ +float GetSoundDuration(ScriptContext &script_context) { auto name = script_context.GetArgument(0); return globals::engineSound->GetSoundDuration(name); @@ -136,21 +115,17 @@ float GetSoundDuration(ScriptContext &script_context) // attenuation, 0, flags, pitch, origin, direction); // } -Ray_t *CreateRay1(ScriptContext &script_context) -{ +Ray_t *CreateRay1(ScriptContext &script_context) { auto ray_type = script_context.GetArgument(0); auto vec1 = script_context.GetArgument(1); auto vec2 = script_context.GetArgument(2); Ray_t *pRay = new Ray_t; - if (ray_type == RayType_EndPoint) - { + if (ray_type == RayType_EndPoint) { pRay->Init(*vec1, *vec2); return pRay; - } - else if (ray_type == RayType_Infinite) - { + } else if (ray_type == RayType_Infinite) { QAngle angles; Vector endVec; angles.Init(vec2->x, vec2->y, vec2->z); @@ -166,8 +141,7 @@ Ray_t *CreateRay1(ScriptContext &script_context) return nullptr; } -Ray_t *CreateRay2(ScriptContext &script_context) -{ +Ray_t *CreateRay2(ScriptContext &script_context) { auto vec1 = script_context.GetArgument(0); auto vec2 = script_context.GetArgument(1); auto vec3 = script_context.GetArgument(2); @@ -178,8 +152,7 @@ Ray_t *CreateRay2(ScriptContext &script_context) return pRay; } -void TraceRay(ScriptContext &script_context) -{ +void TraceRay(ScriptContext &script_context) { auto ray = script_context.GetArgument(0); auto pTrace = script_context.GetArgument(1); auto trace_filter = script_context.GetArgument(2); @@ -188,57 +161,44 @@ void TraceRay(ScriptContext &script_context) globals::engineTrace->TraceRay(*ray, flags, trace_filter, pTrace); } -CSimpleTraceFilter *NewSimpleTraceFilter(ScriptContext &script_context) -{ +CSimpleTraceFilter *NewSimpleTraceFilter(ScriptContext &script_context) { auto index_to_ignore = script_context.GetArgument(0); return new CSimpleTraceFilter(index_to_ignore); } -TraceFilterProxy *NewTraceFilterProxy(ScriptContext &script_context) -{ +TraceFilterProxy *NewTraceFilterProxy(ScriptContext &script_context) { return new TraceFilterProxy(); } -void TraceFilterProxySetTraceTypeCallback(ScriptContext &script_context) -{ +void TraceFilterProxySetTraceTypeCallback(ScriptContext &script_context) { auto trace_filter = script_context.GetArgument(0); auto callback = script_context.GetArgument(1); trace_filter->SetGetTraceTypeCallback(callback); } -void TraceFilterProxySetShouldHitEntityCallback(ScriptContext &script_context) -{ +void TraceFilterProxySetShouldHitEntityCallback(ScriptContext &script_context) { auto [trace_filter, callback] = script_context.GetArguments(); trace_filter->SetShouldHitEntityCallback(callback); } -CGameTrace *NewTraceResult(ScriptContext &script_context) -{ - return new CGameTrace(); -} +CGameTrace *NewTraceResult(ScriptContext &script_context) { return new CGameTrace(); } -double GetTickedTime(ScriptContext &script_context) -{ - return globals::timerSystem.GetTickedTime(); -} +double GetTickedTime(ScriptContext &script_context) { return globals::timerSystem.GetTickedTime(); } -void QueueTaskForNextFrame(ScriptContext &script_context) -{ +void QueueTaskForNextFrame(ScriptContext &script_context) { auto func = script_context.GetArgument(0); typedef void(voidfunc)(void); globals::mmPlugin->AddTaskForNextFrame([func]() { reinterpret_cast(func)(); }); } -byte *ConvertToByteArray(const char *str, size_t *outLength) -{ - size_t len = strlen(str) / 4; // Every byte is represented as \xHH +byte *ConvertToByteArray(const char *str, size_t *outLength) { + size_t len = strlen(str) / 4; // Every byte is represented as \xHH byte *result = (byte *)malloc(len); - for (size_t i = 0, j = 0; i < len; ++i, j += 4) - { + for (size_t i = 0, j = 0; i < len; ++i, j += 4) { sscanf(str + j, "\\x%2hhx", &result[i]); } @@ -246,8 +206,7 @@ byte *ConvertToByteArray(const char *str, size_t *outLength) return result; } -void *FindSignature(ScriptContext &scriptContext) -{ +void *FindSignature(ScriptContext &scriptContext) { auto moduleName = scriptContext.GetArgument(0); auto bytesStr = scriptContext.GetArgument(1); @@ -255,8 +214,7 @@ void *FindSignature(ScriptContext &scriptContext) auto sigBytes = ConvertToByteArray(bytesStr, &iSigLength); auto module = dlopen(moduleName, RTLD_NOW); - if (module == nullptr) - { + if (module == nullptr) { scriptContext.ThrowNativeError("Could not find module"); return nullptr; } @@ -264,64 +222,49 @@ void *FindSignature(ScriptContext &scriptContext) void *moduleBase; size_t moduleSize; - if (GetModuleInformation(module, &moduleBase, &moduleSize) != 0) + if (GetModuleInformation(module, &moduleBase, &moduleSize) != 0) { scriptContext.ThrowNativeError("Failed to get module info"); + return nullptr; + } unsigned char *pMemory; void *returnAddr = nullptr; - CSSHARP_CORE_INFO("Module name {}, module base: {}, bytes {}, sigbytes {:X}, sigLength: {}, modulesize: {}", - moduleName, moduleBase, bytesStr, sigBytes[0], iSigLength, moduleSize); - pMemory = (byte *)moduleBase; - for (size_t i = 0; i < moduleSize; i++) - { + for (size_t i = 0; i < moduleSize; i++) { size_t matches = 0; - while (*(pMemory + i + matches) == sigBytes[matches] || sigBytes[matches] == '\x2A') - { + while (*(pMemory + i + matches) == sigBytes[matches] || sigBytes[matches] == '\x2A') { matches++; - if (matches == iSigLength) - { + if (matches == iSigLength) { returnAddr = (void *)(pMemory + i); } } } - CSSHARP_CORE_TRACE("Return Addr {}", returnAddr); - - if (returnAddr == nullptr) - { + if (returnAddr == nullptr) { scriptContext.ThrowNativeError("Could not find signature"); + return nullptr; } - scriptContext.SetResult(returnAddr); + return returnAddr; } -enum InterfaceType -{ - Engine, - Server -}; +enum InterfaceType { Engine, Server }; -void *GetValveInterface(ScriptContext &scriptContext) -{ +void *GetValveInterface(ScriptContext &scriptContext) { auto [interfaceType, interfaceName] = scriptContext.GetArguments(); CreateInterfaceFn factoryFn; - if (interfaceType == Server) - { + if (interfaceType == Server) { factoryFn = globals::ismm->GetServerFactory(); - } - else if (interfaceType == Engine) - { + } else if (interfaceType == Engine) { factoryFn = globals::ismm->GetEngineFactory(); } auto foundInterface = globals::ismm->VInterfaceMatch(factoryFn, interfaceName); - if (foundInterface == nullptr) - { + if (foundInterface == nullptr) { scriptContext.ThrowNativeError("Could not find interface"); } @@ -366,4 +309,4 @@ REGISTER_NATIVES(engine, { ScriptEngine::RegisterNativeHandler("GET_VALVE_INTERFACE", GetValveInterface); ScriptEngine::RegisterNativeHandler("FIND_SIGNATURE", FindSignature); }) -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/scripting/natives/natives_events.cpp b/src/scripting/natives/natives_events.cpp index ae419f380..2784ec439 100644 --- a/src/scripting/natives/natives_events.cpp +++ b/src/scripting/natives/natives_events.cpp @@ -18,11 +18,9 @@ #include "core/managers/event_manager.h" #include "scripting/autonative.h" -namespace counterstrikesharp -{ +namespace counterstrikesharp { -static void HookEvent(ScriptContext &script_context) -{ +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); @@ -30,8 +28,7 @@ static void HookEvent(ScriptContext &script_context) globals::eventManager.HookEvent(name, callback, post); } -static void UnhookEvent(ScriptContext &script_context) -{ +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); @@ -39,20 +36,17 @@ static void UnhookEvent(ScriptContext &script_context) globals::eventManager.UnhookEvent(name, callback, post); } -static IGameEvent *CreateEvent(ScriptContext &script_context) -{ +static IGameEvent *CreateEvent(ScriptContext &script_context) { auto name = script_context.GetArgument(0); bool force = script_context.GetArgument(1); return globals::gameEventManager->CreateEvent(name, force); } -static void FireEvent(ScriptContext &script_context) -{ +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"); } @@ -78,12 +72,10 @@ static void FireEvent(ScriptContext &script_context) // game_client->FireGameEvent(game_event); // } -static const char *GetEventName(ScriptContext &script_context) -{ +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; } @@ -91,13 +83,11 @@ static const char *GetEventName(ScriptContext &script_context) return game_event->GetName(); } -static bool GetEventBool(ScriptContext &script_context) -{ +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; } @@ -105,13 +95,11 @@ static bool GetEventBool(ScriptContext &script_context) return game_event->GetBool(key_name); } -static int GetEventInt(ScriptContext &script_context) -{ +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; } @@ -119,13 +107,11 @@ static int GetEventInt(ScriptContext &script_context) return game_event->GetInt(key_name); } -static float GetEventFloat(ScriptContext &script_context) -{ +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; } @@ -133,13 +119,11 @@ static float GetEventFloat(ScriptContext &script_context) return game_event->GetFloat(key_name); } -static const char *GetEventString(ScriptContext &script_context) -{ +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; } @@ -147,56 +131,47 @@ static const char *GetEventString(ScriptContext &script_context) return game_event->GetString(key_name); } -static void SetEventBool(ScriptContext &script_context) -{ +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) -{ +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) -{ +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) -{ +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 int LoadEventsFromFile(ScriptContext &script_context) -{ +static int LoadEventsFromFile(ScriptContext &script_context) { auto [path, searchAll] = script_context.GetArguments(); return globals::gameEventManager->LoadEventsFromFile(path, searchAll); @@ -223,4 +198,4 @@ REGISTER_NATIVES(events, { ScriptEngine::RegisterNativeHandler("LOAD_EVENTS_FROM_FILE", LoadEventsFromFile); }) -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/scripting/natives/natives_timers.cpp b/src/scripting/natives/natives_timers.cpp index f4c78af44..eaf7bc33e 100644 --- a/src/scripting/natives/natives_timers.cpp +++ b/src/scripting/natives/natives_timers.cpp @@ -19,11 +19,9 @@ #include "core/timer_system.h" -namespace counterstrikesharp -{ +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); @@ -31,8 +29,7 @@ timers::Timer *CreateTimer(ScriptContext &script_context) return globals::timerSystem.CreateTimer(interval, callback, flags); } -void KillTimer(ScriptContext &script_context) -{ +void KillTimer(ScriptContext &script_context) { auto timer = script_context.GetArgument(0); globals::timerSystem.KillTimer(timer); } @@ -41,4 +38,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_vector.cpp b/src/scripting/natives/natives_vector.cpp index 841fa8a81..9dcb26032 100644 --- a/src/scripting/natives/natives_vector.cpp +++ b/src/scripting/natives/natives_vector.cpp @@ -19,8 +19,7 @@ #include "scripting/autonative.h" #include "scripting/script_engine.h" -namespace counterstrikesharp -{ +namespace counterstrikesharp { CREATE_GETTER_FUNCTION(Vector, float, Length, Vector *, obj->Length()); CREATE_GETTER_FUNCTION(Vector, float, Length2D, Vector *, obj->Length2D()); @@ -38,36 +37,27 @@ CREATE_SETTER_FUNCTION(Vector, float, Z, Vector *, obj->z = value); std::vector managed_vectors; -Vector *VectorNew(ScriptContext &script_context) -{ +Vector *VectorNew(ScriptContext &script_context) { auto vec = new Vector(); managed_vectors.push_back(vec); return vec; } -QAngle *AngleNew(ScriptContext &script_context) -{ - return new QAngle(); -} +QAngle *AngleNew(ScriptContext &script_context) { return new QAngle(); } -void NativeVectorAngles(ScriptContext &script_context) -{ +void NativeVectorAngles(ScriptContext &script_context) { auto vec = script_context.GetArgument(0); auto pseudoUpVector = script_context.GetArgument(1); auto outAngle = script_context.GetArgument(2); - if (!pseudoUpVector) - { + if (!pseudoUpVector) { VectorAngles(*vec, *outAngle); - } - else - { + } else { VectorAngles(*vec, *pseudoUpVector, *outAngle); } } -void NativeAngleVectors(ScriptContext &script_context) -{ +void NativeAngleVectors(ScriptContext &script_context) { auto vec = script_context.GetArgument(0); auto fwd = script_context.GetArgument(1); auto right = script_context.GetArgument(2); @@ -96,4 +86,4 @@ REGISTER_NATIVES(vector, { ScriptEngine::RegisterNativeHandler("VECTOR_LENGTH_2D_SQR", VectorGetLength2DSqr); ScriptEngine::RegisterNativeHandler("VECTOR_IS_ZERO", VectorGetLengthSqr); }) -} // namespace counterstrikesharp \ No newline at end of file +} // namespace counterstrikesharp \ No newline at end of file diff --git a/src/scripting/script_engine.cpp b/src/scripting/script_engine.cpp index 3d97e12c1..56647d678 100644 --- a/src/scripting/script_engine.cpp +++ b/src/scripting/script_engine.cpp @@ -33,13 +33,11 @@ static std::unordered_map g_registeredHandlers; -namespace counterstrikesharp -{ +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); @@ -56,10 +54,8 @@ void ScriptContext::ThrowNativeError(const char *msg, ...) *this->m_has_error = 1; } -void ScriptContext::Reset() -{ - if (*m_has_error) - { +void ScriptContext::Reset() { + if (*m_has_error) { errors.pop(); } @@ -67,43 +63,36 @@ 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; @@ -112,31 +101,27 @@ 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) -{ - if (context.nativeIdentifier == 0) - return; +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 a2a90f27f..c412c6aa6 100644 --- a/src/scripting/script_engine.h +++ b/src/scripting/script_engine.h @@ -31,23 +31,19 @@ #include #include -namespace counterstrikesharp -{ +namespace counterstrikesharp { -inline uint32_t hash_string(const char *string) -{ +inline uint32_t hash_string(const char *string) { unsigned long result = 5381; - for (int i = 0; i < strlen(string); i++) - { + for (int i = 0; i < strlen(string); i++) { result = ((result << 5) + result) ^ string[i]; } return result; } -struct fxNativeContext -{ +struct fxNativeContext { int numArguments; int numResults; int hasError; @@ -59,16 +55,11 @@ struct 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: +protected: void *m_argumentBuffer; int m_numArguments; @@ -79,85 +70,74 @@ class ScriptContext fxNativeContext *m_native_context; - public: +public: inline ScriptContext() = default; - public: +public: void ThrowNativeError(const char *msg, ...); - bool HasError() - { - return *m_has_error == 1; - } + 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 + template struct gen_seq<0, Is...> : index {}; - template - inline const std::tuple GetArguments() - { + 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) - { + template + inline const T &GetArgument(int index) { auto functionData = (uint64_t *)m_argumentBuffer; return *reinterpret_cast(&functionData[index]); } - template inline void SetArgument(int index, const T &value) - { + 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) - { + if (sizeof(T) < ArgumentSize) { *reinterpret_cast(&functionData[index]) = 0; } *reinterpret_cast(&functionData[index]) = value; } - template inline const T &CheckArgument(int 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."); } return argument; } - inline int GetArgumentCount() - { - return m_numArguments; - } + inline int GetArgumentCount() { return m_numArguments; } - template inline void Push(const T &value) - { + 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) - { + if (sizeof(T) < ArgumentSize) { *reinterpret_cast(&functionData[m_numArguments]) = 0; } @@ -166,19 +146,17 @@ class ScriptContext m_native_context->numArguments++; } - inline void PushString(const char *value) - { + inline void PushString(const char *value) { auto functionData = (uint64_t *)m_argumentBuffer; *reinterpret_cast(&functionData[m_numArguments]) = value; } - template inline void SetResult(const T &value) - { + template + inline void SetResult(const T &value) { auto functionData = (uint64_t *)m_result; - if (sizeof(T) < ArgumentSize) - { + if (sizeof(T) < ArgumentSize) { *reinterpret_cast(&functionData[0]) = 0; } @@ -188,29 +166,21 @@ class ScriptContext m_numArguments = 0; } - template inline T GetResult() - { + template + inline T GetResult() { auto functionData = (uint64_t *)m_result; return *reinterpret_cast(functionData); } - inline void *GetArgumentBuffer() - { - return m_argumentBuffer; - } + inline void *GetArgumentBuffer() { return m_argumentBuffer; } - inline int GetNumArguments() - { - return m_native_context->numArguments; - } + 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; @@ -221,8 +191,7 @@ class ScriptContextRaw : public ScriptContext m_result = &context.result; } - inline ScriptContextRaw() - { + inline ScriptContextRaw() { m_numResults = 0; m_numArguments = 0; } @@ -230,11 +199,11 @@ class ScriptContextRaw : public ScriptContext 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); @@ -242,13 +211,11 @@ class ScriptEngine static void RegisterNativeHandlerInt(uint64_t nativeIdentifier, TNativeHandler function); - template static void RegisterNativeHandler(const char *nativeName, TypedTNativeHandler function) - { - + 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); } }; @@ -256,14 +223,13 @@ class ScriptEngine 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); - private: +private: static ScriptContextRaw m_context; }; -} // namespace counterstrikesharp +} // namespace counterstrikesharp diff --git a/src/utils/virtual.h b/src/utils/virtual.h index 3ec2125a4..62d8c2b7e 100644 --- a/src/utils/virtual.h +++ b/src/utils/virtual.h @@ -1,63 +1,56 @@ /** -* ============================================================================= -* CS2Fixes -* Copyright (C) 2023 Source2ZE -* ============================================================================= -* -* This program is free software; you can redistribute it and/or modify it under -* the terms of the GNU General Public License, version 3.0, as published by the -* Free Software Foundation. -* -* This program 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 -* this program. If not, see . -*/ + * ============================================================================= + * CS2Fixes + * Copyright (C) 2023 Source2ZE + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program 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 + * this program. If not, see . + */ #pragma once #include "platform.h" -#define CALL_VIRTUAL(retType, idx, ...) \ - vmt::CallVirtual(idx, __VA_ARGS__) +#define CALL_VIRTUAL(retType, idx, ...) vmt::CallVirtual(idx, __VA_ARGS__) -namespace vmt -{ +namespace vmt { template -inline T GetVMethod(uint32 uIndex, void *pClass) -{ - if (!pClass) - { - Warning("Tried getting virtual function from a null class.\n"); - return T(); - } +inline T GetVMethod(uint32 uIndex, void *pClass) { + if (!pClass) { + Warning("Tried getting virtual function from a null class.\n"); + return T(); + } - void **pVTable = *static_cast(pClass); - if (!pVTable) - { - Warning("Tried getting virtual function from a null vtable.\n"); - return T(); - } + void **pVTable = *static_cast(pClass); + if (!pVTable) { + Warning("Tried getting virtual function from a null vtable.\n"); + return T(); + } - return reinterpret_cast(pVTable[uIndex]); + return reinterpret_cast(pVTable[uIndex]); } template -inline T CallVirtual(uint32 uIndex, void *pClass, Args... args) -{ +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) - { - Warning("Tried calling a null virtual function.\n"); - return T(); - } + if (!pFunc) { + Warning("Tried calling a null virtual function.\n"); + return T(); + } - return pFunc(pClass, args...); + return pFunc(pClass, args...); } -} \ No newline at end of file +} // namespace vmt \ No newline at end of file