Compare commits

...

9 Commits

Author SHA1 Message Date
Michael Wilson
7f5103d9ee Add Basic VPROF Budgets, Add Con Command Unlocker to Core (#505) 2024-06-17 21:08:05 +10:00
dependabot[bot]
877b7c5a4a chore(deps): bump libraries/hl2sdk-cs2 from 4202f1c to 4b31db7 (#496)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Michael Wilson <roflmuffin@users.noreply.github.com>
2024-06-17 08:35:54 +00:00
WidovV
24363d6352 [no ci] Change example command prefix to follow "best practice" (#503) 2024-06-17 18:25:13 +10:00
Yarukon
2eaf7c2d8c Fix AddResource offset for Linux (#479) 2024-06-13 22:27:34 +10:00
dependabot[bot]
8b486ecf7e chore(deps): bump libraries/hl2sdk-cs2 from 739c88f to 4202f1c (#494)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Roflmuffin <shortguy014@gmail.com>
2024-06-13 22:26:50 +10:00
StefanX
54cc93e0f8 fix: CBasePlayerController_SetPawn signature (#493) 2024-06-13 21:55:33 +10:00
Michael Wilson
a695eec4fa Revert "fix: improve error handling if globals are accessed before ready"
This reverts commit e207be2fbf.
2024-05-31 20:06:26 +10:00
Roflmuffin
e207be2fbf fix: improve error handling if globals are accessed before ready 2024-05-31 12:51:48 +10:00
Nukoooo
eea64519a6 Update `GiveNamedItem` signature for linux (#470) 2024-05-31 08:49:03 +10:00
19 changed files with 302 additions and 407 deletions

View File

@@ -56,8 +56,6 @@ set(SOURCE_FILES
src/core/tick_scheduler.cpp
src/scripting/autonative.h
src/scripting/natives/natives_engine.cpp
src/core/engine_trace.h
src/core/engine_trace.cpp
src/scripting/natives/natives_callbacks.cpp
src/core/managers/player_manager.h
src/core/managers/player_manager.cpp

View File

@@ -79,7 +79,7 @@ public class HelloWorldPlugin : BasePlugin
return HookResult.Continue;
}
[ConsoleCommand("issue_warning", "Issue warning to player")]
[ConsoleCommand("css_issue_warning", "Issue warning to player")]
public void OnCommand(CCSPlayerController? player, CommandInfo command)
{
Logger.LogWarning("Player shouldn't be doing that");

View File

@@ -4,5 +4,7 @@
"FollowCS2ServerGuidelines": true,
"PluginHotReloadEnabled": true,
"PluginAutoLoadEnabled": true,
"ServerLanguage": "en"
"ServerLanguage": "en",
"UnlockConCommands": true,
"UnlockConVars": true
}

View File

@@ -36,7 +36,7 @@
"signatures": {
"library": "server",
"windows": "44 88 4C 24 ? 55 56 57 41 54 41 56 48 8D 6C 24 ?",
"linux": "55 48 89 E5 41 57 41 56 41 89 D6 41 55 49 89 FD 41 54 45 89 C4"
"linux": "55 48 89 E5 41 57 41 56 41 55 49 89 FD 41 54 45 89 C4"
}
},
"CCSPlayerPawnBase_PostThink": {
@@ -57,7 +57,7 @@
"signatures": {
"library": "server",
"windows": "48 89 5C 24 ? 48 89 74 24 ? 55 57 41 ? 41 ? 41 ? 48 ? ? ? ? 48 ? ? ? ? ? ? 4D ? ? 48",
"linux": "55 48 89 E5 41 57 41 56 49 89 D6 41 55 49 89 CD 41 54 49 89 F4 53 48 89 FB 48 8D 3D 33 DA 7B 00"
"linux": "55 48 89 E5 41 57 41 56 49 89 D6 41 55 49 89 CD 41 54 49 89 F4 53 48 89 FB 48 8D 3D"
}
},
"UTIL_Remove": {
@@ -237,7 +237,7 @@
"CEntityResourceManifest_AddResource": {
"offsets": {
"windows": 2,
"linux": 2
"linux": 0
}
}
}

View File

@@ -28,7 +28,6 @@ receive a ban.
> [!NOTE]
> Disable this option at your own risk.
## PluginHotReloadEnabled
When enabled, plugins are automatically reloaded when their .dll file is updated.
@@ -39,4 +38,12 @@ When enabled, plugins are automatically loaded from the plugins directory on ser
## ServerLanguage
Configures the default language to use for server commands & messages. The format for the culture name based on RFC 4646 is `languagecode2-country`/`regioncode2`, where `languagecode2` is the two-letter language code and `country/regioncode2` is the two-letter subculture code. Examples include `ja-JP` for Japanese (Japan) and `en-US` for English (United States). Defaults to "en".
Configures the default language to use for server commands & messages. The format for the culture name based on RFC 4646 is `languagecode2-country`/`regioncode2`, where `languagecode2` is the two-letter language code and `country/regioncode2` is the two-letter subculture code. Examples include `ja-JP` for Japanese (Japan) and `en-US` for English (United States). Defaults to "en".
## UnlockConCommands
When enabled, will remove the `FCVAR_HIDDEN`,`FCVAR_DEVELOPMENTONLY`, `FCVAR_MISSING0`, `FCVAR_MISSING1`, `FCVAR_MISSING2`, `FCVAR_MISSING3` flags from all console commands.
## UnlockConVars
When enabled, will remove the `FCVAR_HIDDEN`,`FCVAR_DEVELOPMENTONLY`, `FCVAR_MISSING0`, `FCVAR_MISSING1`, `FCVAR_MISSING2`, `FCVAR_MISSING3` flags from all console variables.

View File

@@ -46,15 +46,21 @@ namespace CounterStrikeSharp.API.Core
[JsonPropertyName("FollowCS2ServerGuidelines")]
public bool FollowCS2ServerGuidelines { get; set; } = true;
[JsonPropertyName("PluginHotReloadEnabled")]
public bool PluginHotReloadEnabled { get; set; } = true;
[JsonPropertyName("PluginAutoLoadEnabled")]
public bool PluginAutoLoadEnabled { get; set; } = true;
[JsonPropertyName("ServerLanguage")]
public string ServerLanguage { get; set; } = "en";
[JsonPropertyName("UnlockConCommands")]
public bool UnlockConCommands { get; set; } = true;
[JsonPropertyName("UnlockConVars")]
public bool UnlockConVars { get; set; } = true;
}
/// <summary>
@@ -97,14 +103,18 @@ namespace CounterStrikeSharp.API.Core
/// When enabled, plugins are automatically reloaded when their .dll file is updated.
/// </summary>
public static bool PluginHotReloadEnabled => _coreConfig.PluginHotReloadEnabled;
/// <summary>
/// When enabled, plugins are automatically loaded from the plugins directory on server start.
/// </summary>
public static bool PluginAutoLoadEnabled => _coreConfig.PluginAutoLoadEnabled;
public static string ServerLanguage => _coreConfig.ServerLanguage;
public static bool UnlockConCommands => _coreConfig.UnlockConCommands;
public static bool UnlockConVars => _coreConfig.UnlockConVars;
}
public partial class CoreConfig : IStartupService
@@ -140,7 +150,7 @@ namespace CounterStrikeSharp.API.Core
ReloadCoreConfigCommand));
_commandsRegistered = true;
}
if (!File.Exists(_coreConfigPath))
{
_logger.LogWarning(
@@ -181,13 +191,13 @@ namespace CounterStrikeSharp.API.Core
serverCulture = CultureInfo.InvariantCulture;
}
}
CultureInfo.DefaultThreadCurrentUICulture = serverCulture;
CultureInfo.DefaultThreadCurrentCulture = serverCulture;
CultureInfo.CurrentUICulture = serverCulture;
CultureInfo.CurrentCulture = serverCulture;
_logger.LogInformation("Successfully loaded core configuration");
}
}
}
}

