ISource2ModConfigs

JSON config files a plugin declares once and reads already merged.

A plugin names its configs and gives each one its defaults as JSON text (comments allowed). Source2Mod then owns the files:

addons/source2mod/configs/<plugin>/
  <name>.example.json   the defaults, verbatim; rewritten whenever they change
  <name>.json           the admin's file; created from the defaults when missing

What the plugin reads is the admin's file merged over the defaults: a key the admin's file lacks (a setting added in a newer plugin version) comes from the defaults, a value of the wrong type is reported and replaced by the default, and everything the admin wrote stays as written. So every key the defaults have is always there, and the plugin needs no fallback values of its own.

The usual shape: the plugin class derives from ISource2ModConfigListener next to ISource2ModPlugin / ISource2ModListener, declares its configs in OnDeclareConfigs() and copies the values it needs in OnConfigChanged():

bool MyPlugin::Load(ISource2ModAPI* api, char* error, size_t maxlen, bool late)
{
    SOURCE2MOD_SAVEVARS();
    if (!g_pSource2ModConfigs || !g_pSource2ModConfigs->AddListener(this, error, maxlen))
        return false;
    ...
}

void MyPlugin::OnDeclareConfigs(ISource2ModConfigDeclarations* configs)
{
    configs->Add("config", R"json({ "Prefix": "[MY]", "Enabled": true })json");
}

void MyPlugin::OnConfigChanged(ISource2ModConfig* config, ConfigChange reason)
{
    m_bEnabled = config->Root()->GetBool("Enabled");
}

The defaults can also be built key by key (Source2ModConfigDefaults below) instead of written as one JSON text.

Everything here runs on the game thread.

Interface id ISource2ModConfigs003 (SOURCE2MOD_CONFIGS_INTERFACE) · Global g_pSource2ModConfigs · Header source2mod/ISource2ModConfigs.h

Types

PluginId

using PluginId = int;

Methods

AddListener

virtual bool AddListener(ISource2ModConfigListener* listener, char* error, size_t maxlen) = 0;

Hooks a plugin's config listener up and reads its configs.

Calls OnDeclareConfigs(), then for every declared config writes the example, creates <name>.json when it is missing, reads and merges it, asks OnConfigValidate() and calls OnConfigChanged(ConfigChange::Loaded) -- all before it returns, so Load() can use the values right after.

ParameterTypeDescription
listenerISource2ModConfigListener*Usually the plugin object itself; its plugin owns the configs.
errorchar*
maxlensize_t

Returns bool — False with the reason when a declaration is broken (name, defaults, a duplicate), a REQUIRED file does not parse or OnConfigValidate() refused the first read.

RemoveListener

virtual void RemoveListener(ISource2ModConfigListener* listener) = 0;

Optional; the unload drops it anyway. The configs stay readable.

ParameterType
listenerISource2ModConfigListener*

Register

virtual ISource2ModConfig* Register(const char* pszName, const char* pszDefaults, uint32_t nFlags, ISource2ModConfigListener* listener, char* error, size_t maxlen) = 0;

A config outside the declaration step, e.g. one per map.

Same file handling as a declared one. The listener may be null; when set, it gets OnConfigValidate / OnConfigChanged for this config only (OnConfigChanged(Loaded) before Register returns).

ParameterType
pszNameconst char*
pszDefaultsconst char*
nFlagsuint32_t
listenerISource2ModConfigListener*
errorchar*
maxlensize_t

Returns ISource2ModConfig* — The config, or null with the reason (as AddListener()).

Unregister

virtual void Unregister(ISource2ModConfig* config) = 0;

Forgets a config (the files stay). The handle is gone afterwards.

ParameterType
configISource2ModConfig*

Get

virtual ISource2ModConfig* Get(const char* pszName) = 0;

A config by owner and name, this plugin's or another one's (plugin ids as OnPluginLoad reports them); null when there is none.

ParameterType
pszNameconst char*

ISource2ModConfigDeclarations

Handed to ISource2ModConfigListener::OnDeclareConfigs(); valid only during that call.

Add

virtual void Add(const char* pszName, const char* pszDefaults, uint32_t nFlags = SOURCE2MOD_CONFIG_DEFAULT) = 0;

Declares one config of this plugin.

ParameterTypeDefaultDescription
pszNameconst char*File stem under configs/<plugin>/: letters, digits, '_', '-', '.' and '/' for a subfolder; no "..", no extension. "config" is configs/<plugin>/config.json.
pszDefaultsconst char*The defaults as JSON text, comments allowed; the root must be an object. Copied.
nFlagsuint32_tSOURCE2MOD_CONFIG_DEFAULTSOURCE2MOD_CONFIG_* flags.

ISource2ModConfigListener

A plugin's view of its configs. Derive the plugin class from it; every method is optional.

OnDeclareConfigs

virtual void OnDeclareConfigs(ISource2ModConfigDeclarations* configs);

Which configs the plugin has. Called once, from AddListener().

ParameterType
configsISource2ModConfigDeclarations*

OnConfigValidate

virtual bool OnConfigValidate(ISource2ModConfig* config, const ISource2ModJSONValue* root, char* error, size_t maxlen);

Checks a freshly read file before it goes live.

ParameterTypeDescription
configISource2ModConfig*
rootconst ISource2ModJSONValue*The new document, already merged with the defaults.
errorchar*
maxlensize_t

Returns bool — False to refuse it, with the reason in error: a reload keeps the previous document, the first read fails AddListener().

OnConfigChanged

