Skip to content

Project architecture

Source baseline: local 2.6.0, dev at 463d21ca (2026-11-14), plus the core engineering audit. Tag 2.5.1 is a7f2d9da; later branch behavior is recorded in version history. This describes the repository, not a promise that Workshop already contains these commits.

Runtime boundaries

Realm Owns Entry points
Server Population, bodies/brains, AI, navigation, damage, wanted/arrest, medics, vehicle providers sv_ files and server branches in sh_
Client Menu, voices/subtitles, ghost visuals, wanted HUD, route/debug rendering cl_ files and client branches in sh_
Shared Classes, configuration, API definitions, serialization and received actor records sh_ files; data is independent in each Lua realm

A shared filename says where a file loads. It does not guarantee a method can drive gameplay on the client. Use the realm references.

Load sequence

lua/autorun/background_npcs.lua sends and includes background_npcs_core/sh_init.lua. The loader sorts files, loads sh_, sv_, then cl_ within each directory, recursively; explicit includes are deduplicated. Replic language files and menu option translations are loaded manually. tests/ is only sent to clients; bgn_selftest / bgn_selftest_cl include it when they run.

  1. Core: notices, classes, networking, utilities, scheduler, then remaining helpers.
  2. Built-in config/actors/phrases/states, custom config, legacy config adapter.
  3. Public API, cvars, commands, custom preload; save config defaults.
  4. Actor class/components/body adapters, events/update/sync.
  5. Navigation base/providers/IO, then the DV provider.
  6. Team and wanted modules, arrest module, remaining systems; brains, spawners, integrations.
  7. Menu languages/UI/debug; custom postload; BGN_PostLoadScripts.

Order matters: offender/state modules capture the registered arrest module. Reloading via bgn_scripts_reload reruns this loader; a map reload is the clean validation for changed bodies and persisted world state.

The shared UID allocator survives script reload; SERVER snapshot sequences use that same monotonic allocator. CLIENT retirement marks the actor removed before pending initialization can register it again. Scheduler ticks visit a snapshot of task IDs, so task removal/replacement cannot invalidate the live iteration. Long-lived services own their repeat loops; returning from a task finishes it. See audit contracts and limits.

Files and responsibilities

All paths below are relative to the repository root. Under lua/background_npcs_core/:

Path Responsibility / connections
sh_init.lua Version, shared storage, deterministic loading.
core/ Class factory, task budget, network codec/chunks, cvar/command infrastructure, self-test runner (bgNPC.Test), notices, utility helpers.
config/ Main settings; actors/ defaults and inheritance; states/ dialogue/scenic/arrest data; replics/language/ text and voice definitions.
custom_modules/config, preload, postload Extension stages, also discoverable from separate addons through merged GMod Lua paths.
api/ Actors/config/points/states/modes/vision/statistics/assertions and combat facade. compat/sh_legacy.lua retains old colon APIs.
cvars/, commands/ Setting registration, defaults and administrative actions.
actor/sh_actor.lua, components/ Character identity/health/lifetime and partial state, enemy, target, team, movement, weapon, animation, speech and vehicle methods.
actor/body/ Server NPC/NextBot engine adapters.
actor/update, events, sync Scheduled simulation, damage/death/save hooks, server snapshots and client binding.
nav/ Provider facade, graph/A*, custom/navmesh/nodegraph providers; generator/ incremental route building, io/ editor/save/compile/dupes, legacy/ conversion.
brain/fsm/, brain/goap/ State execution and combat planning. States call Actor methods; bodies perform engine actions.
spawner/ Visibility-safe population placement/recycling, separate vehicle ranges, pursuit reinforcement and cleanup.
systems/ Wanted/arrest, offenders, medics/corpses, teams/enemy sharing, gang wars/support/packs and combat cooldown, dialogue, seats, scenic, ghost crowd, modes.
modules/ Optional integrations: DV, DarkRP, StormFox and NPC mods. dv/ owns provider access, traffic recovery, pedestrian detours, return and vehicle damage.
ui/ Settings window, Classic panels, wizard/welcome, spawnmenu, update display, translations.
debug/ Admin UID subscriptions and bounded decision/sight/signal journal (SERVER); cached mesh/HUD, camera and scene/hand markers (CLIENT); diagnostics and automated checks.
tests/ Self-tests of pure logic, split by realm prefix (sh_, sv_, cl_). Not loaded with the addon: bgNPC.Test.Run includes them on each bgn_selftest (SERVER) / bgn_selftest_cl (CLIENT) run, so edited tests run without a map change. A test reads only public fields; a helper a test needs is exposed on its module with a read by tests/ comment.

Other repository paths:

Path Contents
lua/entities/ NextBot actor and DV-related scripted entities/controllers; inspect each entity's init/shared/client files for realm.
lua/weapons/ Tools, including route editing support.
lua/autorun/ Addon bootstrap.
lua/ulx/ Optional ULX administrative integration.
materials/, models/, sound/, resource/ Runtime visuals, gang models/skins, voice assets and UI localization.
tools/ Python regression checks, opt-in DV lab fixtures/bridge client, asset/voice generation helpers; not loaded automatically by the game.
docs/, mkdocs.yml, requirements-docs.txt EN/RU site sources, navigation/translations, pinned documentation dependencies.
.github/ CI/site deployment configuration.
addon.json, version.txt, LICENSE, README.md Addon metadata, release number, license and entry page.
site/ Ignored generated documentation; never edit by hand.
quarantine/ Retained files outside the active loader; not an extension entry point.