View File

@@ -1,22 +1,24 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include "core/coreconfig.h"
#include <fstream>
#include "core/log.h"
#include "core/coreconfig.h"
namespace counterstrikesharp {
@@ -28,10 +30,12 @@ bool CCoreConfig::Init(char* conf_error, int conf_error_size)
{
std::ifstream ifs(std::string(m_sPath + ".json"));
if (!ifs) {
if (!ifs)
{
std::ifstream exampleIfs(std::string(m_sPath + ".example.json"));
if (!exampleIfs) {
if (!exampleIfs)
{
V_snprintf(conf_error, conf_error_size, "CoreConfig file not found.");
return false;
}
@@ -46,14 +50,19 @@ bool CCoreConfig::Init(char* conf_error, int conf_error_size)
m_json = json::parse(ifs);
try {
try
{
PublicChatTrigger = m_json.value("PublicChatTrigger", PublicChatTrigger);
SilentChatTrigger = m_json.value("SilentChatTrigger", SilentChatTrigger);
FollowCS2ServerGuidelines = m_json.value("FollowCS2ServerGuidelines", FollowCS2ServerGuidelines);
PluginHotReloadEnabled = m_json.value("PluginHotReloadEnabled", PluginHotReloadEnabled);
PluginAutoLoadEnabled = m_json.value("PluginAutoLoadEnabled", PluginAutoLoadEnabled);
ServerLanguage = m_json.value("ServerLanguage", ServerLanguage);
} catch (const std::exception& ex) {
UnlockConCommands = m_json.value("UnlockConCommands", UnlockConCommands);
UnlockConVars = m_json.value("UnlockConVars", UnlockConVars);
}
catch (const std::exception& ex)
{
V_snprintf(conf_error, conf_error_size, "Failed to parse CoreConfig file: %s", ex.what());
return false;
}
@@ -61,10 +70,7 @@ bool CCoreConfig::Init(char* conf_error, int conf_error_size)
return true;
}
const std::string CCoreConfig::GetPath() const
{
return m_sPath;
}
const std::string CCoreConfig::GetPath() const { return m_sPath; }
bool CCoreConfig::IsTriggerInternal(std::vector<std::string> triggers, const std::string& message, std::string& prefix) const
{
@@ -90,4 +96,4 @@ bool CCoreConfig::IsPublicChatTrigger(const std::string& message, std::string& p
{
return IsTriggerInternal(PublicChatTrigger, message, prefix);
}
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -1,25 +1,27 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#pragma once
#include "core/globals.h"
#include <string>
#include <nlohmann/json.hpp>
#include <string>
#include "core/globals.h"
namespace counterstrikesharp {
class CCoreConfig
@@ -31,6 +33,8 @@ class CCoreConfig
bool PluginHotReloadEnabled = true;
bool PluginAutoLoadEnabled = true;
std::string ServerLanguage = "en";
bool UnlockConCommands = true;
bool UnlockConVars = true;
using json = nlohmann::json;
CCoreConfig(const std::string& path);

View File

@@ -1,69 +0,0 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include "core/engine_trace.h"
#include "core/log.h"
namespace counterstrikesharp {
CTraceFilterHitAll g_HitAllFilter;
bool CSimpleTraceFilter::ShouldHitEntity(CEntityInstance *pServerEntity, int contentsMask) {
// int index = ExcIndexFromBaseHandle(pServerEntity->GetRefEHandle());
// if (index == m_index_to_exclude)
// return false;
return true;
}
TraceType_t TraceFilterProxy::GetTraceType() const {
auto nativeContext = fxNativeContext{};
auto scriptContext = ScriptContextRaw(nativeContext);
m_cb_get_trace_type(&nativeContext);
return scriptContext.GetResult<TraceType_t>();
}
bool TraceFilterProxy::ShouldHitEntity(CEntityInstance *pServerEntity, int contentsMask) {
return true;
// auto entity = ExcIndexFromBaseHandle(pServerEntity->GetRefEHandle());
// if (entity < 0)
// return false;
//
// auto nativeContext = fxNativeContext{};
// auto scriptContext = ScriptContextRaw(nativeContext);
//
// scriptContext.Push(entity);
// scriptContext.Push<int>(0);
//
// m_cb_should_hit_entity(&nativeContext);
//
// auto result = scriptContext.GetResult<bool>();
//
// CSSHARP_CORE_INFO("Received result {0} from `ShouldHitEntity`", result);
//
// return result;
/*return result;
return true;*/
}
void TraceFilterProxy::SetShouldHitEntityCallback(CallbackT cb) { m_cb_should_hit_entity = cb; }
void TraceFilterProxy::SetGetTraceTypeCallback(CallbackT cb) { m_cb_get_trace_type = cb; }
} // namespace counterstrikesharp

View File

@@ -1,52 +0,0 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#pragma once
#include <public/engine/IEngineTrace.h>
#include "scripting/callback_manager.h"
namespace counterstrikesharp {
class TraceFilterProxy : public ITraceFilter {
public:
TraceFilterProxy() {}
bool ShouldHitEntity(CEntityInstance *pServerEntity, int contentsMask);
TraceType_t GetTraceType() const;
void SetShouldHitEntityCallback(CallbackT cb);
void SetGetTraceTypeCallback(CallbackT cb);
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) {}
bool ShouldHitEntity(CEntityInstance *pServerEntity, int contentsMask);
TraceType_t GetTraceType() const { return TRACE_EVERYTHING; }
private:
int m_index_to_exclude = -1;
};
enum RayType { RayType_EndPoint, RayType_Infinite };
} // namespace counterstrikesharp

View File

@@ -39,6 +39,7 @@
#include <algorithm>
#include "core/coreconfig.h"
#include "core/log.h"
#include "core/memory.h"
#include "core/utils.h"
@@ -64,7 +65,7 @@ json WriteTypeJson(json obj, CSchemaType* current_type)
if (atomicTType->m_pAtomicInfo != nullptr)
{
obj["outer"] = atomicTType->m_pAtomicInfo->m_pszName1;
obj["outer"] = atomicTType->m_pAtomicInfo->m_pszName;
}
}
@@ -83,7 +84,7 @@ json WriteTypeJson(json obj, CSchemaType* current_type)
auto fixedArrayType = static_cast<CSchemaType_FixedArray*>(current_type);
obj["inner"] = WriteTypeJson(json::object(), fixedArrayType->m_pElementType);
}
else if (current_type->m_eTypeCategory == SCHEMA_TYPE_PTR)
else if (current_type->m_eTypeCategory == SCHEMA_TYPE_POINTER)
{
auto ptrType = static_cast<CSchemaType_Ptr*>(current_type);
obj["inner"] = WriteTypeJson(json::object(), ptrType->m_pObjectType);
@@ -203,6 +204,63 @@ void ConCommandManager::OnAllInitialized()
m_global_cmd.callback_pre = globals::callbackManager.CreateCallback("OnClientCommandGlobalPre");
m_global_cmd.callback_post = globals::callbackManager.CreateCallback("OnClientCommandGlobalPost");
if (globals::coreConfig->UnlockConCommands)
{
UnlockConCommands();
}
if (globals::coreConfig->UnlockConVars)
{
UnlockConVars();
}
}
static uint64 flagsToRemove = (FCVAR_HIDDEN | FCVAR_DEVELOPMENTONLY | FCVAR_MISSING0 | FCVAR_MISSING1 | FCVAR_MISSING2 | FCVAR_MISSING3);
void UnlockConVars()
{
int unhiddenConVars = 0;
ConVar* currentCvar = nullptr;
ConVarHandle currentCvarHandle;
currentCvarHandle.Set(0);
do
{
currentCvar = globals::cvars->GetConVar(currentCvarHandle);
currentCvarHandle.Set(currentCvarHandle.Get() + 1);
if (!currentCvar) continue;
if (!(currentCvar->flags & flagsToRemove)) continue;
currentCvar->flags &= ~flagsToRemove;
unhiddenConVars++;
} while (currentCvar);
}
void UnlockConCommands()
{
int unhiddenConCommands = 0;
ConCommand* currentConCommand = nullptr;
ConCommand* invalidConCommand = globals::cvars->GetCommand(ConCommandHandle());
ConCommandHandle conCommandHandle;
conCommandHandle.Set(0);
do
{
currentConCommand = globals::cvars->GetCommand(conCommandHandle);
conCommandHandle.Set(conCommandHandle.Get() + 1);
if (!currentConCommand || currentConCommand == invalidConCommand || !(currentConCommand->GetFlags() & flagsToRemove)) continue;
currentConCommand->RemoveFlags(flagsToRemove);
unhiddenConCommands++;
} while (currentConCommand && currentConCommand != invalidConCommand);
}
void ConCommandManager::OnShutdown()

View File

@@ -32,46 +32,52 @@
#pragma once
#include <map>
#include <string>
#include <vector>
#include "core/globals.h"
#include "core/global_listener.h"
#include "scripting/script_engine.h"
#include <string>
#include "core/globals.h"
#include "playerslot.h"
#include "scripting/script_engine.h"
struct CaseInsensitiveComparator {
bool operator()(const std::string& lhs, const std::string& rhs) const {
return std::lexicographical_compare(
lhs.begin(), lhs.end(),
rhs.begin(), rhs.end(),
[](char a, char b) { return std::tolower(a) < std::tolower(b); }
);
struct CaseInsensitiveComparator
{
bool operator()(const std::string& lhs, const std::string& rhs) const
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), [](char a, char b) {
return std::tolower(a) < std::tolower(b);
});
}
};
namespace counterstrikesharp {
void UnlockConVars();
void UnlockConCommands();
class ScriptCallback;
enum CommandCallingContext {
enum CommandCallingContext
{
Console = 0,
Chat = 1,
};
class ConCommandInfo {
class ConCommandInfo
{
friend class ConCommandManager;
public:
ConCommandInfo();
ConCommandInfo(bool bNoCallbacks);
public:
ConCommandInfo();
ConCommandInfo(bool bNoCallbacks);
~ConCommandInfo();
public:
public:
void HookChange(CallbackT callback, bool post);
void UnhookChange(CallbackT callback, bool post);
ScriptCallback* GetCallback() { return callback_pre; }
private:
private:
ConCommandRefAbstract p_cmd;
ConCommand* command;
ScriptCallback* callback_pre;
@@ -79,10 +85,11 @@ private:
bool server_only;
};
class ConCommandManager : public GlobalClass {
class ConCommandManager : public GlobalClass
{
friend class ConCommandInfo;
public:
public:
ConCommandManager();
~ConCommandManager();
void OnAllInitialized() override;
@@ -95,15 +102,16 @@ public:
bool RemoveValveCommand(const char* name);
void Hook_DispatchConCommand(ConCommandHandle cmd, const CCommandContext& ctx, const CCommand& args);
void Hook_DispatchConCommand_Post(ConCommandHandle cmd, const CCommandContext& ctx, const CCommand& args);
HookResult ExecuteCommandCallbacks(const char* name, const CCommandContext& ctx,
const CCommand& args, HookMode mode, CommandCallingContext callingContext);
HookResult ExecuteCommandCallbacks(
const char* name, const CCommandContext& ctx, const CCommand& args, HookMode mode, CommandCallingContext callingContext);
CommandCallingContext GetCommandCallingContext(CCommand* args);
private:
private:
std::vector<ConCommandInfo*> m_cmd_list;
std::map<std::string, ConCommandInfo*, CaseInsensitiveComparator> m_cmd_lookup;
std::map<const CCommand*, CommandCallingContext> m_cmd_contexts;
ConCommandInfo m_global_cmd = ConCommandInfo(true);
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -33,6 +33,7 @@
#include "core/log.h"
#include "scripting/callback_manager.h"
#include "vprof.h"
SH_DECL_HOOK2(IGameEventManager2, FireEvent, SH_NOATTRIB, 0, bool, IGameEvent*, bool);
@@ -211,6 +212,7 @@ bool EventManager::OnFireEvent(IGameEvent* pEvent, bool bDontBroadcast)
pCallback->ScriptContext().Push(pEvent);
pCallback->ScriptContext().Push(&override);
VPROF_BUDGET("CS#::OnFireEvent", "CS# Event Hooks");
for (auto fnMethodToCall : pCallback->GetFunctions())
{
if (!fnMethodToCall) continue;
@@ -257,6 +259,8 @@ bool EventManager::OnFireEventPost(IGameEvent* pEvent, bool bDontBroadcast)
if (pCallback)
{
VPROF_BUDGET("CS#::OnFireEventPost", "CS# Event Hooks");
auto pEventCopy = m_EventCopies.top();
CSSHARP_CORE_TRACE("Pushing event `{}` pointer: {}, dont broadcast: {}, post: {}", pEventCopy->GetName(), (void*)pEventCopy,
bDontBroadcast, true);

View File

@@ -16,22 +16,23 @@
#include <cstdio>
#include "core/coreconfig.h"
#include "core/game_system.h"
#include "core/gameconfig.h"
#include "core/global_listener.h"
#include "core/log.h"
#include "core/coreconfig.h"
#include "core/gameconfig.h"
#include "core/game_system.h"
#include "core/timer_system.h"
#include "core/tick_scheduler.h"
#include "core/utils.h"
#include "core/managers/entity_manager.h"
#include "core/tick_scheduler.h"
#include "core/timer_system.h"
#include "core/utils.h"
#include "entity2/entitysystem.h"
#include "igameeventsystem.h"
#include "interfaces/cs2_interfaces.h"
#include "iserver.h"
#include "scripting/callback_manager.h"
#include "scripting/dotnet_host.h"
#include "scripting/script_engine.h"
#include "entity2/entitysystem.h"
#include "interfaces/cs2_interfaces.h"
#include "tier0/vprof.h"
#define VERSION_STRING "v" BUILD_NUMBER " @ " GITHUB_SHA
#define BUILD_TIMESTAMP __DATE__ " " __TIME__
@@ -203,6 +204,7 @@ void CounterStrikeSharpMMPlugin::Hook_GameFrame(bool simulating, bool bFirstTick
* true | game is ticking
* false | game is not ticking
*/
VPROF_BUDGET("CS#::Hook_GameFrame", "CS# On Frame");
globals::timerSystem.OnGameFrame(simulating);
std::vector<std::function<void()>> out_list(1024);

View File

@@ -12,65 +12,68 @@
* This sample plugin is public domain.
*/
#ifndef _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_
#define _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_
#define VPROF_LEVEL 1
#include <ISmmPlugin.h>
#include <functional>
#include <iserver.h>
#include <igameevents.h>
#include <iplayerinfo.h>
#include <sh_vector.h>
#include <vector>
#include "entitysystem.h"
#include "concurrentqueue.h"
#ifndef _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_
#define _INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_
#include <ISmmPlugin.h>
#include <igameevents.h>
#include <iplayerinfo.h>
#include <iserver.h>
#include <sh_vector.h>
#include <functional>
#include <vector>
#include "concurrentqueue.h"
#include "entitysystem.h"
namespace counterstrikesharp {
class ScriptCallback;
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;
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,
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 AddTaskForNextFrame(std::function<void()> &&task);
void Hook_StartupServer(const GameSessionConfiguration_t& config, ISource2WorldSession*, const char*);
void AddTaskForNextFrame(std::function<void()>&& task);
void Hook_RegisterLoopMode(const char* pszLoopModeName, ILoopModeFactory *pLoopModeFactory, void **ppGlobalPointer);
void Hook_RegisterLoopMode(const char* pszLoopModeName, ILoopModeFactory* pLoopModeFactory, void** ppGlobalPointer);
IEngineService* Hook_FindService(const char* serviceName);
public:
const char *GetAuthor() override;
const char *GetName() override;
const char *GetDescription() override;
const char *GetURL() override;
const char *GetLicense() override;
const char *GetVersion() override;
const char *GetDate() override;
const char *GetLogTag() override;
public:
const char* GetAuthor() override;
const char* GetName() override;
const char* GetDescription() override;
const char* GetURL() override;
const char* GetLicense() override;
const char* GetVersion() override;
const char* GetDate() override;
const char* GetLogTag() override;
private:
private:
moodycamel::ConcurrentQueue<std::function<void()>> m_nextTasks;
};
static ScriptCallback *on_activate_callback;
static ScriptCallback* on_activate_callback;
extern CounterStrikeSharpMMPlugin gPlugin;
PLUGIN_GLOBALVARS();
#endif //_INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_
}
#endif //_INCLUDE_METAMOD_SOURCE_STUB_PLUGIN_H_
}

View File

@@ -15,43 +15,48 @@
*/
#include "scripting/callback_manager.h"
#include "core/log.h"
#include <algorithm>
#include "core/log.h"
#include "vprof.h"
namespace counterstrikesharp {
ScriptCallback::ScriptCallback(const char* szName) : m_root_context(fxNativeContext{})
{
m_script_context_raw = ScriptContextRaw(m_root_context);
m_name = std::string(szName);
m_profile_name = "ScriptCallback::Execute::" + m_name;
}
ScriptCallback::~ScriptCallback() { m_functions.clear(); }
void ScriptCallback::AddListener(CallbackT fnPluginFunction)
{
m_functions.push_back(fnPluginFunction);
}
void ScriptCallback::AddListener(CallbackT fnPluginFunction) { m_functions.push_back(fnPluginFunction); }
bool ScriptCallback::RemoveListener(CallbackT fnPluginFunction)
{
bool bSuccess = true;
m_functions.erase(std::remove(m_functions.begin(), m_functions.end(), fnPluginFunction),
m_functions.end());
m_functions.erase(std::remove(m_functions.begin(), m_functions.end(), fnPluginFunction), m_functions.end());
return bSuccess;
}
void ScriptCallback::Execute(bool bResetContext)
{
for (auto fnMethodToCall : m_functions) {
if (fnMethodToCall) {
VPROF_BUDGET(m_profile_name.c_str(), "CS# Script Callbacks");
for (auto fnMethodToCall : m_functions)
{
if (fnMethodToCall)
{
fnMethodToCall(&ScriptContextStruct());
}
}
if (bResetContext) {
if (bResetContext)
{
Reset();
}
}
@@ -71,8 +76,10 @@ ScriptCallback* CallbackManager::CreateCallback(const char* szName)
ScriptCallback* CallbackManager::FindCallback(const char* szName)
{
for (auto* pMarshal : m_managed) {
if (strcmp(pMarshal->GetName().c_str(), szName) == 0) {
for (auto* pMarshal : m_managed)
{
if (strcmp(pMarshal->GetName().c_str(), szName) == 0)
{
return pMarshal;
}
}
@@ -82,18 +89,19 @@ ScriptCallback* CallbackManager::FindCallback(const char* szName)
void CallbackManager::ReleaseCallback(ScriptCallback* pCallback)
{
auto I = std::remove_if(m_managed.begin(), m_managed.end(),
[pCallback](ScriptCallback* pI) { return pCallback == pI; });
auto I = std::remove_if(m_managed.begin(), m_managed.end(), [pCallback](ScriptCallback* pI) {
return pCallback == pI;
});
if (I != m_managed.end())
m_managed.erase(I, m_managed.end());
if (I != m_managed.end()) m_managed.erase(I, m_managed.end());
delete pCallback;
}
bool CallbackManager::TryAddFunction(const char* szName, CallbackT fnCallable)
{
auto* pCallback = FindCallback(szName);
if (pCallback) {
if (pCallback)
{
pCallback->AddListener(fnCallable);
return true;
}
@@ -104,7 +112,8 @@ bool CallbackManager::TryAddFunction(const char* szName, CallbackT fnCallable)
bool CallbackManager::TryRemoveFunction(const char* szName, CallbackT fnCallable)
{
auto* pCallback = FindCallback(szName);
if (pCallback) {
if (pCallback)
{
return pCallback->RemoveListener(fnCallable);
}
@@ -114,7 +123,8 @@ bool CallbackManager::TryRemoveFunction(const char* szName, CallbackT fnCallable
void CallbackManager::PrintCallbackDebug()
{
CSSHARP_CORE_INFO("----CALLBACKS----");
for (auto* pCallback : m_managed) {
for (auto* pCallback : m_managed)
{
CSSHARP_CORE_INFO("{0} ({0})\n", pCallback->GetName().c_str(), 1);
}
}
@@ -126,7 +136,8 @@ CallbackPair::CallbackPair()
CallbackPair::CallbackPair(bool bNoCallbacks)
{
if (!bNoCallbacks) {
if (!bNoCallbacks)
{
pre = globals::callbackManager.CreateCallback("");
post = globals::callbackManager.CreateCallback("");
}
@@ -138,4 +149,4 @@ CallbackPair::~CallbackPair()
globals::callbackManager.ReleaseCallback(post);
}
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -43,6 +43,7 @@ class ScriptCallback
private:
std::vector<CallbackT> m_functions;
std::string m_name;
std::string m_profile_name;
ScriptContextRaw m_script_context_raw;
fxNativeContext m_root_context;
};
@@ -69,12 +70,11 @@ class CallbackPair
CallbackPair();
CallbackPair(bool bNoCallbacks);
~CallbackPair();
bool HasCallbacks() const
{ return pre->GetFunctionCount() > 0 || post->GetFunctionCount() > 0; }
bool HasCallbacks() const { return pre->GetFunctionCount() > 0 || post->GetFunctionCount() > 0; }
public:
ScriptCallback* pre;
ScriptCallback* post;
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -22,7 +22,6 @@
// clang-format off
#include "mm_plugin.h"
#include "core/engine_trace.h"
#include "core/timer_system.h"
#include "core/utils.h"
#include "scripting/autonative.h"
@@ -43,16 +42,12 @@ namespace counterstrikesharp {
const char* GetMapName(ScriptContext& script_context)
{
if (globals::getGlobalVars() == nullptr)
return nullptr;
if (globals::getGlobalVars() == nullptr) return nullptr;
return globals::getGlobalVars()->mapname.ToCStr();
}
const char* GetGameDirectory(ScriptContext& script_context)
{
return strdup(Plat_GetGameDirectory());
}
const char* GetGameDirectory(ScriptContext& script_context) { return strdup(Plat_GetGameDirectory()); }
bool IsMapValid(ScriptContext& script_context)
{
@@ -60,26 +55,21 @@ bool IsMapValid(ScriptContext& script_context)
return globals::engine->IsMapValid(mapname) != 0;
}
float GetTickInterval(ScriptContext& script_context)
{
return globals::engine_fixed_tick_interval;
}
float GetTickInterval(ScriptContext& script_context) { return globals::engine_fixed_tick_interval; }
float GetCurrentTime(ScriptContext& script_context) { return globals::getGlobalVars()->curtime; }
int GetTickCount(ScriptContext& script_context) { return globals::getGlobalVars()->tickcount; }
float GetGameFrameTime(ScriptContext& script_context)
{
return globals::getGlobalVars()->frametime;
}
float GetGameFrameTime(ScriptContext& script_context) { return globals::getGlobalVars()->frametime; }
double GetEngineTime(ScriptContext& script_context) { return Plat_FloatTime(); }
int GetMaxClients(ScriptContext& script_context)
{
auto globalVars = globals::getGlobalVars();
if (globalVars == nullptr) {
if (globalVars == nullptr)
{
script_context.ThrowNativeError("Global Variables not initialized yet.");
return -1;
}
@@ -144,83 +134,6 @@ float GetSoundDuration(ScriptContext& script_context)
// attenuation, 0, flags, pitch, origin, direction);
// }
Ray_t* CreateRay1(ScriptContext& script_context)
{
auto ray_type = script_context.GetArgument<RayType>(0);
auto vec1 = script_context.GetArgument<Vector*>(1);
auto vec2 = script_context.GetArgument<Vector*>(2);
Ray_t* pRay = new Ray_t;
if (ray_type == RayType_EndPoint) {
pRay->Init(*vec1, *vec2);
return pRay;
} else if (ray_type == RayType_Infinite) {
QAngle angles;
Vector endVec;
angles.Init(vec2->x, vec2->y, vec2->z);
AngleVectors(angles, &endVec);
endVec.NormalizeInPlace();
endVec = *vec1 + endVec * MAX_TRACE_LENGTH;
pRay->Init(*vec1, endVec);
return pRay;
}
return nullptr;
}
Ray_t* CreateRay2(ScriptContext& script_context)
{
auto vec1 = script_context.GetArgument<Vector*>(0);
auto vec2 = script_context.GetArgument<Vector*>(1);
auto vec3 = script_context.GetArgument<Vector*>(2);
auto vec4 = script_context.GetArgument<Vector*>(3);
Ray_t* pRay = new Ray_t;
pRay->Init(*vec1, *vec2, *vec3, *vec4);
return pRay;
}
void TraceRay(ScriptContext& script_context)
{
auto ray = script_context.GetArgument<Ray_t*>(0);
auto pTrace = script_context.GetArgument<CGameTrace*>(1);
auto trace_filter = script_context.GetArgument<ITraceFilter*>(2);
auto flags = script_context.GetArgument<uint32_t>(3);
globals::engineTrace->TraceRay(*ray, flags, trace_filter, pTrace);
}
CSimpleTraceFilter* NewSimpleTraceFilter(ScriptContext& script_context)
{
auto index_to_ignore = script_context.GetArgument<int>(0);
return new CSimpleTraceFilter(index_to_ignore);
}
TraceFilterProxy* NewTraceFilterProxy(ScriptContext& script_context)
{
return new TraceFilterProxy();
}
void TraceFilterProxySetTraceTypeCallback(ScriptContext& script_context)
{
auto trace_filter = script_context.GetArgument<TraceFilterProxy*>(0);
auto callback = script_context.GetArgument<CallbackT>(1);
trace_filter->SetGetTraceTypeCallback(callback);
}
void TraceFilterProxySetShouldHitEntityCallback(ScriptContext& script_context)
{
auto [trace_filter, callback] = script_context.GetArguments<TraceFilterProxy*, CallbackT>();
trace_filter->SetShouldHitEntityCallback(callback);
}
CGameTrace* NewTraceResult(ScriptContext& script_context) { return new CGameTrace(); }
double GetTickedTime(ScriptContext& script_context) { return globals::timerSystem.GetTickedTime(); }
void QueueTaskForNextFrame(ScriptContext& script_context)
@@ -228,7 +141,9 @@ void QueueTaskForNextFrame(ScriptContext& script_context)
auto func = script_context.GetArgument<void*>(0);
typedef void(voidfunc)(void);
globals::mmPlugin->AddTaskForNextFrame([func]() { reinterpret_cast<voidfunc*>(func)(); });
globals::mmPlugin->AddTaskForNextFrame([func]() {
reinterpret_cast<voidfunc*>(func)();
});
}
void QueueTaskForNextWorldUpdate(ScriptContext& script_context)
@@ -236,7 +151,9 @@ void QueueTaskForNextWorldUpdate(ScriptContext& script_context)
auto func = script_context.GetArgument<void*>(0);
typedef void(voidfunc)(void);
globals::serverManager.AddTaskForNextWorldUpdate([func]() { reinterpret_cast<voidfunc*>(func)(); });
globals::serverManager.AddTaskForNextWorldUpdate([func]() {
reinterpret_cast<voidfunc*>(func)();
});
}
void QueueTaskForFrame(ScriptContext& script_context)
@@ -259,15 +176,19 @@ void* GetValveInterface(ScriptContext& scriptContext)
auto [interfaceType, interfaceName] = scriptContext.GetArguments<InterfaceType, const char*>();
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");
}
@@ -280,33 +201,29 @@ void GetCommandParamValue(ScriptContext& scriptContext)
auto paramType = scriptContext.GetArgument<DataType_t>(1);
int iContextIndex = 2;
switch (paramType) {
case DATA_TYPE_STRING:
scriptContext.SetResult(CommandLine()->ParmValue(
paramName, scriptContext.GetArgument<const char*>(iContextIndex)));
return;
case DATA_TYPE_INT:
scriptContext.SetResult(
CommandLine()->ParmValue(paramName, scriptContext.GetArgument<int>(iContextIndex)));
return;
case DATA_TYPE_FLOAT:
scriptContext.SetResult(
CommandLine()->ParmValue(paramName, scriptContext.GetArgument<float>(iContextIndex)));
return;
switch (paramType)
{
case DATA_TYPE_STRING:
scriptContext.SetResult(CommandLine()->ParmValue(paramName, scriptContext.GetArgument<const char*>(iContextIndex)));
return;
case DATA_TYPE_INT:
scriptContext.SetResult(CommandLine()->ParmValue(paramName, scriptContext.GetArgument<int>(iContextIndex)));
return;
case DATA_TYPE_FLOAT:
scriptContext.SetResult(CommandLine()->ParmValue(paramName, scriptContext.GetArgument<float>(iContextIndex)));
return;
}
scriptContext.ThrowNativeError("Invalid param type");
}
void PrintToServerConsole(ScriptContext& scriptContext) {
void PrintToServerConsole(ScriptContext& scriptContext)
{
auto message = scriptContext.GetArgument<const char*>(0);
META_CONPRINT(message);
}
CREATE_GETTER_FUNCTION(Trace, bool, DidHit, CGameTrace*, obj->DidHit());
CREATE_GETTER_FUNCTION(TraceResult, CBaseEntity*, Entity, CGameTrace*, obj->m_pEnt);
REGISTER_NATIVES(engine, {
ScriptEngine::RegisterNativeHandler("GET_GAME_DIRECTORY", GetGameDirectory);
ScriptEngine::RegisterNativeHandler("GET_MAP_NAME", GetMapName);
@@ -324,20 +241,6 @@ REGISTER_NATIVES(engine, {
ScriptEngine::RegisterNativeHandler("GET_SOUND_DURATION", GetSoundDuration);
// ScriptEngine::RegisterNativeHandler("EMIT_SOUND", EmitSound);
ScriptEngine::RegisterNativeHandler("NEW_SIMPLE_TRACE_FILTER", NewSimpleTraceFilter);
ScriptEngine::RegisterNativeHandler("NEW_TRACE_RESULT", NewTraceResult);
ScriptEngine::RegisterNativeHandler("TRACE_DID_HIT", TraceGetDidHit);
ScriptEngine::RegisterNativeHandler("TRACE_RESULT_ENTITY", TraceResultGetEntity);
ScriptEngine::RegisterNativeHandler("NEW_TRACE_FILTER_PROXY", NewTraceFilterProxy);
ScriptEngine::RegisterNativeHandler("TRACE_FILTER_PROXY_SET_TRACE_TYPE_CALLBACK",
TraceFilterProxySetTraceTypeCallback);
ScriptEngine::RegisterNativeHandler("TRACE_FILTER_PROXY_SET_SHOULD_HIT_ENTITY_CALLBACK",
TraceFilterProxySetShouldHitEntityCallback);
ScriptEngine::RegisterNativeHandler("CREATE_RAY_1", CreateRay1);
ScriptEngine::RegisterNativeHandler("CREATE_RAY_2", CreateRay2);
ScriptEngine::RegisterNativeHandler("TRACE_RAY", TraceRay);
ScriptEngine::RegisterNativeHandler("GET_TICKED_TIME", GetTickedTime);
ScriptEngine::RegisterNativeHandler("QUEUE_TASK_FOR_NEXT_FRAME", QueueTaskForNextFrame);
ScriptEngine::RegisterNativeHandler("QUEUE_TASK_FOR_NEXT_WORLD_UPDATE", QueueTaskForNextWorldUpdate);