KGX Core

KGX Core

The shared library every KGX addon runs on, and its API.

What it is

KGX Core is the shared library every KGX addon runs on: the addon registry, safe networking, the data layer, staff permissions and access keys, a settings registry, translations with an in-game editor, screens in the world, notifications, the action log and the UI kit. On its own it adds three pages to the Q menu (KGX Core, KGX Access, KGX Translations) and nothing else. KGX addons that need it list it as a required item on the Workshop, so subscribing to one of them subscribes you to Core as well.

Core is a dependency, not a framework: each addon keeps its own ConVars, data files and gameplay and calls KGXCore.* for the plumbing. A public function is never removed or renamed inside a major version; a removal is deprecated for one minor release first.

Install

Subscribe on the Steam Workshop (item 3828103214), or extract the kgx_core folder into garrysmod/addons/. The resulting path must be garrysmod/addons/kgx_core/lua/autorun/_kgx_core.lua. The host installs it; its Lua is sent to joining clients. The leading underscore sorts it ahead of the other KGX autoruns; addons never rely on that and wait for KGXCore.OnReady instead.

If an addon needs a newer Core than the one installed, it is not loaded, the console says which version it needs, and superadmins get a chat line on join. Nothing errors.

The KGX Core page

Q menu > Utilities > KGX > KGX Core.

PartShows or setsWho
InstalledA row per registered addon: name, version, the Core version it needs, and a note when a newer version is on the Workshop or it needs a newer Core. Click a row to open its Workshop page.Everyone
Languagekgx_lang: the server default, your Garry's Mod language, or en, es, de, fr, ru, pt_br. Applies to every KGX addon.Everyone
Themekgx_theme: dark (default), light, or a theme a KGX addon adds (v1.3.3: KGX's Admin Toolbox's eight dark-menu themes), for every KGX window and screen.Everyone
An addon's display rowsv1.3.3: rows an addon adds under Theme for how its own menus look (KGX's Admin Toolbox: Dark menus, brightness, colored text).Everyone
NEW / UPDATE markskgx_tags: show the green and yellow marks on settings until you hover them, and a button to mark them all seen.Everyone
Screen distancekgx_screen_distance: how far away KGX screens are drawn (200 to 2000).Everyone
Server settingsStaff ranks, the default language, the net budget, the update check and screens on / off (below).Superadmin

Also under Utilities > KGX: KGX Access and KGX Translations (below).

!kgx in chat prints the installed KGX addons to your console. Console: kgx_version (client), kgx_check_updates_now and kgx_screen_addons (superadmin).

KGX Access (v1.1.0)

Q menu > Utilities > KGX > KGX Access lists every access key the installed KGX addons declare: what each addon lets you hand out, who has it now, and whether you have it. A key starts at its default (staff only, or everyone) until a superadmin changes it.

Superadmins click a key to open its window: tick Everyone, or tick ranks and add single players (from the players online, or by SteamID64), then Save; Back to the default forgets the change. Staff always have every key, except keys an addon declares as rules staff do not get by themselves (v1.3.1, shown as "Nobody" by default). Keys are saved per addon in data/kgx_core/<addon>/access.json and logged.

Screens (v1.2.0)

KGX addons can show a page in the world: on the entity's own screen (14 monitor models are known, such as the CRT monitors, the LCD and plasma TVs, the billboard and the 1x1 and 2x2 panels; any other model shows it on the front of its box) or on a screen standing beside it (right, left or above, half to three times the size). The HIDE / SHOW button at the bottom right turns a screen off and on for everyone (E on it; staff, or whoever the addon allows). The rest of the page can answer E when the addon wants it to.

Each player gets their own page from the server (what they may see), asked for while the screen is drawn and pushed again when it changes. kgx_screens 0 turns every KGX screen off; kgx_screen_distance is how far away each player draws them. Try it: look at a prop and run kgx_screen_addons (superadmin) to show the installed KGX addons on it; run it again on it to remove it.

The screens came from KGX's Admin Toolbox (its treasury and store screens), which keeps its own for now.

KGX Translations (v1.3.0)

Q menu > Utilities > KGX > KGX Translations shows every phrase of every KGX addon on Core in any language, with search, which addon it belongs to, and how much of the language is translated. Everyone can read it.