virtual void OnConfigChanged(ISource2ModConfig* config, ConfigChange reason);

A new document is live; config->GetName() says which one.

Copy what you need into your own variables here: the nodes of the previous document are gone after the next frame.

ParameterType
configISource2ModConfig*
reasonConfigChange

ISource2ModConfig

One config file. Owned by Source2Mod; valid until Unregister() or the owning plugin's unload.

Nodes reached through Root(), Defaults() and Find() belong to the current generation. A reload or a Set*() makes a new one; the old nodes stay readable until the next frame, then are freed -- never keep them past the callback that read them.

GetName

virtual const char* GetName() const = 0;

The name it was declared with ("config", "maps/de_dust2", ...).

GetPath

virtual const char* GetPath() const = 0;

Absolute path of <name>.json.

Root

virtual const ISource2ModJSONValue* Root() const = 0;

The admin's file merged over the defaults (the file alone with SOURCE2MOD_CONFIG_NO_MERGE). Never null.

Defaults

virtual const ISource2ModJSONValue* Defaults() const = 0;

The defaults as declared. Never null.

Find

virtual const ISource2ModJSONValue* Find(const char* pszPointer) const = 0;

The node at a JSON pointer into Root() ("/Api/Url"); null when absent.

ParameterType
pszPointerconst char*

GetGeneration

virtual uint32_t GetGeneration() const = 0;

Bumped by every reload and Set*().

GetLastError

virtual const char* GetLastError() const = 0;

What the last read reported: the parse error, wrong-typed values, ... Empty when it was clean.

SetString

virtual bool SetString(const char* pszPointer, const char* pszValue) = 0;

Changes a value in memory; Save() writes it out.

Objects on the way are created. False when the pointer is malformed or runs through something that is not an object. OnConfigChanged() is not called: the plugin made the change itself.

ParameterType
pszPointerconst char*
pszValueconst char*

SetInt64

virtual bool SetInt64(const char* pszPointer, int64_t nValue) = 0;
ParameterType
pszPointerconst char*
nValueint64_t

SetDouble

virtual bool SetDouble(const char* pszPointer, double flValue) = 0;
ParameterType
pszPointerconst char*
flValuedouble

SetBool

virtual bool SetBool(const char* pszPointer, bool bValue) = 0;
ParameterType
pszPointerconst char*
bValuebool

SetJSON

virtual bool SetJSON(const char* pszPointer, const char* pszJson) = 0;

Any JSON value given as text: an object, an array, null.

ParameterType
pszPointerconst char*
pszJsonconst char*

Remove

virtual bool Remove(const char* pszPointer) = 0;
ParameterType
pszPointerconst char*

Save

virtual bool Save(char* error, size_t maxlen) = 0;

Writes the current document to <name>.json.

The previous file is kept as <name>.json.bak. The admin's comments do not survive the rewrite. Does not trigger a reload.

ParameterType
errorchar*
maxlensize_t

Reload

virtual bool Reload(char* error, size_t maxlen) = 0;

Reads the file again now; OnConfigChanged(ConfigChange::Reload) when it went live. False with the reason when it did not (the old one stays).

ParameterType
errorchar*
maxlensize_t

Source2ModConfigDefaults

Config defaults built key by key instead of written as JSON text.

Header-only: it only produces the text Add() / Register() take. A key is a plain member name ("RelayControl") or a JSON pointer into nested objects ("/Feature/Enabled"), whose objects are created on the way; keys keep the order they were added in, and adding one again replaces its value. An optional comment goes into the generated text above the key, so it shows in <name>.example.json and the first <name>.json.

Source2ModConfigDefaults defaults;
defaults.Add("RelayControl", "127.0.0.1:27100")
        .Add("RelayTimeoutMs", 300, "milliseconds")
        .Add("/Feature/Enabled", true)
        .AddJSON("Admins", "[]");
configs->Add("config", defaults.Json());

Add

Source2ModConfigDefaults& Add(const char* key, const char* value, const char* comment = nullptr);
Source2ModConfigDefaults& Add(const char* key, const std::string& value, const char* comment = nullptr);
Source2ModConfigDefaults& Add(const char* key, bool value, const char* comment = nullptr);
Source2ModConfigDefaults& Add(const char* key, int value, const char* comment = nullptr);
Source2ModConfigDefaults& Add(const char* key, int64_t value, const char* comment = nullptr);
Source2ModConfigDefaults& Add(const char* key, double value, const char* comment = nullptr);
Source2ModConfigDefaults& Add(const char* key, float value, const char* comment = nullptr);
ParameterTypeDefault
keyconst char*
valueconst char*
commentconst char*nullptr
valueconst std::string&
valuebool
valueint
valueint64_t
valuedouble
valuefloat

AddJSON

Source2ModConfigDefaults& AddJSON(const char* key, const char* json, const char* comment = nullptr);

Any JSON value as text: an array, an object, null. Invalid text makes the whole defaults invalid, which Add() / Register() report.

ParameterTypeDefault
keyconst char*
jsonconst char*
commentconst char*nullptr

Json

const char* Json();

The defaults as JSON text, comments included.

Enums

ConfigChange

enum class ConfigChange

Why OnConfigChanged() was called.

NameDescription
LoadedThe first read, from AddListener() / Register().
FileChangedThe file changed on disk.
Command"s2m config reload".
ReloadISource2ModConfig::Reload().

Macros

PLUGIN_CONFIG

#define PLUGIN_CONFIG(name) g_pSource2ModConfigs->Get(name)

This plugin's config by name.

On this page