Object Reference

From BF2 Technical Information Wiki
Revision as of 23:00, 9 September 2017 by UTurista (talk | contribs) (Creating page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Python program interact with Battlefield 2 using "objects", as well as "methods" (functions) and "attributes" (data) that are part of those objects. This section is a reference to the objects, methods, and attributes in BF2 that can be accessed and manipulated by Python programs.

host

The host object encapsulates the interfaces between the main BF2 engine (written in C++) and Python modules. Most host methods will generally not need to be used directly from within Python modules, as standard BF2 Python modules (like bf2.GameLogic, for example) provide object-oriented wrappers around most of the raw BF2 engine functions.

You must import host to access the methods and attributes shown here.

Event Handler Methods

host.registerHandler('EventName', eventHandler[, alwaysCall])
Registers a function to handle an event. If alwaysCall is not specified the handler will only be called when the game is in the "Playing" state--not in the "Pregame" and "Postgame" states. If you would like it to run in Pregame and Postgame as well, alwaysCall must be specified and evaluate as true (e.g. "1").
host.registerGameStatusHandler(gameStatusEventHandler)
Registers a function to handle a game status event.
host.unregisterGameStatusHandler(gameStatusEventHandler)
Unregisters a game status event-handling function.

Trigger Methods

host.trig_create(object, callback, objName, radius, unknownBool, data)
host.trig_getObjects(trig_id)
host.trig_destroyAll()
host.trig_destroy(trig_id)

Global Stats Methods

host.pers_gamespyStatsNewGame()
host.pers_gamespyStatsEndGame()
host.pers_gamespyStatsSendSnapshotFinal(snapShot)
host.pers_gamespyStatsSendSnapshotUpdate
host.pers_getStatsKeyVal(key)
host.pers_plrRequestAwards(playerIndex, unknown, unknown)
host.pers_plrRequestStats(playerIndex, unknown, urlToStatType)
Presumably returns the specified stat of the specified player.
host.pers_plrRequestUnlocks(playerIndex, unknown)
Presumably returns the specified player's unlocks.
host.pers_plrSetUnlocks(playerIndex, unknown, unknown)
host.pers_plrAwardMedal

"sh" Methods (SwiffHost?)

host.sh_setEnableCommander(bool)
Enables or disables the commander position.

"gl" Methods (GameLogic?)

host.gl_sendEndOfRoundData(dataString)
Presumably sends stats-related information to clients when a round ends.

"sgl" Methods (ServerGameLogic?)

host.sgl_getSettingsBool
host.sgl_sendTextMessage(playerId, 10, 1, message)
Send a server message to one player. Working Status Unknown
host.sgl_sendRankEvent(playerIndex, rank, score)
host.sgl_sendMedalEvent(playerIndex, type, value)
host.sgl_sendPythonEvent
host.sgl_sendGameLogicEvent(playerID, event, data)
host.sgl_sendHudEvent(playerID, event, data)
host.sgl_getIsAIGame()
Presumably returns whether or not the current game has AI.
host.sgl_getControlPointsInGroup
host.sgl_endGame(winner, victoryType)
Presumably ends a current game, awarding victory of victoryType to winner.
host.sgl_getParam(name, unknown, unknown)
host.sgl_setParam(name, unknown, unknown, unknown)
host.sgl_getWorldSize()
returns a tuple giving the north/south and east/west dimensions of the current map, more-or-less in meters.
host.sgl_getMapName()
Returns the current map name.
host.sgl_getModDirectory()
Returns the directory containing the currently active mod.

"ss" Methods (Server Settings?)

host.ss_getParam(parameter)
Returns value of specified setting.
Settings include:
ticketRatio
teamRatioPct
maxPlayers
gameMode
mapName
timeLimit
scoreLimit
autoBalance
tkpEnabled
tkpNeeded
tkpDefault
globRank
globUnlocks
You cannot find out server name, port and other similar information this way. Instead, use f.e. host.rcon_invoke('sv.serverName') to get the server name.

Object Manager Methods

host.omgr_getObjectsOfTemplate(template)
host.omgr_getObjectsOfType(type)

Timer Methods

host.timer_created(timer)
host.timer_getTimers - Do not use, unfinished DICE code
Creates a Tuple and only fills one slot. Trying to access the other slots will crash the server.
host.timer_destroy(timer)
host.timer_getWallTime()
Return the number of seconds since server started; see BF2 Time

Player Manager Methods

host.pmgr_enableScoreEvents
host.pmgr_getScore(playerIndex, name)
Gets value of score name of specified player.
host.pmgr_setScore(playerIndex, name, value)
Sets value of score name of specified player.
host.pmgr_p_get(name, playerIndex)
host.pmgr_p_set(name, playerIndex, value)
host.pmgr_isIndexValid(index)
Checks the validity of specified player index.
host.pmgr_getCommander()
Presumably returns Player object for the current commander.
host.pmgr_getPlayers()
Returns current player objects.
host.pmgr_getNumberOfPlayers()
Returns number of players.

RCon Methods

host.rcon_invoke(command)
Executes a server console command.
host.rcon_feedback(playerid, message)
Send a message to an in-game player RCon client.

List of available host.rcon_invoke commands

Logging Methods

host.log(message)
Send a message to the log.

PhysicalObject

PhysicalObjects represent physical things in the BF2 game world; as such, they have the properties of real objects in the physical world: properties like position (X, Y, Z coordinates) and orientation (rotation), and can contain, and be contained by, other PhysicalObjects. PhysicalObjects appear to be implemented as C++ objects in the game engine which the embedded Python engine has access to, but since they are game engine objects, they are not defined anywhere in Python, and cannot be created directly in Python--but they can be accessed from Python. No special imports are necessary to manipulate these objects.

Please note that since these are not native Python objects, we don't know what they are actually named inside the game engine; "PhysicalObject", as well as the names of other types of objects that inherit from that class, are made up for convienience. We also can't see into the game engine code to see if the hierarchial structure of these classes is what is presented here--for example, VehicleObject and SoldierObject may, in fact, be a single class; the hierarchy of PhysicalObject's decendents given here should nevertheless be equivalent to whatever the real hierarchy is.

PhysicalObject is a base class whose methods and attributes are inherited by several sub-classes.

Methods for instances of PhysicalObject

physicalObject.isValid()
physicalObject.getTemplateProperty()
physicalObject.getPosition()
physicalObject.setPosition( (X, Y, Z) )
physicalObject.getRotation()
physicalObject.setRotation( (A, B, C) )
physicalObject.getParent()
Returns PhysicalObject that contains this instance, if any
physicalObject.getChildren()
Returns a tuple of PhysicalObjects contained by this instance

For information about the coordinate system used by the Position and Rotation methods, see the page on BF2 Coordinates.

The known properties available via the getTemplateProperty method are:

radius
(For control points only.)
ControlPointID
(For control points only.)

Attributes for instances of PhysicalObject

physicalObject.templateName
physicalObject.isControlPoint
physicalObject.isPlayerControlObject
physicalObject.hasArmor
physicalObject.token

WeaponObject

A WeaponObject is used to represent a weapon in BF2. The WeaponObject class inherits the methods and attributes of PhysicalObject, with no additonal methods or attributes.

KitObject

A KitObject is used to represent a "kit" in BF2. The KitObject class inherits the methods and attributes of PhysicalObject, with no additonal methods or attributes.

ControlPointObject

A ControlPointObject is used to represent a control point in BF2. The ControlPointObject class inherits the methods and attributes of PhysicalObject, with the following additional methods and attributes:

Additional Methods

ControlPointObject.cp_getParam('parameter')
ControlPointObject.cp_setParam('parameter', value)

Additional Attributes

ControlPointObject.flagPosition
Returns 0=top, 1=middle, 2=bottom
ControlPointObject.lastAttackingTeam
ControlPointObject.triggerId

Internal Properties

ControlPointObjects also have a number of internal properties that are accessed through the cp_getParam and cp_setParam methods:

isHemisphere
0 or 1, indicating if the control point capture area is a hemisphere or not.
team
Team the capture point belongs to: 0 for neutral, 1 for team 1, and 2 for team 2. Updating this value also changes the minimap and flag tag indicator.
flag
The flag image used in the control point; 1 for team 1's flag, 2 for team 2's.
areaValue
The weighting value for this control point
unableToChangeTeam
Whether or not this control point is capturable (0) or not (1)
timeToGetControl
How many seconds it takes to get control of this control point
timeToLoseControl
How many seconds it takes to get control of this control point
onlyTakeableByTeam
Whether (1) or not (0) this control point is only capturable by one team
takeOverChangePerSecond
Capture speed; speed at which the flag at this control point raises or lowers.
enemyTicketLossWhenCaptured
Ticket loss caused to the enemy when this control point is captured (needs to be verified)
playerId
Unknown; may set the playerID of the player that captured this control point first (the first player to arrive, not assisting players?)

VehicleObject

A VehicleObject represents a BF2 vehicle. The VehicleObject class inherits the methods and attributes of PhysicalObject, with several additional methods. SoldierObject, used to represent the physical body of player, is a sub-class of VehicleObject.

Additional Methods

vehicleObject.getDamage()
vehicleObject.setDamage(intValue)
vehicleObject.getIsWreck()
Returns boolean, 1 if the vehicle is destroyed
vehicleObject.getOccupyingPlayers()
Returns an array with index 0 being the driver
vehicleObject.getIsRemoteControlled()

The getDamage() and setDamage() methods actually read/set the health of the vehicle. Transport helicopters start with 1500, tanks with 1000 and light jeeps with 750. They all explode when the damage reaches 0.

SoldierObject

A SoldierObject represents the physical body of a human or AI player in BF2. The SoldierObject class inherits the methods and attributes of VehicleObject, with no additonal methods or attributes. (Note: it appears that within the game engine, SoldierObject and VehicleObject may actually be the exact same thing; conceptually, though, it helps to think of SoldierObject as a subclass of VehicleObject).

It is important to pay attention to the destinction between a player's "physical" body in the game, which is represented by an instance of the SoldierObject class, having position, orientation, health, etc., and the in-game "spirit" of that player, which is represented by an instance of the bf2.PlayerManager.Player class, having properties like a name, squad, profile ID, etc. The bf2.PlayerManager.Player ("spirit") is created when a player connects to the server, and persists as long as the server continues running, even across game rounds (and disconnect/reconnects--if the player disconnects and then reconnects, the server tries to match them up with an existing bf2.PlayerManager.Player object). By contrast, a player remains associated with a SoldierObject only as long as they remain alive; as soon as they die, their association with the SoldierObject is broken; when they respawn, a new SoldierObject instance is created, and becomes associated with the player. That is to say, between dying and respawning, the player's "spirit" leaves their first "body" and is "reincarnated" in a new "body". Is that metaphysical enough for you?

bf2.GameStatus

Just used as a container for the constant values returned by callbacks from the GameStatusChanged event:

bf2.GameStatus.Playing
bf2.GameStatus.EndGame
bf2.GameStatus.PreGame
bf2.GameStatus.Paused
bf2.GameStatus.RestartServer
bf2.GameStatus.NotConnected

You must import bf2 to access these class attributes.

bf2.GameLogic.GameLogic

A wrapper around lots of BF2 engine stuff accessible through host, apparently to make it more Pythonic. During its initialization the bf2 class instantiates this class as the singleton object bf2.gameLogic.

You must import bf2 to access the methods and attributes of this object.

Methods for the singleton object

bf2.gameLogic.getModDir()
bf2.gameLogic.getMapName()
bf2.gameLogic.getWorldSize()
returns a tuple giving the north/south and east/west dimensions of the current map, more-or-less in meters.
bf2.gameLogic.getTeamName(team)
bf2.gameLogic.isAIGame()
bf2.gameLogic.sendClientCommand(playerId, command, args)
Appears to tell game engine to prompt a player for input; the player's response returns control to Python by generating a ClientCommand event; command is typically a numeric value, args can be anything, but is typically a tuple or list.
bf2.gameLogic.sendGameEvent(playerObject, event, data)
Tells the BF2 game engine to cause a GameEvent to occur.
bf2.gameLogic.sendMedalEvent(playerObject, type, value)
bf2.gameLogic.sendRankEvent(playerObject, rank, score)
bf2.gameLogic.sendHudEvent(playerObject, event, data)
Tells the BF2 game engine to cause a HudEvent to occur.
bf2.gameLogic.sendServerMessage(playerId, message)
bf2.gameLogic.getTicketState(team)
bf2.gameLogic.setTicketState(team, value)
bf2.gameLogic.getTickets(team)
bf2.gameLogic.setTickets(team, value)
bf2.gameLogic.getDefaultTickets(team)
bf2.gameLogic.getTicketChangePerSecond(team)
bf2.gameLogic.setTicketChangePerSecond(team, value)
bf2.gameLogic.getTicketLimit(team, id)
bf2.gameLogic.setTicketLimit(team, id, value)
bf2.gameLogic.getDefaultTicketLossPerMin(team)
bf2.gameLogic.getDefaultTicketLossAtEndPerMin()
bf2.gameLogic.getWinner()
bf2.gameLogic.getVictoryType()
bf2.gameLogic.setHealPointLimit(value)
Percentage heal required to trigger a PlayerHealPoint event.
bf2.gameLogic.setRepairPointLimit(value)
Percentage heal required to trigger a PlayerRepairPoint event.
bf2.gameLogic.setGiveAmmoPointLimit(value)
Percentage heal required to trigger a PlayerGiveAmmoPoint event.
bf2.gameLogic.setTeamDamagePointLimit(value)
Percentage heal required to trigger a PlayerTeamDamagePoint event.
bf2.gameLogic.setTeamVehicleDamagePointLimit(value)

bf2.GameLogic.ServerSettings

Another wrapper around more BF2 engine stuff that's accessible through host; this class makes it accessing these things cleaner and more Pythonic. During its initialization the bf2 class instantiates this class as the singleton object bf2.serverSettings.

You must import bf2 to access the methods and attributes of this object.

Methods for the singleton object

bf2.serverSettings.getTicketRatio()
bf2.serverSettings.getTeamRatioPercent()
bf2.serverSettings.getMaxPlayers()
bf2.serverSettings.getGameMode()
bf2.serverSettings.getMapName()
bf2.serverSettings.getTimeLimit()
bf2.serverSettings.getScoreLimit()
bf2.serverSettings.getAutoBalanceTeam()
bf2.serverSettings.getTKPunishEnabled()
bf2.serverSettings.getTKNumPunishToKick()
bf2.serverSettings.getTKPunishByDefault()
bf2.serverSettings.getUseGlobalRank()
bf2.serverSettings.getUseGlobalUnlocks()

You cannot find out server name, port and other similar information this way. Instead, use f.e. host.rcon_invoke('sv.serverName') to get the server name.

bf2.ObjectManager.ObjectManager

During its initialization the bf2 class instantiates this class as the singleton object bf2.objectManager. This object can be used by Python to get access to internal game engine C++ objects. A list of the available object types can be found here, and a list of available object templates can be found here.

You must import bf2 to access the methods and attributes of this object.

Methods for the singleton object

bf2.objectManager.getObjectsOfType('object type')
bf2.objectManager.getObjectsOfTemplate('object template')


bf2.PlayerManager.PlayerScore

Objects of this class maintain a long list of player score attributes. They are used inside of objects of the Player class; for any Player object x, x.score is an object of class PlayerScore.

You will not normally create objects of this class; they are created automatically as part of the Player class when Player objects are created. No special imports are necessary to access methods and attributes of these objects.

There is also a separate player.stats object, which tracks different information. You can use the following code fragment to see all of the variables in the player.stats object.

for s in vars(player.stats): print str(s)

Class methods

reset()
resets all score attributes stored within the object itself.

Class attributes stored in the PlayerScore object

index
heals
ammos
repairs
damageAssists
passengerAssists
driverAssists
targetAssists
driverSpecials
revives
teamDamages
teamVehicleDamages
cpCaptures
cpDefends
cpAssists
suicides
cpNeutralizes
cpNeutralizeAssists
rplScore
This attribute may not be in all versions of BF2
skillScore
cmdScore

Class attributes stored in the BF2 engine

deaths
kills
TKs
score
skillScore
rplScore
cmdScore
fracScore
rank
firstPlace
secondPlace
thirdPlace
bulletsFired
gives a tuple, each element of which is a 2-tuple consisting of the name of a weapon the player has fired, and the number of shots they fired from that weapon. As the player uses more weapons, more of the 2-tuples are added to the list. An example tuple returned:
(("uspi-m16", 30), ("knife", 3))
Before the first weapon is fired, this may be None or an empty tuple. The first weapon fired will not always be the first 2-tuple on the list returned.
bulletsGivingDamage
Same as above, but only with bullets giving damage
bulletsFiredAndClear
The "AndClear" resets the engine counter. polling this will only give new bullets. However having more than one module polling them is not a good idea.
bulletsGivingDamageAndClear

Class attributes computed from other attribute values

dkRatio

bf2.PlayerManager.Player

An object of this class is created for each player in the game. When they are initialized, Player objects automatically instantiate a PlayerScore object and assign it to their score attribute.

You must import bf2.PlayerManager if you wish to create objects of this class; normally, however, you will just access methods and attributes of already existing Player objects that are returned to you by other calls, which requires no special import statement.

Instances created with

 x = bf2.PlayerManager.Player(index)

Class Attributes

index
playerID for this player
score
current score for this player

Methods

isValid()
isRemote()
isAIPlayer()
isAlive()
isManDown()
isConnected()
getProfileId()
isFlagHolder()
getTeam()
setTeam(t)
getPing()
Returns the player's ping (network transit time from player to server and back) in milliseconds
getSuicide()
Returns 1 if the player suicided. Resets once the player spawns.
setSuicide(t)
getTimeToSpawn()
Returns 0 when a player is spawned in; when a player is waiting to spawn, it returns the number of seconds until they are allowed to spawn.
setTimeToSpawn(t)
Appears to generate an exception if used on a player that is already spawned in; if used on a player that that is waiting to spawn it changes the time until they are allowed to spawn.
getSquadId()
Returns the player's squad ID. Squads for each team are independently numbered beginning at "1" and increasing thereafter. Players not on a squad, including team commanders, are assigned to squad "0".
isSquadLeader()
Returns 1 if player is a squad leader.
isCommander()
Returns 1 if player is currently the commander.
getName()
Return's player's name
setName(name)
Sets a player's name (at least, it changes what getName() returns), but the change doesn't show up in-game--everything in the game still shows the player's old name. (it is working,but only sees that player who connected after the name change.)
getSpawnGroup()
setSpawnGroup(t)
getKit()
Returns the current player's kit object.
getVehicle()
Returns the current player's vehicle object. If the player is not in a vehicle at the time this returns the player's soldier object.
getDefaultVehicle()
Returns the player's soldier object, no matter what vehicle they are in.
getPrimaryWeapon()
Returns the weapon object for the player's currently selected weapon.
getAddress()
Returns player's IP address
setIsInsideCP(val)
getIsInsideCP()

bf2.PlayerManager.PlayerManager

This class is a wraper around some player management functions in the BF2 engine, and also adds some simple calculations and logic to those functions. During its initialization the bf2 class instantiates this class as the singleton object bf2.playerManager.

You must import bf2 to access the methods and attributes of this object.

Methods for the singleton object

bf2.playerManager.getNumberOfPlayers()
bf2.playerManager.getCommander(team)
bf2.playerManager.getPlayers()
bf2.playerManager.getPlayerByIndex(index)
bf2.playerManager.getNextPlayer(index)
bf2.playerManager.getNumberOfPlayersInTeam(team)
bf2.playerManager.getNumberOfAlivePlayersInTeam(team)
bf2.playerManager.enableScoreEvents()
Enables PlayerScore events
bf2.playerManager.disableScoreEvents()
Disables PlayerScore events


bf2.Timer

(Not available in PR, use the realitytimer below.)

Objects in this class are timers that can cause timer events to be generated when a fixed amount of time has elapsed. Instances are created with

 timer = bf2.Timer(timerEventHandler, delta, alwaysTrigger, data)

timerEventHandler is the handler to be called when delta seconds have elapsed since the creation of the timer; alwaysTrigger should be 1 (not sure what the alternative is). data is an optional item (typically a tuple) that will be passed to timerEventHandler. (Note that even though data is optional when establishing a timer, the timerEventHandler must specify it as a parameter, or the handler won't work).

A timer may fire only once per tick. Setting a very low interval time will assure the timer fires every tick. Setting 0 disables it.

You must import bf2.Timer to create timer objects.

Class Methods

destroy()
Destroys the associated game engine timer (but not the Python instance.)
getTime()
Returns the wall time at which this timer will fire.
setTime(time)
Changes the wall time at which this timer will fire.
setRecurring(interval)
Specifies this this timer should fire repeatedly, every interval seconds.
onTrigger()
For internal use only; calls timerEventHandler.



Project Reality Timer interface

Project Reality timer (realitytimer.py) expands the default interface and adds:

-Exception catching with a debug message when an exception is not caught in the handler, No need to worry about bad code crashing the server.

-Internal check to make sure timers don't fire after destroy() was called (Can happen when Destroy() is called on the same tick)

-realitytimer.fireOnce(targetFunc, delay, data=None) class that can fire an event once after delay and then destroy itself (No need to store reference)

-realitytimer.fireNextTick(targetFunc, data=None) class that will fire the event at the next game tick and then destroy itself (Also no need to store)

bf2.TriggerManager.TriggerManager

This class is a wraper around some player management functions in the BF2 engine. During its initialization the bf2 class instantiates this class as the singleton object bf2.triggerManager. This object is used to manage "triggers", which are events that are fired when a PCO enters a defined spherical or hemispherical volume surrounding an object.

You must import bf2 to access the methods and attributes of this object.

Methods for the singleton object

bf2.triggerManager.createRadiusTrigger(object, callback, objName, radius, data=None)
Creates a trigger that causes callback to be called if a player enters a spherical region of radius radius centered on object, passing data as an argument.
bf2.triggerManager.createHemiSphericalTrigger(object, callback, objName, radius, data=None)
Same as bf2.triggerManager.createRadiusTrigger, except that instead of a spherical trigger region, the trigger region is a flat circle lying along the ground (yes, it's badly named).
bf2.triggerManager.destroyAllTriggers()
Destroys all registered triggers.
bf2.triggerManager.destroy(trig_id)
Destroys a specific trigger.
getObjects(trig_id)
Returns a tuple containing all objects currently within the specified trigger region.

bf2.stats.constants

This module appears intended to be imported with something like

 from bf2.stats.constants import *

so that everything in it is loaded into the local namespace, rather than being a part of any object. The module includes a lot of constants and dictionaries, as well as some utility functions.

Functions

getVehicleType(templateName)
getWeaponType(templateName)
getKitType(templateName)
getArmy(templateName)
getMapId(mapName)
getGameModeId(gameMode)
getRootParent(physicalObject)
Traverses the containment for physicalObject all the way to the top; returns the outermost (topmost?) containing object.

For example, getWeaponType("usrif_m16a2") looks up an M16 rifle in a dictionary called weaponTypeMap (also defined in bf2.stats.constants) and returns the constant WEAPON_TYPE_ASSAULT. . . which, too, is defined in bf2.stats.constants, as having a numeric value of "0". A list of template names used in some of these functions can be found in the Game Engine Object Templates page.

These constant values appear to be the same as those used in the statistics server, specifically the look up values.