Superadmins double-click a phrase to change it (English too; empty puts the addon's own text back), right-click to copy the English or undo an edit, add up to 16 languages of their own (players pick them like the built-in ones), and copy a language as JSON to share or back up. Edits are saved in data/kgx_core/kgx_core/lang_<code>.json (own languages: lang_custom.json), sent to every player at once and on join, and win over the addons' own phrases. A file put there by hand, for a built-in language or one you added, loads when the server starts.

v1.3.3: KGX's Admin Toolbox's phrases are on this page too (pick it under Addon); an edit here wins in the toolbox. With the toolbox installed, its server owner (superadmins while no owner is set) changes phrases. On the first start the toolbox's own older edits and languages move here once (edits already made here win).

Settings

Server ConVarDefaultDoes
kgx_superadmin_only0Only superadmins count as KGX staff; admins and the admin mod's answer are ignored.
kgx_allowed_ranksExtra ranks that count as staff, comma separated (moderator,vip).
kgx_languageenDefault language: en, es, de, fr, ru, pt_br or auto (each player's Garry's Mod language).
kgx_net_budget0KGX net messages one player may send per second across every KGX addon; more are dropped and logged. 0 = no limit.
kgx_check_updates1Check the KGX website for newer versions (a note in the menu, a chat line to superadmins). Nothing is downloaded or installed.
kgx_screens1The KGX addons' screens are drawn and answer E. 0 = none anywhere (v1.2.0).

Player: kgx_lang, kgx_theme, kgx_tags, kgx_screen_distance (v1.2.0).

Who is staff. With an admin mod that supports CAMI (ULX, SAM, sAdmin and others) the privilege KGX Addons decides (admin and up by default). Without one, admins and superadmins are staff, plus the ranks in kgx_allowed_ranks. kgx_superadmin_only overrides everything.

Data and the update check

Every KGX data file lives in garrysmod/data/kgx_core/<addon>/*.json. A write goes to _tmp/ first and its size is checked; the old file moves to _bak/; then the new file moves into place. A crash or a full disk mid-save leaves the old file or the backup, never half a file. A file that does not parse is moved to _broken/ and the last good copy is used.

Update check. The server fetches versions.json from this site 30 seconds after the map loads and every 6 hours, keeps the answer in data/kgx_core/kgx_core/versions.json, and sends it to players for the menu. If outgoing HTTP is blocked on the server the note never appears and nothing else is affected.

For addon developers: getting started

An addon registers once, inside KGXCore.OnReady, and names the lowest Core version it needs. If Core's autorun has not run yet it boots on the KGXCore_Ready hook; a server without Core at all sees one warning on the first tick instead of errors.

-- lua/autorun/my_addon.lua
if SERVER then AddCSLuaFile() end

local function boot()
    local ok = KGXCore.Register({
        id       = "my_addon",        -- a-z, 0-9 and _, starting with a letter
        name     = "My Addon",
        version  = "1.0.0",
        needs    = "1.0.0",           -- lowest Core version
        workshop = "1234567890",      -- Workshop item id (the menu links to it)
    })
    if not ok then return end         -- Core too old, or the id is taken: already warned

    -- settings a superadmin may change from a panel
    local speed = CreateConVar("my_speed", "650", bit.bor(FCVAR_ARCHIVE, FCVAR_REPLICATED), "Speed.", 100, 1500)
    KGXCore.Setting("my_addon", speed, {min = 100, max = 1500, new = "1.0.0"})

    if SERVER then
        KGXCore.Receive("my_addon_go", function(len, ply)
            KGXCore.Action("my_addon", ply, nil, "pressed go")
            KGXCore.NotifyL(ply, "Done, {1}!", NOTIFY_GENERIC, {ply:Nick()})
        end, {rate = 0.5})
    else
        KGXCore.AddPhrases("my_addon", "es", {["Done, {1}!"] = "Listo, {1}!"})
        hook.Add("PopulateToolMenu", "MyAddon_Menu", function()
            spawnmenu.AddToolMenuOption("Utilities", "KGX", "my_addon", "My Addon", "", "", function(panel)
                local check, slider, applyButton = KGXCore.SettingRows(panel, LocalPlayer():IsSuperAdmin())
                slider("my_speed", KGXCore.L("Speed"))
                applyButton()
            end)
        end)
    end
end

if KGXCore then
    KGXCore.OnReady(boot)
else
    -- Core's autorun (_kgx_core.lua) normally runs first; if not, boot when it is ready.
    hook.Add("KGXCore_Ready", "MyAddon_Boot", function() hook.Remove("KGXCore_Ready", "MyAddon_Boot") boot() end)
    timer.Simple(0, function() -- after every autorun has run: Core really is missing
        if KGXCore then return end
        ErrorNoHalt("[My Addon] KGX Core is not installed. Subscribe to it on the Workshop.\n")
        if SERVER then
            hook.Add("PlayerInitialSpawn", "MyAddon_NoCore", function(ply)
                timer.Simple(10, function()
                    if IsValid(ply) and ply:IsSuperAdmin() then
                        ply:ChatPrint("[My Addon] KGX Core is missing; the addon is not loaded.")
                    end
                end)
            end)
        end
    end)
end

Another KGX addon as a dependency: KGXCore.Require("throw_equipped", "1.2.0") is true when it is installed at that version or newer.

API reference

Registry (sh_core.lua)

FunctionRealmDoes
KGXCore.Register(info)sharedinfo = {id, name, version, needs, workshop, author}. Stores the addon in KGXCore.Addons[id], checks needs against KGXCore.Version, prints one console line, runs KGXCore_Registered(row). Returns false (and warns) when Core is too old, the id is invalid or taken by another addon.
KGXCore.Require(id, minVersion)sharedTrue when another KGX addon is registered at minVersion or newer.
KGXCore.OnReady(fn)sharedRuns fn now if Core is loaded, otherwise once KGXCore_Ready fires. Errors in fn are printed, not thrown.
KGXCore.Installed()sharedThe registered addons, sorted by name: {id, name, version, needs, workshop, author}.
KGXCore.VersionBelow(a, b) / VersionAtLeast(have, want) / VersionOK(v)sharedNumeric per part: 1.2.0 < 1.10.0. VersionOK: looks like 1.2.0 (more parts allowed).
KGXCore.Version, KGXCore.Name, KGXCore.Ready, KGXCore.ProblemssharedCore's version string; "KGX Core"; true once loaded; the warnings superadmins get on join.

Networking (sh_net.lua)

FunctionRealmDoes
KGXCore.Receive(name, fn, opts)servernet.Receive with the checks every KGX message gets before fn(len, ply) runs: a valid player, the message under opts.maxBytes (default 64 KB), the player inside kgx_net_budget, opts.rate seconds since their last one of this message, opts.auth(ply) true. Errors in fn are printed with their stack and never stop other messages.
KGXCore.SendPayload(name, target, data)serverdata as compressed JSON to a player, a list, or everyone (nil). Over 65,000 bytes is refused and logged. Add the name with util.AddNetworkString first.
KGXCore.SendPayloadToServer(name, data)clientThe same, upward.
KGXCore.ReadPayload(maxOut) / ReadPayloadText(maxOut)sharedInside a receiver: the table / the JSON text, or nil. maxOut caps what is unpacked (default 1 MB).

Data (sv_data.lua)

FunctionRealmDoes
KGXCore.DataRead(id, file)serverdata/kgx_core/<id>/<file>.json as a table, or nil. A broken file is moved to _broken/ and the _tmp/ or _bak/ copy is used.
KGXCore.DataWrite(id, file, data, pretty)serverWrites it safely (temp, backup, move). Returns true when saved.
KGXCore.DataDelete(id, file)serverRemoves the file and its copies.
KGXCore.DataSaver(id, name, every, fn)serverfn runs every `every` seconds (nil = only at shutdown) and once more at ShutDown. The same name again replaces it.

Permissions (sh_perms.lua)

FunctionRealmDoes
KGXCore.Allowed(ply)sharedStaff: kgx_superadmin_only, else the ranks in kgx_allowed_ranks, else CAMI (privilege KGX Addons), else IsAdmin(). Cached one second per player; KGXCore.AllowedReset(ply) clears it.
KGXCore.Check(admin, target, needPlayer)serverGuard before an action: a valid admin, a real target, and a player when needPlayer is set (the admin is told otherwise).
KGXCore.AccessKey(id, key, opts)sharedv1.1.0. Declares a key for the KGX Access page (both realms). opts: label and help (English), default = "staff" (default) or "everyone", staff = false (v1.3.1: staff do not get it by themselves; its default is then "nobody"; for rule exceptions such as Pickup Equipped's walk-over pickup), new / updated = a version for the NEW / UPDATE mark. Returns the definition.
KGXCore.AccessStaffHas(id, key)sharedv1.3.1. Whether staff get the key automatically (false for keys declared with staff = false).
KGXCore.HasAccess(ply, id, key)sharedStaff always; else the saved key (everyone, the player's rank, or the player's SteamID64), else the key's default.
KGXCore.AccessState(id, key)sharedv1.1.0. "everyone" / "staff" / "some", whether it is the default, and the saved row.
KGXCore.AccessKeysOf(id) / AccessAddons()sharedv1.1.0. One addon's declared keys in order; the addons with keys.
KGXCore.SetAccess(id, key, players, ranks, steamids)serverSets one key (players = everyone; ranks = a list or set; steamids = {[SteamID64] = name}, v1.1.0), saves access.json and sends it to clients (KGXCore_AccessChanged).
KGXCore.ResetAccess(id, key)serverv1.1.0. Back to the key's default.
KGXCore.AllRanks(extra)shareduser, admin, superadmin, the admin mod's groups, the ranks of players online, plus extra; sorted.

Screens (sh_screens.lua, sv_screens.lua, cl_screens.lua)

FunctionRealmDoes
KGXCore.ScreenKind(kind, def)sharedv1.2.0. A kind of screen (both realms). def: id, page = server function(ply, ent) returning that player's page table (or nil), draw = client function(ent, d, ui) (d is nil while it loads), refresh = seconds between asks (default 10), use = server function(ply, ent, u, v) for E on the page, blockUse = E on the page does not also use the entity, mayHide = server function(ply, ent) for the HIDE / SHOW button (default staff).
KGXCore.ScreenSet(ent, kind, opts)serverv1.2.0. Shows it. opts: place = "is" (default) or "beside", side = right / left / above, size = 0.5 to 3, btn (default on), hidden, yaw (a fixed facing for beside screens), title (48 characters).
KGXCore.ScreenClear(ent) / ScreenSetHidden(ent, hidden) / ScreenPush(ent)serverv1.2.0. Removes it; turns it off or on for everyone; sends the page again to the players near it (once a second at most).
KGXCore.ScreenOf(ent) / ScreenGeometry(ent) / ScreenCursor(ent, ply, reach)sharedv1.2.0. The kind it shows; its world position (the middle), angle, width and height; where a player aims on it (u, v from the top left, and the distance).
KGXCore.ScreenUIclientv1.2.0. The helpers given to draw as ui: W (512), H, u, v, colors, font(name), fit(text, font, maxWidth), text(text, font, x, y, color, alignX, alignY), header(title, color), center(lines).
KGXCore.ScreenModels / ScreenModelListsharedv1.2.0. The models with a known screen and the ones offered in pickers; KGXCore.ScreenModelBox / ScreenModelMonitor add more.

Settings (sh_settings.lua)

FunctionRealmDoes
KGXCore.Setting(id, cvar, opts)sharedRegisters a server ConVar a superadmin may change from a panel. opts: kind (bool | number | string; number when min is set, else bool), min, max, decimals, maxLength, pattern, new = "1.2.0", updated = "1.2.0". Only registered ConVars are accepted by the kgx_setcvar / kgx_setnum / kgx_setstr messages.
KGXCore.MarkNew(name, version) / MarkUpdated(name, version)sharedNEW / UPDATE marks for controls that are not ConVars, keyed by any name.
KGXCore.SettingsOf(id)sharedThe registered settings of one addon.

Translations (sh_lang.lua)

FunctionRealmDoes
KGXCore.AddPhrases(id, code, table)sharedAn addon's phrases for one language: {["English"] = "Texto"}. Codes: es, de, fr, ru, pt_br. Its English goes on the KGX Translations page.
KGXCore.AddEnglish(id, list)sharedv1.3.0. English text the addon shows that has no phrase yet, so it is on the KGX Translations page too.
KGXCore.LangEnglish(id) / LangName(code)sharedv1.3.0. One addon's (or every addon's: nil) English phrases, sorted; a language's name, built in or the server's own.
KGXCore.LangSet(code, english, text) / LangSync(target, code)serverv1.3.0. Changes one edit ("" = back to the addon's own) and saves it; sends the edits (everything to a player, or one language to everyone).
KGXCore.L(text, ...)sharedThe text in the player's language with {1}, {2}... filled: the server's edit first (v1.3.0), then the addon's phrase, else the English. On the server it fills the arguments and keeps English.
KGXCore.T(text) / KGXCore.TA(value)sharedT marks English the client translates later; TA marks an argument that is itself English to translate.
KGXCore.NotifyL(ply, text, kind, args)serverA notification in the player's own language (template with {1}..{8}).
KGXCore.ChatL(target, text, args, color, prefix)serverA chat line the same way; target = a player, a list, or nil for everyone; prefix = the [name] in front ("" for none).
KGXCore.LangCurrent() / LangCombo(panel)clientThe language in use; a language combo for a settings page.
KGXCore.AddPhraseTable(id, code, table)clientv1.3.3. For an addon with its own lookup: shows its phrase table on the KGX Translations page without adding it to the shared one (kept by reference). The addon's lookup checks KGXCore.LangOverrides (the edits) first.
KGXCore.CanEditPhrases(ply)sharedv1.3.3. Whether the player may change phrases: what a KGXCore_CanEditPhrases hook answers (true = may, false = may not, and why in English), else superadmins.
KGXCore.LangImport(code, set, name)serverv1.3.3. Adds an addon's older edits ({English = text}) to Core's: edits already in Core win; name adds the language as one of the server's own when it is not built in. Saves once and sends it. Returns how many were added, or false.
KGXCore.ShowPhrases(id)clientv1.3.3. Opens KGX Translations on one addon's phrases (nil = every addon).

Log (sh_log.lua)

FunctionRealmDoes
KGXCore.Notify(ply, text, kind)sharedA HUD notice (bottom right); kind is a NOTIFY_* value. A bot's notices go to ply.KGXCore_NotifyRelay when set.
KGXCore.Action(id, admin, target, text)serverOne log line "[<addon>] <admin> <text>" with {T} = the target; runs KGXCore_Action(id, line, admin, target, text). Returns the line.
KGXCore.Say(id, text)sharedA console line with the addon's name.

UI kit (cl_ui.lua)

FunctionRealmDoes
KGXCore.SettingRows(panel, isSuper)clientReturns check(name, label), slider(name, label), applyButton(label), text(name, label) for a DForm; range and kind come from the registered setting; disabled for non-superadmins.
KGXCore.MarkControl(ctrl, name, label, restore)clientThe control's label goes green (NEW) or yellow (UPDATE) until the mouse has been over it once; kept in data/kgx_core/seen.json.
KGXCore.WindowOnTop(frame)clientA window opened from another window comes up in front and stays usable.
KGXCore.Theme() / ThemeName()clientThe shared colour table (bg, panel, line, text, dim, accent, good, warn, bad) for kgx_theme.
KGXCore.AddTheme(id, label, colors) / ThemeList()clientv1.3.3. A theme for every KGX window: id (letters, digits, _), label (English, or a function giving the addon's own translation), colors (the keys above; left out = Dark's). ThemeList(): {{id, name}, ...} in list order. Adding again replaces it.
KGXCore.AddDisplay(id, fn)clientv1.3.3. fn(panel) adds an addon's rows under Theme on the KGX Core page (how its own menus look). Errors are caught.
KGXCore.OpenPage(item)clientv1.3.3. Opens a Q menu page by its name: kgx_core, kgx_core_access, kgx_core_phrases, or an addon's.

Helpers (sh_util.lua)

FunctionRealmDoes
KGXCore.Money(n, symbol, cents, suffix)shared"$1,234,567", "$1,234.50" with cents, "100 credits" with suffix.
KGXCore.Finite(v) / Clamp(v, low, high) / Cut(text, n) / Upper(text)sharedA number or nil; clamp; cut without breaking UTF-8; upper case that knows Cyrillic and accents.
KGXCore.IsEntity(e) / IsPlayer(e) / Label(e) / LogName(ply) / SafeCall(fn, ...)sharedEntity checks, "prop_physics #12", the Steam name plus the shown name, pcall with the error printed.

Hooks

HookRealmWhen
KGXCore_ReadysharedCore has loaded every file.
KGXCore_Registered(row)sharedAn addon registered.
KGXCore_Action(id, line, admin, target, text)serverAn action was logged (Discord logs, histories).
KGXCore_AccessChanged(id)sharedAn addon's access keys arrived (client) or were changed (server, v1.1.0).
KGXCore_ScreenHidden(ent, hidden, ply)serverv1.2.0. A screen was turned off or on.
KGXCore_ScreenUsed(ent, ply, u, v)serverv1.2.0. E on a screen's page.
KGXCore_ScreenPage(ent, page)clientv1.2.0. A page arrived.
KGXCore_LangChangedclientThe language changed, or the server's edits arrived (v1.3.0).
KGXCore_ThemeChanged(name)clientThe theme changed (v1.3.3: also when the picked theme is added or replaced).
KGXCore_CanEditPhrases(ply)sharedv1.3.3. Return true to let a player change phrases, or false (and why, English) to stop them; nil = superadmins.
KGXCore_PhrasesShow(id)clientv1.3.3. KGXCore.ShowPhrases was called (the open KGX Translations page switches addon).
KGXCore_VersionsChecked(latest, behind)serverversions.json was fetched.
KGXCore_NetOverBudget(ply, line)serverA player went over kgx_net_budget (once a minute per player).

Back to Help

Type to search every tool, panel, setting, FAQ answer and release.