BF2.US bf2-rsdeveloper wiki Parity Discord bf2.us
On this page

The Python layer

Game rules that change often (scoring, game modes, ranks, admin tools) are Python 2.3 scripts the server runs. The engine gives them one module, host; everything else is plain Python. This page explains the life of those scripts; the API reference lists every function.

BF22142Heroes

Who runs Python#

Only the machine that hosts the game: the dedicated server, or a client that hosts a local game. A joining client never runs game scripts. bf2-rs embeds the same CPython 2.3.4 the games shipped (built from source with the original configuration, crates/bf2-python), so the shipped scripts run unchanged; the host module is written in Rust (crates/bf2-server/src/hostfns.rs, players_host.rs, crates/bfh-server for Heroes).

Start-up and life cycle#

1 init sys.path script import bf2 bf2.init_module() 2 admin import default init() update() shutdown() 3 game mode game.gamemodes.gpm_cq init() at level load deinit() at unload 4 every frame admin update() due timers: onTrigger() triggers: enter / leave + events as they happen 5 shutdown admin shutdown() clear handlers Py_Finalize()
The server's Python life cycle (PythonHost::init, loadAdmin, loadGameMode, update, shutdown).
  1. init (PythonHost::init, bf2_w32ded.exe!0x0042c450): Py_Initialize without site, then exactly this script sets the module path (bf2-rs: bf2_python::pythonhost::sys_path_script): python import sys sys.path = [ 'pylib-2.3.4.zip', 'python' , 'mods/<mod>/python' , 'mods/bf2/python' , 'admin' ] The <mod> entry is left out for the base mod. Then the engine creates host, imports the bf2 package (python/bf2/__init__.py), reads bf2.playerConvFunc and calls bf2.init_module(), which loads scoring and stats.
  2. admin (loadAdmin): sv.adminScript (BF2 ships "default") is imported from admin/; it must define init, update and shutdown. init() runs once; update() every frame.
  3. game mode (loadGameMode, at level load): game.gamemodes.<mode> (for example gpm_cq conquest); the name must be [a-z0-9_], and an unknown mode falls back to gpm_cq. Its init() runs, deinit() at unload.
  4. every frame (PythonHost::update): admin update(), then due timers and triggers, unless the game is paused. Events are delivered as they happen.
  5. shutdown: admin shutdown(), handlers, timers and triggers cleared, Py_Finalize(). The console command pythonHost.reinitialize runs shutdown + init + game mode + admin again (handy while editing scripts).

Events: host.registerHandler#

Almost everything a script does is a reaction to an event:

a conquest-style handler
import host

def init():
    host.registerHandler('PlayerKilled', onPlayerKilled)
    host.registerHandler('ControlPointChangedOwner', onCPStatusChange)

def onPlayerKilled(victim, attacker, weapon, assists, obj):
    if attacker is not None and attacker != victim:
        host.rcon_invoke('game.sayAll "%s got %s"' % (attacker.getName(), victim.getName()))

def onCPStatusChange(cp, top):
    pass

The signatures are the shipped scripts' own (BF2 Admin/standard_admin/tk_punish.py, gpm_coop.py). Heroes passes one more argument to PlayerKilled: onPlayerKilledCdm(victim, attacker, attackerActiveAbility, weapon, assists, object) in gpm_cdm.py.

  • The name must match the game's event table exactly (case sensitive); a name the game does not have is silently never raised. The events page shows each event's id per game and the handler signature the shipped scripts use.
  • Handlers run in registration order. The third argument alwaysTrigger (default 0) decides whether the handler also runs while the round is not in its playing state.
  • Exceptions in handlers are cleared and never logged in the original engine. If a handler seems not to run, wrap its body in try/except and print the traceback.
  • registerGameStatusHandler(fn) gets fn(status) for game status changes (pre-game, playing, end game, paused).

Players and objects#

Players are not engine objects: they are bf2.PlayerManager.Player instances created by bf2.playerConvFunc(index). Their attributes go through host.pmgr_p_get(attr, index) / pmgr_p_set (team, kit, vehicle, alive, name, ...) and scores through pmgr_getScore / pmgr_setScore.

Engine objects (vehicles, control points, kits, weapons) arrive as host.Object wrappers. The wrapper of an object is always the same Python instance, so == works; isValid() tells whether the engine object still exists (calling anything else on a deleted object raises). Methods are bound per kind: every object has position / rotation / children / getTemplateProperty; armored ones have damage; vehicles have occupants and team; control points have cp_getParam / cp_setParam. See host.Object.

Timers and triggers#

using python/bf2/Timer.py: Timer(targetFunc, delta, alwaysTrigger, data=None)
import bf2.Timer
def tick(data):
    pass
t = bf2.Timer.Timer(tick, 10, 1)   # first call in 10 s, then ...
t.setRecurring(5)                  # ... every 5 s; t.destroy() stops it

bf2.Timer registers itself with host.timer_created; each frame the engine calls onTrigger() on due timers and reschedules them by interval from now (not from the due time). A one-shot timer that comes due while the game is not playing is dropped without firing unless it is alwaysTrigger.

Triggers (host.trig_create(object, callback, name, radius, ...)) call callback(triggerId, sourceObject, object, entered[, data]) when objects enter or leave a sphere around an object; control points use them.

Output and errors#

print goes to bf2.fake_stream, which hands text to host.log; in the original engine that text only reaches a log while an error is being formatted, so plain print output is invisible on a retail server. bf2-rs keeps that behaviour by default; its server log shows Python tracebacks.

The three games#

BF22142Heroes
host functions536975
host.Object methods161824
Events426486
Main additions-squads, Titan parts, EMP, unlocks, rank / disconnect replies, player positionsXP, prestige, ELO, hero data (pmgr_p_getXData), abilities, CTF, daily missions, war-room stats

The 2142 and Heroes servers use the same mechanism with their own tables; bf2-rs picks the table by game (bf2_python::pythonhost::host_functions) and Heroes registers its own (bfh_server::tables).

Where to look in the code#

WhatWhere
Tables (names, order, events)crates/bf2-python/src/pythonhost.rs, crates/bfh-server/src/tables.rs
Handlers, timers, triggerscrates/bf2-python/src/host_state.rs
Host functionscrates/bf2-server/src/hostfns.rs, hostfns_2142.rs, players_host.rs, crates/bfh-server/src/lib.rs
The interpreter buildcrates/bf2-python/build.rs, cpython/
Every fact about the originalnotes/subsystems/python.md, notes/subsystems/python-usage.md, re/data/python_host_api.tsv

How it is tested#

  • The game's own scripts start as in the original (crates/bf2-python/tests/retail_startup.rs): the shipped admin and game mode scripts are run the way the host runs them at server start.
  • The interpreter's compiler (compile_corpus.rs): all 992 modules of the Python 2.3.4 library and the 29 scripts the game runs compile to the same bytecode as the original's.
  • The host's state (host_state.rs): handlers, timers and triggers with the original's semantics; the C runtime's math on hand-picked cases with the original's result bits.
  • A mod's scripts first (crates/bf2-server/tests/mod_python_native.rs): a mod path puts the mod's Python before Battlefield 2's.

In play, the game rules rig runs the same scripts on the port and on the original server and compares scores and tickets.

Source: docs/dev/python/guide.md · built from bf2-rs e3b4f05 · part of the Battlefield 2 / 2142 / Heroes reimplementation. Not affiliated with EA or DICE.