12#include <engine2/igameeventsystem.h>
13#include <engine2/isource2server.h>
14#include <engine2/ivengineserver2.h>
18#include <interfaces/interfaces.h>
20#include <networksystem/inetworkmessages.h>
21#include <schemasystem/schemasystem.h>
24#include <tier0/convar.h>
38 const bool loaded = AttachImpl(host, error, errorSize);
45 catch (
const std::exception& exception)
66 field =
static_cast<T*
>((host.*lookup)(version));
69 return std::unexpected(
Error::NotReady(std::format(
"Could not find interface: {}", version)));
78 auto unsafe = std::make_unique<UnsafeServices>();
79 auto& gi = unsafe->Interfaces;
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),
95 for (
const Status& status : resolved)
99 return std::unexpected(status.error());
106 g_pGameResourceServiceServer = gi.GameResourceService;
107 ConVar_Register(FCVAR_RELEASE | FCVAR_CLIENT_CAN_EXECUTE | FCVAR_SERVER_CAN_EXECUTE | FCVAR_GAMEDLL);
112 unsafe->GameData = unsafe->Bindings.Bind(
113 [gameData](
GameDataSection sections, std::string_view name) {
return gameData->Lookup(sections, name); });
117 unsafe->GameData = std::unexpected(
Error::Engine(
"the host has no gamedata"));
127 [&host](std::string_view className, std::string_view field) {
return host.
FindSchemaField(className, field); });
130bool PluginModule::AttachImpl(
IPluginContext& host,
char* error,
size_t errorSize)
138 [&host](
LogLevel level, std::string_view message) { host.
WriteLog(
static_cast<uint8_t
>(level), message); });
143 return Refuse(std::format(
"SchemaLayout: {}", schema.error().Detail), error, errorSize);
149 return Refuse(unsafe.error().Detail, error, errorSize);
151 _unsafe = std::move(*unsafe);
152 _languages = std::make_unique<HostPlayerLanguages>(host.
Languages());
153 _runtime = std::make_unique<Runtime>(host, *_unsafe, *_languages);
156 _plugin = _factory(*_runtime);
157 if (std::string reason = _runtime->LoadReport.AbortReason(); !reason.empty())
159 return Refuse(reason, error, errorSize);
162 SubscribeHostEvents();
164 if (!_plugin->Load())
166 std::string reason = _runtime->LoadReport.AbortReason();
167 return Refuse(reason.empty() ?
"Load returned false" : reason, error, errorSize);
170 Log::Info(
"{}", _runtime->LoadReport.Summary());
174bool PluginModule::Refuse(std::string_view reason,
char* error,
size_t errorSize)
178 Log::Info(
"{}", _runtime->LoadReport.Summary());
192void PluginModule::Shutdown() noexcept
196 _runtime->Commands.RemoveAll();
209 _status = _runtime ? _runtime->Status.BuildJson() : std::string(
"{}");
210 return _status.c_str();
218void PluginModule::SubscribeHostEvents()
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));
230 keep(events.
OnConsoleCommand(&HostCallback<&PluginModule::OnConsoleCommand>::Call,
this));
231 keep(events.
OnCheckTransmit(&HostCallback<&PluginModule::OnCheckTransmit>::Call,
this));
235void PluginModule::OnFrame()
239 _runtime->OnGameFrame();
242void PluginModule::OnServerStartup(std::string_view mapName)
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);
252bool PluginModule::OnClientConnecting(
int slot, int64_t steamId, std::string_view name,
char* reason,
size_t reasonSize)
254 ConnectRequest request{.Slot = slot, .SteamId = steamId, .Name = name};
255 _runtime->Players.Connecting.Raise(request);
256 if (request.Rejected)
260 return request.Rejected;
263void PluginModule::OnClientConnected(
int slot, int64_t steamId, std::string_view name, std::string_view address)
265 _runtime->Players.Add(slot, steamId, std::string(name), std::string(address));
268void PluginModule::OnClientDisconnected(
int slot)
270 _runtime->Players.Remove(slot);
273void PluginModule::OnClientFullyConnected(
int slot)
275 _runtime->Players.OnClientFullyConnected(slot);
278void PluginModule::OnClientSettingsChanged(
int slot)
280 _runtime->Players.OnClientSettingsChanged(slot);
283void PluginModule::OnCheckTransmit(CCheckTransmitInfo** infoList,
int infoCount)
285 _runtime->Visibility.OnCheckTransmit(infoList, infoCount);
288void PluginModule::OnBuildGameSessionManifest(IEntityResourceManifest* manifest)
290 _runtime->Precache.WriteTo(*manifest);
const char * StatusJson() noexcept
bool Attach(IPluginContext &host, char *error, size_t errorSize) noexcept
static void CopyToBuffer(char *buffer, std::size_t size, std::string_view text) noexcept
void Add(Subscription subscription)
KHook::IKHook * __exported__khook
static Status ResolveSchema(const IPluginContext &host)
static Status Resolve(T *&field, const IPluginContext &host, InterfaceLookup lookup, const char *version)
void *(IPluginContext::*)(const char *version) const InterfaceLookup
static Result< std::unique_ptr< UnsafeServices > > OpenUnsafe(IPluginContext &host)
Subscription HostSubscription(IPluginEvents &events, uint64_t token)
void Info(std::format_string< Args... > fmt, Args &&... args)
void SetHandler(Handler handler)
void SetMinimumLevel(LogLevel level)
Status ResolveLayout(std::span< FieldLayout > fields, const LiveFieldLookup &lookup)
std::span< FieldLayout > GeneratedLayout()
void SetBaseDir(const std::filesystem::path &baseDir)
Set the base directory for path resolution (the host's csgo directory). Must be called during initial...
std::expected< void, Error > Status
std::expected< T, Error > Result
static Error Engine(std::string detail)
static Error NotReady(std::string detail)
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