VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
Plugin.cpp
Go to the documentation of this file.
2#include "Schema/Layout.hpp"
3
11#include <VoltMod/Runtime.hpp>
12#include <engine2/igameeventsystem.h>
13#include <engine2/isource2server.h>
14#include <engine2/ivengineserver2.h>
15#include <exception>
16#include <format>
17#include <icvar.h>
18#include <interfaces/interfaces.h>
19#include <memory>
20#include <networksystem/inetworkmessages.h>
21#include <schemasystem/schemasystem.h>
22#include <string>
23#include <string_view>
24#include <tier0/convar.h>
25
26namespace VoltMod::Internal
27{
28
33
34bool PluginModule::Attach(IPluginContext& host, char* error, size_t errorSize) noexcept
35{
36 try
37 {
38 const bool loaded = AttachImpl(host, error, errorSize);
39 if (!loaded)
40 {
41 _host = nullptr;
42 }
43 return loaded;
44 }
45 catch (const std::exception& exception)
46 {
47 Strings::CopyToBuffer(error, errorSize, exception.what());
48 Shutdown();
49 _host = nullptr;
50 return false;
51 }
52 catch (...)
53 {
54 Strings::CopyToBuffer(error, errorSize, "plugin threw a non-standard exception during load");
55 Shutdown();
56 _host = nullptr;
57 return false;
58 }
59}
60
61using InterfaceLookup = void* (IPluginContext::*)(const char* version) const;
62
63template <class T>
64static Status Resolve(T*& field, const IPluginContext& host, InterfaceLookup lookup, const char* version)
65{
66 field = static_cast<T*>((host.*lookup)(version));
67 if (!field)
68 {
69 return std::unexpected(Error::NotReady(std::format("Could not find interface: {}", version)));
70 }
71 return {};
72}
73
74/** Resolve the engine interfaces and bind the host's gamedata. Fails when an interface is missing; a
75 * gamedata failure is kept in `GameData`, and the services that need it say so. */
77{
78 auto unsafe = std::make_unique<UnsafeServices>();
79 auto& gi = unsafe->Interfaces;
80
83 const Status resolved[] = {
84 Resolve(gi.ServerGameDLL, host, server, INTERFACEVERSION_SERVERGAMEDLL),
85 Resolve(gi.ServerGameClients, host, server, INTERFACEVERSION_SERVERGAMECLIENTS),
86 Resolve(gi.NetworkServerService, host, engine, NETWORKSERVERSERVICE_INTERFACE_VERSION),
87 Resolve(gi.GameEntities, host, server, INTERFACEVERSION_SERVERGAMEENTS),
88 Resolve(gi.Engine, host, engine, INTERFACEVERSION_VENGINESERVER),
89 Resolve(gi.GameEventSystem, host, engine, GAMEEVENTSYSTEM_INTERFACE_VERSION),
90 Resolve(gi.NetworkMessages, host, engine, NETWORKMESSAGES_INTERFACE_VERSION),
91 Resolve(gi.SchemaSystem, host, engine, SCHEMASYSTEM_INTERFACE_VERSION),
92 Resolve(gi.CVar, host, engine, CVAR_INTERFACE_VERSION),
93 Resolve(gi.GameResourceService, host, engine, GAMERESOURCESERVICESERVER_INTERFACE_VERSION),
94 };
95 for (const Status& status : resolved)
96 {
97 if (!status)
98 {
99 return std::unexpected(status.error());
100 }
101 }
102
103 // Register pending tier1 ConCommands before the engine invokes ServerCommand instances.
104 g_pCVar = gi.CVar;
105 // The SDK's ::GameEntitySystem() reads it.
106 g_pGameResourceServiceServer = gi.GameResourceService;
107 ConVar_Register(FCVAR_RELEASE | FCVAR_CLIENT_CAN_EXECUTE | FCVAR_SERVER_CAN_EXECUTE | FCVAR_GAMEDLL);
108
109 // The host read and scanned gamedata once for the process; this only takes the numbers.
110 if (IPluginGameData* gameData = host.GameData())
111 {
112 unsafe->GameData = unsafe->Bindings.Bind(
113 [gameData](GameDataSection sections, std::string_view name) { return gameData->Lookup(sections, name); });
114 }
115 else
116 {
117 unsafe->GameData = std::unexpected(Error::Engine("the host has no gamedata"));
118 }
119 return unsafe;
120}
121
122/** Fill this module's generated offsets from the running server before any accessor runs. */
124{
127 [&host](std::string_view className, std::string_view field) { return host.FindSchemaField(className, field); });
128}
129
130bool PluginModule::AttachImpl(IPluginContext& host, char* error, size_t errorSize)
131{
133 _host = &host;
134
135 // The host owns the console and prefixes this plugin's log tag; services log while they are built.
136 Log::SetMinimumLevel(static_cast<LogLevel>(host.MinLogLevel()));
138 [&host](LogLevel level, std::string_view message) { host.WriteLog(static_cast<uint8_t>(level), message); });
139 SetBaseDir(host.BaseDir());
140
141 if (Status schema = ResolveSchema(host); !schema)
142 {
143 return Refuse(std::format("SchemaLayout: {}", schema.error().Detail), error, errorSize);
144 }
145
146 auto unsafe = OpenUnsafe(host);
147 if (!unsafe)
148 {
149 return Refuse(unsafe.error().Detail, error, errorSize);
150 }
151 _unsafe = std::move(*unsafe);
152 _languages = std::make_unique<HostPlayerLanguages>(host.Languages());
153 _runtime = std::make_unique<Runtime>(host, *_unsafe, *_languages);
154
155 // Members that load settings record a required step, so a failure refuses the plugin before Load.
156 _plugin = _factory(*_runtime);
157 if (std::string reason = _runtime->LoadReport.AbortReason(); !reason.empty())
158 {
159 return Refuse(reason, error, errorSize);
160 }
161
162 SubscribeHostEvents();
163
164 if (!_plugin->Load())
165 {
166 std::string reason = _runtime->LoadReport.AbortReason();
167 return Refuse(reason.empty() ? "Load returned false" : reason, error, errorSize);
168 }
169
170 Log::Info("{}", _runtime->LoadReport.Summary());
171 return true;
172}
173
174bool PluginModule::Refuse(std::string_view reason, char* error, size_t errorSize)
175{
176 if (_runtime)
177 {
178 Log::Info("{}", _runtime->LoadReport.Summary());
179 }
180 Strings::CopyToBuffer(error, errorSize, reason);
181 Shutdown();
182 return false;
183}
184
185void PluginModule::Detach() noexcept
186{
187 Shutdown();
188 _host = nullptr;
189}
190
191// Stop commands before destroying their captured state, then drop host events and services.
192void PluginModule::Shutdown() noexcept
193{
194 if (_runtime)
195 {
196 _runtime->Commands.RemoveAll();
197 }
198 _plugin.reset();
199 _hostEvents.Clear();
200 _runtime.reset();
201 _languages.reset();
202 _unsafe.reset();
203}
204
205const char* PluginModule::StatusJson() noexcept
206{
207 try
208 {
209 _status = _runtime ? _runtime->Status.BuildJson() : std::string("{}");
210 return _status.c_str();
211 }
212 catch (...)
213 {
214 return "{}";
215 }
216}
217
218void PluginModule::SubscribeHostEvents()
219{
220 IPluginEvents& events = _host->Events();
221 auto keep = [&](uint64_t token) { _hostEvents.Add(HostSubscription(events, token)); };
222
223 keep(events.OnFrame(&HostCallback<&PluginModule::OnFrame>::Call, this));
224 keep(events.OnServerStartup(&HostCallback<&PluginModule::OnServerStartup>::Call, this));
225 keep(events.OnClientConnecting(&HostCallback<&PluginModule::OnClientConnecting>::Call, this));
226 keep(events.OnClientConnected(&HostCallback<&PluginModule::OnClientConnected>::Call, this));
227 keep(events.OnClientDisconnected(&HostCallback<&PluginModule::OnClientDisconnected>::Call, this));
228 keep(events.OnClientFullyConnected(&HostCallback<&PluginModule::OnClientFullyConnected>::Call, this));
229 keep(events.OnClientSettingsChanged(&HostCallback<&PluginModule::OnClientSettingsChanged>::Call, this));
230 keep(events.OnConsoleCommand(&HostCallback<&PluginModule::OnConsoleCommand>::Call, this));
231 keep(events.OnCheckTransmit(&HostCallback<&PluginModule::OnCheckTransmit>::Call, this));
232 keep(events.OnBuildGameSessionManifest(&HostCallback<&PluginModule::OnBuildGameSessionManifest>::Call, this));
233}
234
235void PluginModule::OnFrame()
236{
237 // `volt log` changes this; reading it once a frame lets the log helpers skip silenced lines.
238 Log::SetMinimumLevel(static_cast<LogLevel>(_host->MinLogLevel()));
239 _runtime->OnGameFrame();
240}
241
242void PluginModule::OnServerStartup(std::string_view mapName)
243{
244 Log::Info("Server startup: map '{}'.", mapName.empty() ? std::string_view("<none>") : mapName);
245 _runtime->Map.SetCurrent(std::string(mapName));
246 _runtime->Entities.OnServerStartup();
247 _runtime->GameEvents.OnServerStartup();
248 _runtime->ClientConVars.OnServerStartup();
249 _runtime->Map.Started.Raise(mapName);
250}
251
252bool PluginModule::OnClientConnecting(int slot, int64_t steamId, std::string_view name, char* reason, size_t reasonSize)
253{
254 ConnectRequest request{.Slot = slot, .SteamId = steamId, .Name = name};
255 _runtime->Players.Connecting.Raise(request);
256 if (request.Rejected)
257 {
258 Strings::CopyToBuffer(reason, reasonSize, request.Reason);
259 }
260 return request.Rejected;
261}
262
263void PluginModule::OnClientConnected(int slot, int64_t steamId, std::string_view name, std::string_view address)
264{
265 _runtime->Players.Add(slot, steamId, std::string(name), std::string(address));
266}
267
268void PluginModule::OnClientDisconnected(int slot)
269{
270 _runtime->Players.Remove(slot);
271}
272
273void PluginModule::OnClientFullyConnected(int slot)
274{
275 _runtime->Players.OnClientFullyConnected(slot);
276}
277
278void PluginModule::OnClientSettingsChanged(int slot)
279{
280 _runtime->Players.OnClientSettingsChanged(slot);
281}
282
283void PluginModule::OnCheckTransmit(CCheckTransmitInfo** infoList, int infoCount)
284{
285 _runtime->Visibility.OnCheckTransmit(infoList, infoCount);
286}
287
288void PluginModule::OnBuildGameSessionManifest(IEntityResourceManifest* manifest)
289{
290 _runtime->Precache.WriteTo(*manifest);
291}
292
293} // namespace VoltMod::Internal
const char * StatusJson() noexcept
Definition Plugin.cpp:205
bool Attach(IPluginContext &host, char *error, size_t errorSize) noexcept
Definition Plugin.cpp:34
static void CopyToBuffer(char *buffer, std::size_t size, std::string_view text) noexcept
Definition Strings.cpp:257
void Add(Subscription subscription)
KHook::IKHook * __exported__khook
Definition Host.cpp:30
static Status ResolveSchema(const IPluginContext &host)
Definition Plugin.cpp:123
static Status Resolve(T *&field, const IPluginContext &host, InterfaceLookup lookup, const char *version)
Definition Plugin.cpp:64
void *(IPluginContext::*)(const char *version) const InterfaceLookup
Definition Plugin.cpp:61
static Result< std::unique_ptr< UnsafeServices > > OpenUnsafe(IPluginContext &host)
Definition Plugin.cpp:76
Subscription HostSubscription(IPluginEvents &events, uint64_t token)
void Info(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:79
void SetHandler(Handler handler)
Definition Logger.cpp:26
void SetMinimumLevel(LogLevel level)
Definition Logger.cpp:37
Status ResolveLayout(std::span< FieldLayout > fields, const LiveFieldLookup &lookup)
Definition Layout.cpp:10
std::span< FieldLayout > GeneratedLayout()
Definition Layout.cpp:137
void SetBaseDir(const std::filesystem::path &baseDir)
Set the base directory for path resolution (the host's csgo directory). Must be called during initial...
Definition Paths.cpp:9
std::expected< void, Error > Status
Definition Result.hpp:67
std::expected< T, Error > Result
Definition Result.hpp:64
LogLevel
Definition Log.hpp:13
static Error Engine(std::string detail)
Definition Result.hpp:58
static Error NotReady(std::string detail)
Definition Result.hpp:50
virtual IPluginGameData * GameData() const =0
virtual IPluginEvents & Events()=0
virtual KHook::IKHook * HookDispatcher() const =0
virtual void * ServerInterface(const char *version) const =0
virtual Schema::LiveField FindSchemaField(std::string_view className, std::string_view field) const =0
virtual void WriteLog(uint8_t level, std::string_view text)=0
virtual std::string_view BaseDir() const =0
virtual uint8_t MinLogLevel() const =0
virtual void * EngineInterface(const char *version) const =0
virtual IPluginLanguages & Languages()=0
virtual uint64_t OnFrame(FrameFn callback, void *context)=0
virtual uint64_t OnConsoleCommand(ConsoleCommandFn callback, void *context)=0
virtual uint64_t OnClientSettingsChanged(ClientSettingsChangedFn callback, void *context)=0
virtual uint64_t OnServerStartup(ServerStartupFn callback, void *context)=0
virtual uint64_t OnClientConnected(ClientConnectedFn callback, void *context)=0
virtual uint64_t OnClientConnecting(ClientConnectingFn callback, void *context)=0
virtual uint64_t OnBuildGameSessionManifest(BuildGameSessionManifestFn callback, void *context)=0
virtual uint64_t OnClientDisconnected(ClientDisconnectedFn callback, void *context)=0
virtual uint64_t OnClientFullyConnected(ClientFullyConnectedFn callback, void *context)=0
virtual uint64_t OnCheckTransmit(CheckTransmitFn callback, void *context)=0