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.
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#
- init (
PythonHost::init,bf2_w32ded.exe!0x0042c450):Py_Initializewithoutsite, 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 createshost, imports thebf2package (python/bf2/__init__.py), readsbf2.playerConvFuncand callsbf2.init_module(), which loads scoring and stats. - admin (
loadAdmin):sv.adminScript(BF2 ships"default") is imported fromadmin/; it must defineinit,updateandshutdown.init()runs once;update()every frame. - game mode (
loadGameMode, at level load):game.gamemodes.<mode>(for examplegpm_cqconquest); the name must be[a-z0-9_], and an unknown mode falls back togpm_cq. Itsinit()runs,deinit()at unload. - every frame (
PythonHost::update): adminupdate(), then due timers and triggers, unless the game is paused. Events are delivered as they happen. - shutdown: admin
shutdown(), handlers, timers and triggers cleared,Py_Finalize(). The console commandpythonHost.reinitializeruns shutdown + init + game mode + admin again (handy while editing scripts).
Events: host.registerHandler#
Almost everything a script does is a reaction to an event:
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):
passThe 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/exceptand print the traceback. registerGameStatusHandler(fn)getsfn(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#
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 itbf2.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#
| BF2 | 2142 | Heroes | |
|---|---|---|---|
host functions | 53 | 69 | 75 |
host.Object methods | 16 | 18 | 24 |
| Events | 42 | 64 | 86 |
| Main additions | - | squads, Titan parts, EMP, unlocks, rank / disconnect replies, player positions | XP, 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#
| What | Where |
|---|---|
| Tables (names, order, events) | crates/bf2-python/src/pythonhost.rs, crates/bfh-server/src/tables.rs |
| Handlers, timers, triggers | crates/bf2-python/src/host_state.rs |
| Host functions | crates/bf2-server/src/hostfns.rs, hostfns_2142.rs, players_host.rs, crates/bfh-server/src/lib.rs |
| The interpreter build | crates/bf2-python/build.rs, cpython/ |
| Every fact about the original | notes/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.
docs/dev/python/guide.md · built from bf2-rs e3b4f05 · part of the Battlefield 2 / 2142 / Heroes reimplementation. Not affiliated with EA or DICE.