Local planning/lab notes are not release contracts. Do not copy machine-specific paths or temporary bridge setup into runtime installation instructions.

On the first player spawn spawner/sv_pre_spawn_cache.lua warms resources: it creates and removes every configured NPC class/model and vehicle once. NextBot relationship sampling uses player dispositions without creating probe entities; see brains.

Main relationships

config -> resolved Config cache -> per-actor config copy
navigation + player visibility -> spawner -> Actor registry
Actor -> brain (FSM / GOAP) -> state callbacks -> Actor methods -> body -> engine entity
systems/events -> reactions / wanted / arrest / medic calls -> state transitions
Actor <-> vehicle provider -> DV controller + chassis + seated visual
server Actor -> PVS snapshots + generation -> client registry -> UI / sound / rendering

The actor and UID survive vehicle boarding; its entity and body adapter do not. Registries, enemy/target references, wanted state and statistics follow the replacement. Addons must follow BGN_ActorEntityChanged(actor, old, new) for their own entity-local data. SERVER sends a player the snapshot identity only on first PVS sight or rebind, then only changed state, at most 8 snapshots per tick; a sequence number keeps a delayed identity packet from overwriting newer state on the CLIENT.

Door shelter is server-owned (systems/sv_door_hold.lua, brain/fsm/states/sv_hold_door.lua); GOAP chooses the action. Temporary knocked_down keeps the original entity and body adapter, hides/freezes them and uses a server ragdoll for physics and forwarded damage. The actor update loop runs only recovery while down; standing requires a free hull. Client synchronization/render optimization preserves the server's hidden-body flag.

systems/siege/ owns bounded NavMesh pocket detection, shared entrance reservations, siege positioning and special weapons on SERVER. GOAP selects siege; brain/fsm/states/sv_siege.lua executes its phases on both body types. Existing donor animations prevent native NPC throw/deploy events from producing duplicate weapons. Clients receive the ordinary state/animation updates. See room sieges.

systems/sh_carry_items.lua shares item definitions, model/animation checks and chance selection. SERVER owns real actors' item lifetime; body adapters exclude carried props from combat weapon queries. Only NextBot activity tables supply carrying locomotion. HL2 NPC movement is unchanged; CLIENT attaches briefcases to the hand bone on both body types; they never spawn physical drops. systems/cl_carry_items.lua manages real actors' client props from carry_visual in existing PVS snapshots. The newspaper hides the NextBot's driving parcel and fits the stock paper model between both hand bones. CLIENT also owns ghost visuals. Ghosts and actors materialized from them never carry items. Scenic placement remains SERVER-owned, including room/ledge traces, furniture bounds and atomic couch pairs.

debug/sv_scenic.lua owns admin scene placement, test ownership/Undo and the one-cycle GOAP door test. lua/weapons/gmod_tool/stools/bgn_scenic_debug.lua supplies the selector and live inspection HUD through the existing server-to-client Tool RPC. Manual placement validates the admin owner in both creation and delayed setup; only that path bypasses hidden-position checks. Normal spawner model hooks still decide all actor models.

Configuration and stored data

systems/sv_lethal_weapons.lua owns the SERVER-only learned weapon cache and optional one-second perception timer. background_npcs/lethal_weapons.json is read once per server/map start; script reloads reuse the cache, and only a newly learned class rewrites the full file. See held weapons.

Cvar defaults are defined in cvars/sh_cvars.lua, sv_cvars.lua, cl_cvars.lua; registration and permissions are in core/sh_cvars.lua. Server settings are admin-controlled; client voice/UI options stay local. Actor definitions resolve inherit and @type references, cache the result and copy it on creation. After editing definitions, clear the config cache; existing actors retain their copy.

ui/spawnmenu/sv_spawnmenu.lua loads custom.dat at initialization/reload, rather than on entity creation, and clears the resolved config cache after mapping changes. Player spawns from the menu and Actor spawner Tool pass an optional owner to the common spawner: PlayerSpawnNPC can veto before creation, and PlayerSpawnedNPC provides gamemode accounting after actor creation. Automatic population passes no owner. Network framing and client upload limits are described in the audit.

GMod DATA paths are relative to garrysmod/data/, not this addon: background_npcs/nodes, graph, seats, compile (created by bootstrap), diagnostic background_npcs/test_report.txt. DV waypoints are separate from pedestrian routes. Preserve users' route files; legacy import/duplication conversion must not overwrite unrelated points. Compiled routes are Lua distribution artifacts generated from stored data.

Development and verification

Unit/stub checks do not establish real GMod physics, multiplayer permission behavior or every optional-addon combination. Record exact conditions for live evidence.

Combat damage authority: systems/sv_first_attacker_found.lua receives confirmed engine/seated damage, records the pair initiator, evaluates existing-arrest harm and emits BGN_ConfirmedDamage for arrest initiation and witnesses. systems/arrest/sv_arrest.lua checks primary-officer compliance every 0.25 seconds. These records are SERVER-only; see wanted.

Damage entry points resolve siege payload ownership through Combat.ResolveVehicleAttacker(attacker, inflictor) before team/protection/reaction checks, independently of native damage-hook order. Actor search age comes from observed/shared timestamps, not NPC engine pursuit writes. Actors.Rebind transfers position/time and combat/recent-attacker references before updating the body's enemy. Siege entry excludes negotiation's hold_fire actors. See the combat continuation tree.