BASEQ3 Runthrough, Server-side
Synopsis
Illustration of an execution path through a Q3 game module (baseq3), from startup through gameplay though shutdown, for dedicated server mode, in outline form.
Motivation:
Enhanced understanding of Q3A to assist in modding and total conversions.
Caveats:
This document certainly is not a thorough understanding nor explanation of Q3.
Information was gleaned by poring through the game source text, with minimal testing.
Most of the statements made in this document are based on source comments and gut feelings
.
Before the game (modification) even loads, Quake 3 on startup:
- searches for/in pak (.pk3) files according to the server cvar
fs_game
- runs startup configuration (.cfg) files default.cfg and q3config.cfg
- initializes the dynamic memory hunk (
com_hunkMegs
, com_soundMegs
, com_zoneMegs
)
- opens network sockets for listening
The most straight-forward way to launch the game is to start a valid map, with the server command map mapname
.
Quake 3 on game start:
- loads the map/level (.bsp) file
- looks through the pak (.pk3) files found on startup
- loads the game qvm file (qagame.qvm)
- compiles the qvm bytecode to native code if vm_game is set to 2
- jumps to the QVM procedure linked at code address 0 (i.e. vmMain())
- upon returning from the QVM procedure, does some other things (such as network tasks, reading in server commands, complaining with Hitch Warnings, etc.)
- jumps to code address 0 again
- rinse, lather, repeat.
The QVM file lacks a symbol table, so the QVM interpreter/compiler subsystem must make a blind decision on a reasonable entry point into the QVM.
Currently, Q3 simply branches to QVM code address 0.
While Q3 (the engine) decides to jump to code address 0, the game (mod) expects Q3A to jump into the function named vmMain().
To ensure these two expectations coincide, vmMain() must be the first function compiled before any other function into QVM bytecode.
This means the function vmMain() must be the first fully-defined function in the first assembled file.
In baseq3, this is vmMain() in g_main.c, which gets assembled first as specified in the file game.q3asm, thus ensuring vmMain() links as code address 0.
Note that other variables may be declared/defined before vmMain(), and other functions may be prototyped/declared before vmMain(), but the first function body to be compiled must be vmMain().
The function at code address 0 is the critical function.
The associated name can be anything, but for consistency I shall refer to code address 0 as vmMain
, as it is in baseq3.
On each server frame (time period determined by cvar sv_fps
), the Q3 engine calls vmMain() with a number of arguments.
The first argument (command in baseq3) determines what major action
to which the game should react.
These actions are enumerated in g_public.h, as enum type gameExport_t.
Since the arguments to vmMain() are specified by the Q3 engine, and merely reflected in gameExport_t, modifying gameExport_t does not change anything in the game module, except possibly to confuse it badly.
A quick overview of the vmMain commands (major game functions) in baseq3:
- GAME_INIT - called on game load/startup.
- GAME_SHUTDOWN - called on end of map/level or server quitting, before actual exit.
- GAME_CLIENT_CONNECT - called when a new player connects to the server.
- GAME_CLIENT_THINK - called (frequency unknown) to handle player inputs and movements.
- GAME_CLIENT_USERINFO_CHANGED - called when a client userinfo record has changed (such as name or player model) and the new information needs to be relayed to all players.
- GAME_CLIENT_DISCONNECT - called when a client disconnect (voluntary disconnect, kicked, timed out), for selective cleanup.
Not called on map/level end (which is wholesale destruction of QVM memory, See also GAME_SHUTDOWN).
- GAME_CLIENT_BEGIN - called when a client's connection is established, map loaded, and ready to start playing (i.e. supply user inputs).
- GAME_CLIENT_COMMAND - when a client sends a command to the server (such as
say
, say_team
, or kill
).
- GAME_RUN_FRAME - called once per server frame to animate and move all non-player entities that need movement or thinking.
- GAME_CONSOLE_COMMAND - called to handle server-side commands (from admin), including rcon commands.
- BOTAI_START_FRAME - Schedules and executes bot user command (framerate of AI is not synchronized with server framerate).
The call to vmMain() is made by the Q3 engine.
The parameters passed to vmMain are marshalled by the Q3 engine.
Additions or changes to these major game functions must be implemented in the engine and reflected in the game module (mod).
Such ability (to add or change major functions) is limited to developers with access to the Q3 engine (not mod) source.
Currently (2002 Aug) this is Id Software itself and its direct licensees (proprietary license).
When the game module is first loaded on game start, Q3 calls vmMain with major function GAME_INIT, along with three additional arguments:
- levelTime - the number of milliseconds the game has been in progress, usually 0 (non-zero for restarts).
- randomSeed - a seed value for the random number generator (RNG).
- restart - ???, affects bot AI initialization only.
In vmMain(), the code immediately branches to G_InitGame() when vmMain recognizes GAME_INIT.
- Initialize random number generator with randomSeed -- srand(randomSeed).
- Register cvars (associates cvars in the Q3 engine with cvar_t variables in game engine) -- G_RegisterCvars().
- Goes through all entries in array gameCvarTable[], associating the cvar in the Q3 engine with the cvar_t variable in the game engine (QVM memory).
- Initialize banlist -- G_ProcessIPBans().
- Reads list of space-separated IP addresses from cvar
g_banIPs
.
- Adds each banned address to ban filter list -- AddIP().
- Maximum of 1024 banned addresses.
- Converts dotted-quad notation to an internal filter format -- StringToFilter().
- Adds filter record to array ipFilters[].
- Initialize the in-QVM dynamic memory pool of 256KB (hey, 64KB sent us to the moon!) -- G_InitMemory().
- Start logging if so configured.
- Initialize world session information -- G_InitWorldSession().
- Resets cvar
session
- Initialize game entities.
- Initialize game clients (players).
- Tell the Q3 engine about g_entities, for network engine purposes -- trap_LocateGameData().
- Initialize body queue (for sinking corpses, etc.) -- InitBodyQue().
- Allocates 8 game entities and reserves them for the body queue.
- Initialize item registration -- ClearRegisteredItems().
- Clears the array itemRegistered[].
- Registers machine gun -- RegisterItem().
- Sets itemRegistered[10] to true (offset for machine gun weapon item)
- Registers gauntlet -- RegisterItem().
- Sets itemRegistered[8] to true (offset for gauntlet weapon item)
- Spawn map entities -- SpawnEntitiesFromString().
- Enable entities spawning with level.spawning = qtrue.
- Parse worldspawn variable, which must be the first such entity in the map file -- SP_worldspawn().
- Read a spawn string -- G_SpawnString("classname", "", &s).
- Retrieve the next spawn string, complain if the spawn string key doesn't match the first argument (i.e. "classname"), otherwise store the value into the third argument. The second argument provides a default value if no value is specified in the map file.
- Complain if the string isn't the worldspawn variable, with a fatal error (game stops).
- Set ConfigString CS_GAME_VERSION according to mod.
- Set ConfigString CS_LEVEL_START_TIME according to the recorded start time.
- Set ConfigString CS_MUSIC (map-specific background music) according to spawn entity -- G_SpawnString("music", "", &s).
- Set ConfigString CS_MESSAGE (map-specific message) according to spawn entity -- G_SpawnString("message", "", &s).
- Set ConfigString CS_MOTD (server MOTD) according to server cvar
sv_motd
.
- Set cvars
g_gravity
, g_enableDust
, and g_enableBreath
according to spawn entities.
- Record the existence of the worldspawn entity.
- Set warmup time as needed, based on cvar
g_doWarmup
.
- Parse spawn variables -- G_ParseSpawnVars().
- Expect an opening brace (
{
), fail miserably if not found -- trap_GetEntityToken().
- Read all key/value pairs.
- Read a token as a key -- trap_GetEntityToken().
- Stop loop if this token is a closing brace (
}
).
- Read a token as a value -- trap_GetEntityToken().
- Complain if this token is a closing brace (
}
).
- Complain if there are now more than 64 spawn variables.
- Record spawn variable key.
- Record spawn variable value.
- Spawn entities from spawn variables -- G_SpawnGEntityFromSpawnVars().
- Allocate a game entity -- G_Spawn().
- Parse the fields for each spawn variable -- G_ParseField().
- ???!
- Takes key/value pairs and sets fields in game entity using arcane binary doohackery.
- Destroy entity according to game type and gametype spawnflags (notsingle, notteam, notfree).
- Destroy entity according to spawn variable gametype and active game type.
- Adjust origins(?)
- Call assocated game spawn function -- G_CallSpawn().
- Complain if entity classname is NULL.
- Attempt to spawn as an item -- G_SpawnItem().
- Set entity field random according to spawn variable random.
- Set entity field wait according to spawn variable wait.
- Register this item -- RegisterItem().
- Check if item is disabled and don't spawn if so -- G_ItemDisabled().
- Returns the value of cvar
disable_classname
. So to disable quad damage would be /set disable_quaddamage 1
.
- Record global/master/templated item information.
- Set think time and function -- FinishSpawningItem().
- Makes items fall to floor. Falling is disabled at spawn time to prevent items spawning within other entities.
- Make entity bouncy.
- Set powerup fields for powerup items (in particular, speed according to spawn variable noglobalsound).
- If the entity didn't spawn as an item, attempt to spawn as a normal entity by finding the classname and calling the associated spawn function -- s->spawn().
(XXX: spawn[] and list of SP_*() functions)
- Failing that, complain about lack of spawn function.
- Destroy object if no such spawn function exists.
- Initialize teams information -- G_FindTeams().
- Create a linked list for each team composed of all entities belonging to the team. The team master is the lowest numbered entity that is not a slave.
- Broadcast item registration information via ConfigString -- SaveRegisteredItems().
- Sets ConfigString CS_ITEMS to a sequence of ASCII
1
and 0
according tot he content of array itemRegistered[]. The information is transmitted to all clients for precaching purposes.
- Initialize bot AI -- BotAISetup(), BotAILoadMap(), G_InitBots().
(XXX: Aieeee!)
- Various other server-side tweaks.
That was just for game initialization.
When Q3 wants to shut down the game module, Q3 calls vmMain() with major function GAME_SHUTDOWN, and one additional argument:
- restart - ???, affects bot AI initialization only.
In vmMain(), the code immediately branches to G_ShutdownGame() when vmMain() recognizes GAME_SHUTDOWN.
For map changes (as after end of round), the game module is shut down then initialized again with the new map (partly to have a clean slate for the new map's entities).
Any data within QVM memory is irretrievably destroyed.
Any data that needs to survive across map changes, or even map restarts, must be committed to files (disk) or cvars (Q3 engine memory).
- Closes any logs.
- Save session data -- G_WriteSessionData().
- Save world session data to cvar
session
, which is just current gametype.
- Save each client session data -- G_WriteClientSessionData().
- Save to cvar
sessionclientnum
the information pertaining to client's team, spectator time, spectator state, client being spectated, wins, losses, and teamLeader.
- Shutdown bot AI -- BotAIShutdown().
- (XXX: yeah, right...)
When a client connects to the server, Q3 calls vmMain() with major function GAME_CLIENT_CONNECT, with arguments:
- clientNum - the assigned client number according to the Q3 engine.
- firstTime - zero if a persistent connection from a previous game on the same server, non-zero if a fresh connect to the server.
- isBot - non-zero if the connecting player is a bot AI.
In vmMain(), code immediated branches to ClientConnect() when vmMain recognizes GAME_CLIENT_CONNECT.
- Get userinfo string from client -- trap_GetUserinfo().
- Check if client's IP address is banned -- G_FilterPacket().
- Check client's IP address against each entry in array ipFilters[].
- Check for password.
- Read/initialize session data -- G_InitSessionData().
- Figure out a team to join; autojoin, spectator, predetermined join (same team as last game), waiting-in-line.
- Set various flags if bot.
- Enact effects of client userinfo -- ClientUserinfoChanged().
- Get userinfo from client (again).
- Enforce sanity-check on name -- Info_Validate().
- Check if local client (non-networked).
- Check if client wants item prediction.
- Set client name.
- Set client team.
- Announce any during-play name change (a client that just connected technically had a name-change from nothing to something, but this particular name change isn't announced).
- Set max health (influence by handicap value).
- Set player model.
- Select skin according to team (if applicable).
- Set teamtask.
- Arrange a subset of userinfo into a ConfigString, stored into a CS_* slot based on client number.
- Announce team joining -- BroadcastTeamChange().
- Tells everyone in the game about someone joining/changing teams.
- Calculate client ranks -- CalculateRanks().
- (XXX: lotsa math and sorting...)
Called (frequency unknown) to handle player input to the game and player movement within the game, with one additional argument:
- clientNum - the client number of which to handle input.
In vmMain(), the code immediately branches to ClientThink() when vmMain recognizes GAME_CLIENT_THINK.
- Retrieve user input -- trap_GetUsercmd().
- Mark the time input was received.
- If not a bot, do non-bot client think process -- ClientThink_real().
- Check if client is still in
Connecting
phase. Return from function if so.
- Record time of retrieval of usercmd (user input).
- Basic timestamp sanity check to squelch speedup cheats.
- Sanity checks on cvar
pmove_msec
.
- Timestamp checks for cvar
pmove_fixed
.
- Check for intermission -- ClientIntermissionThink().
- Disable talk balloons and weapons.
- Toggle
READY
status each time attack button is pressed (changes from low to high).
- If client is spectator, do spectator thinking and return -- SpectatorThink().
- If not following, do almost-normal movements and some triggering.
- Start following or cycle to next spectatee(?) if attack button is pressed.
- Check for inactivity timer -- ClientInactivityTimer().
- If cvar
g_inactivity
is unset or 0, set inactivity timer to 1 minute, but don't do any actual inactivity kicking. This gives some leeway to all players during the instant when admin decides to actually set inactivity timer during gameplay (otherwise the time since game start counts as inactivity at that instant).
- Otherwise check if client is moving or doing some action, and push forward the inactivity timestamp.
- Do not kick local player(s).
- Otherwise check if current time surpassed inactivity timestamp and kick.
- Otherwise see if time to send 10-second warning.
- Clear overhead reward icons if time expired.
- Check movement style (noclip, dead, normal).
- Inherit gravity value.
- Set client speed.
- Increase client speed due to any powerups (haste, scout).
- Prepare for pmove (predictable movement) calculation.
- Check for gauntlet hit for the gauntlet-hit animation if attack button is held with gauntlet, store into pm.gauntletHit -- CheckGauntletAttack().
- See if any damageable object is within 32 units of player.
- Create blood splatters.
- Increase damage due to powerups (Quad, Doubler).
- Apply damage to victim.
- Return true if gauntlet made a hit, otherwise return false.
- Check for gesturing and set animation if needed.
- Check for invulnerability powerup (Team Arena only).
- Make pmove calculations -- Pmove().
- Save results of pmove into client structs.
- Smooth out if cvar
g_smoothClients
is non-zero -- BG_PlayerStateToEntityState().
- Snap various vectors (round components to nearest integer).
- Execute client events -- ClientEvents().
- Retrieve next client event.
- Check fall damages (EV_FALL_MEDIUM, EV_FALL_FAR):
- Check that fall damage is being applied to a player.
- Check if fall damage is disabled (cvar
g_dmflags
& DF_NO_FALLING (8)).
- Set damage amount, 10 for far, 5 for medium.
- Set pain debounce time (XXX: what??)
- Apply damage to player -- G_Damage().
- Check weapon firing (EV_FIRE_WEAPON):
- Fire weapon -- FireWeapon().
- (XXX: Aieee!)
- Check using handheld teleporter (EV_USE_ITEM1):
- Drop CTF flag(s).
- Select a random spawn point -- SelectSpawnPoint().
- Teleport the player to the new point -- TeleportPlayer().
- Create appropriate teleport effects at old and new points.
- Unlink player from game -- trap_UnlinkEntity().
- Place player at new spawn point with some altered properties (speed, angle).
- Telefrag.
- Update from pmove calculations -- BG_PlayerStateToEntityState().
- Link player back into game.
- Check using medkit (EV_USE_ITEM2):
- Sets health to player's maximum health plus 25; the maximum health may vary according to handicap. The medkit is
used up
(removed) elsewhere.
- Check using kamikaze (Team Arena only, EV_USE_ITEM3):
- Check using portal(???) (Team Arena only, EV_USE_ITEM4):
- Check using invulnerability (Team Arena only, EV_USE_ITEM5):
- Ignore other event types.
- Link entity into the world and PVS -- trap_LinkEntity().
- Trigger any... triggers -- G_TouchTriggers().
- Ensure the triggerer(?) is a living player.
- Find all entities reaching into player's space (bounding box), store list into array touch[].
- For each touched entity:
- Ignore if not a trigger.
- If spectating, ignore certain triggers.
- If an item, ignore (since item-touching is handled elsewhere) -- BG_PlayerTouchesItem()
- Otherwise check that the player really is in contact with this entity -- trap_EntityContact().
- If this entity has a touch() function, call it -- hit->touch().
- If client has a touch() function, call it -- ent->touch().
- Check for jumppad.
- Some bot AI checks -- BotTestAAS().
- (XXX: foo)
- Interact with other objects/entities -- ClientImpacts().
- For each entity the player is touching (pm->numtouch, pm->touchents[]):
- Run the player's touch() function, if it exists.
- Run the other entity's touch() function, if it exists.
- Save results of triggers and events.
- Swap/latch button actions, helps check for button press/release.
- If player is dead, check for respawning, based on button press or cvar
g_forcerespawn
-- respawn().
- Create a corpse in body queue -- CopyToBodyQue().
- Selects next spot in queue, overwriting as it goes.
- Unlink the body queue entry -- trap_UnlinkEntity().
- Copy properties of corpse, unset inapplicable properties (such as powerups).
- Set to last frame of death animation, to prevent looped animation.
- Set movement properties.
- Link corpse into game -- trap_LinkEntity().
- Spawn the player -- ClientSpawn().
- If a spectator, just set a spawn point for spectators -- SelectSpectatorSpawnPoint().
- Spawn at intermission location -- FindIntermissionPoint().
- Look for info_player_intermission entity.
- Set viewing angles, towards a target if specified.
- If intermission entity does not exist, the map creator is a moron:
- Select a single-player spawn point as if normally playing, to use as intermission entity -- SelectSpawnPoint().
- If a team game, choose spawn point for team games -- SelectCTFSpawnPoint().
- Choose a team spawn point -- SelectRandomTeamSpawnPoint().
- If just joining the team, look for spawn point named team_CTF_redplayer or team_CTF_blueplayer according to team.
- If not just joining (as in having been just fragged and respawned), look for spawn point named team_CTF_redspawn or team_CTF_bluespawn.
- Look through each spawn point of the appropriate name:
- If the spot would cause a telefrag, choose next spawn point. Otherwise record the location in array spots[].
- If a telefrag-less spot doesn't exist, just use first spawn point. Otherwise, choose a random spawn point from spots[].
- Return the spawn point information.
- If there is no team spawn point, choose a single-player (info_player_deathmatch) spawnpoint -- SelectSpawnPoint().
- Otherwise choose spawn point single-player style:
- If spawned for the first time, choose a
good-looking
spot -- SelectInitialSpawnPoint().
- Look for a spawn point (info_player_deathmatch) with the initial flag set (0x01).
- If no such special spawn point exists, or if the initial spawn point would cause telefrag, choose spawn point the normal way with SelectSpawnPoint().
- If not spawned for first time, select a spawn point far from death point -- SelectSpawnPoint().
- Just calls SelectRandomFurthestSpawnPoint().
- Look through all info_player_deathmatch entities:
- Check if telefrag would occur, choose another spot if so -- SpotWouldTelefrag().
- Check if any players occupy some of the space the would-be-spawned player would occupy.
- Record distance of this spawn point from the avoidPoint (i.e. where player's death occurred) into list_dist and list_spot using [reverse] insertion sort.
- If no spawn point can avoid telefrag, choose first spawn point (info_player_deathmatch).
- Now that list_dist and list_spot are sorted in decreasing order of distances (furthest first), choose a random spot from the first half of the list.
- Return selected spawn point location.
- Juggle spawn point according to nobot or nohuman flags for spawn points.
- Initialize various client flags, fields, and records.
- Provide client with gauntlet and machine gun, with some ammo.
- Set spawn-time health.
- Move client position to spawn point -- G_SetOrigin().
- Set client view angle -- SetClientViewAngle().
- Sets angle vectors based on spawn point variables (XXX: which one?).
- Telefrag as needed -- G_KillBox().
- Link client into game -- trap_LinkEntity().
- Bring up the base weapon, the machine gun.
- Prevent full-tilt running at spawn time.
- Reset inactivity timer.
- Set initial animation.
- If on intermission, do intermission stuff -- MoveClientToIntermission().
- If spectator, stop following -- StopFollowing().
- Clears spectator-following fields.
- Move to intermission location (set by spawn variable info_player_intermission).
- Set movement type to PM_INTERMISSION.
- Clear powerups, attributes, flags, sounds, events, etc.
- Otherwise, trip triggers at spawn point, then select highest player weapon available (which may not be machine gun) -- G_UseTargets().
- Drop player to the floor by gravity -- ClientThink(). No loop as
needs to respawn
has been cleared by now.
- Add teleportation effect at spawn point -- G_TempEntity().
- Link client into game (again, just to be sure).
- Run end-of-frame stuff -- ClientEndFrame.
- Entity state stuff -- BG_PlayerStateToEntityState().
- Run once-per-second client actions -- ClientTimerActions().
- Check if one-second period has passed.
- Increase health due to regeneration powerup, rate is influenced by any excessive health.
- Tick down excessive health (health greater than maxHealth) if no regeneration powerup.
- Tick down excessive armor (armor greater than maxArmor).
- Tick up ammo due to ammo-regen powerup (Team Arena only).
- Check for quad damage powerup.
- Accumulate accuracy statistics.
- Determine firing direction.
- Fire according to weapon in use:
- gauntlet -- Weapon_Gauntlet()
- (Non-operation. Nothing. Nada. Zilch.)
- (Checking for gauntlet hit is done in CheckGauntletHit()).
- lightning gun -- Weapon_LightningFire()
- Check for anything in front for 768 units (LIGHTNING_RANGE)
- Bounce off any invulerability spheres (Team Arena only)
- Apply damage to victim.
- Cause visual and audio effects.
- Record accuracy stats.
- shotgun -- weapon_supershotgun_fire()
- Seed RNG for shotgun pattern.
- Fire shotgun pellets -- ShotgunPattern().
- For 11 (DEFAULT_SHOTGUN_COUNT) pellets:
- Fudge local up and right by random positive or negative values.
- Check for damage dealt by pellet.
- Record accuracy stats.
- machine gun -- Bullet_Fire()
- Fudge the aim direction by a bit (for random spread).
- Search along fudged direction for a victim (or wall).
- Bounce off invulnerability spheres (Team Arena only).
- Cause bullet-hit effect.
- Deal damage -- G_Damage().
- grenade launcher -- weapon_grenadelauncher_fire()
- Fudge the aim direction upwards a little bit for loft.
- Create and launch a grenade -- fire_grenade()
- Allocate a game entity -- G_Spawn().
- Set fields for a grenade entity.
- Snap velocity vectors (components rounded to integers).
- Increase grenade damage by any quad damage.
- rocket launcher -- Weapon_RocketLauncher_fire()
- Create and launch a rocket -- fire_rocket()
- Allocate a game entity -- G_Spawn().
- Set fields for a rocket entity.
- Snap velocity vectors (components rounded to integers).
- Increase rocket damage by any quad damage.
- plasma gun -- Weapon_PlasmaGun_Fire()
- Create and launch a plasma round -- fire_plasma()
- Allocate a game entity -- G_Spawn().
- Set fields for a plasma entity.
- Snap velocity vectors (components rounded to integers).
- Increase plasma damage by any quad damage.
- railgun -- weapon_railgun_fire()
- Railgun range is 8192 units.
- Bounce off invulnerability (Team Arena only).
- Record accuracy stats.
- Damage up to 4 (MAX_RAIL_HITS) players, passing through three.
- Rail slug stops at walls or other impenetrable obstacles.
- Create rail beam/trail effect.
- Fudge locations a bit for visual effect (so rail appears to start from gun location)
- Check for
Impressive
(two consecutive railgun hits without a miss) reward.
- BFG10K -- BFG_Fire()
- Create and launch a BFG round -- fire_bfg()
- Allocate a game entity -- G_Spawn().
- Set fields for a BFG entity.
- Snap velocity vectors (components rounded to integers).
- Increase BFG damage by any quad damage.
- grappling hook -- Weapon_GrapplingHook_Fire()
- nailgun (Team Arena only) -- Weapon_Nailgun_Fire()
- proximity mine launcher (Team Arena only) -- weapon_proxlauncher_fire()
- chaingun (Team Arena only) -- Bullet_Fire()
TODO: Pmove()
When a client user's info has changed (name, player model, handicap, etc.), the Q3 server is notified and reacts with a call to vmMain() with major function GAME_CLIENT_USERINFO_CHANGED, with one argument:
- clientNum - the client number of the client that changed its info.
Immediate branch to ClientUserinfoChanged().
- Note client number and client object/entity.
- Retrieve client userinfo -- trap_GetUserinfo().
- Check for invalid string -- Info_Validate().
- Check if local client (key ip) -- Info_ValueForKey().
- Check item prediction (key
cg_predictItems
).
- Set name (key
name
).
- Announce if in-game name change.
- Set max health according to handicap (key
handicap
).
- Set player model (keys
model
and hmodel
, or team_model
and team_hmodel
).
- If a bot, join team a short time later.
- Otherwise just set team (or spec).
- Set model skin according to team.
- Determine if client wants teamoverlay info (key
teamoverlay
).
- Set team task (key
teamtask
) and leader.
- Set colors (keys
color
, g_redteam
, g_blueteam
).
- Construct a ConfigString from a subset of userinfo, to broadcast to all clients.
When client disconnects (voluntary disconnect
, kicked, dropped, etc.).
Arguments:
- clientNum - the client number of the client just disconnected.
Immediate branch to ClientDisconnect().
- Check if kicking a still-unspawned bot -- G_RemoveQueuedBotBegin().
- If any spectator is following this client, stop their following -- StopFollowing().
- Create teleport-out effect.
- Drop any powerups client had -- TossClientItems().
- If a tournament game, award remaining player with a win.
- Unlink the client -- trap_UnlinkEntity().
- Mark ex-client as being disconnected and mark its slot as unused.
- Clear associated ConfigString.
- Recalculate ranks -- CalculateRanks().
- If a bot AI, shutdown AI -- BotAIShutdownClient().
When client is ready to play.
This occurs when client has finished connecting and loading, or has switched teams, or has continued in from the previous map.
Does not occur on respawns (why should the Q3 engine know about respawns+teleport? The game engine does, though).
Arguments:
- clientNum - client number.
Immediate branch to ClientBegin().
- Note client number and client entity/record.
- Unlink client entity -- trap_UnlinkEntity().
- Initialize client game entity -- G_InitGentity().
- Clear and initialize some critical game entity fields.
- Initialize client fields.
- Select a spawn point -- ClientSpawn().
- Announce the player joining the game, if not tournament mode.
- Recalculate ranks -- CalculateRanks().
When client sends a command to the server.
This usually occurs when the client-end doesn't recognize a console command from the user, and so passes off the command to the server in hopes the server understands it.
Arguments:
- clientNum - client number
Immediate branch to ClientCommand().
- Check client validity.
- Retrieve command name from string -- trap_Argv().
- Check against known command names:
say
say_team
tell
vsay
vsay_team
vtell
vosay
vosay_team
votell
vtaunt
score
- (At intermission, the following commands are ignored, and instead are transmitted as global chat)
give
god
notarget
noclip
kill
teamtask
levelshot
follow
follownext
followprev
team
where
callvote
vote
callteamvote
teamvote
gc
setviewpos
stats
- Unrecognized commands return an error message to the originating client.
Called by Q3 each server frame (period determined by cvar sv_fps
, default value of 20 fps (or 50 ms/frame)) to advance all non-player objects.
Arguments:
- levelTime - the elapsed time on the level as reported by Q3 engine (this is where level.time comes from!).
Immediate branch to G_RunFrame().
- Check if waiting for level to restart.
- Remember previous levelTime.
- Store current levelTime.
- Calculate the time difference.
- Update all cvar changes -- G_UpdateCvars().
- Record the current timestamp (not levelTime) -- trap_Milliseconds().
- For all allocated game entities:
- Ignore unused entity.
- Clear out old events.
- Free entity slot if no longer needed -- G_FreeEntity().
- Unlink entity if needed -- trap_UnlinkEntity().
- Ignore temporary entity (they don't think).
- Ignore unlinked entity.
- If a missile type, run missile think -- G_RunMissile().
- Find missile's current position -- BG_EvaluateTrajectory().
- Do checks for what the missile will or will not pass through.
- See if missile passed through anything noteworthy -- trap_Trace().
- Check if missile is stuck in anything, otherwise just keep moving forward.
- Link missile into the game (XXX: when was it unlinked?) -- trap_LinkEntity().
- If missile collided with something:
- Just free up the entity if hit a SURF_NOIMPACT surface (such as sky or a black hole).
- Otherwise do missile impact stuff -- G_MissileImpact().
- Check for bouncing -- G_BounceMissile()
- (vector math for ricochet/bounce effect)
- Deal impact damage, if applicable.
- Stick proximity mine to victim (Team Arena only)
- Latch grappling hook and start pulling, if applicable.
- Create any explosion effect -- G_AddEvent().
- Snap vectors.
- Deal any splash damage -- G_RadiusDamage().
- Sanity check on damage radius, create a damage bounding box.
- Find entities within damage bounding box and save to array entityList[] -- trap_EntitiesInBox().
- For all the entities in entityList[]:
- Ignore if entity marked for ignore.
- Ignore if entity cannot be damaged.
- See if entity is actually within damage radius.
- Get distance from explosion center to entity center.
- Calculate damage based on this distance.
- Deal damage and knockback, while recording accuracy stats.
- Link missile into the world (XXX: again?) -- trap_LinkEntity().
- If missile hasn't exploded yet, run its think function -- G_RunThink().
- If an item type that's bouncing, run item think -- G_RunItem().
- Check if item is in free fall.
- Check if item has stationary trajectory, if so then just run G_RunThink() and return.
- Get current position of item.
- See if it hit/landed on anything.
- Run think function -- G_RunThink().
- If in a nodrop brush, remove entity from game.
- Cause item to bounce -- G_BounceItem().
- (lots of vector math)
- If a mover, run mover think -- G_RunMover().
- Check if a team slave, return if so (team captain handles all activities).
- If not stationary, run mover -- G_MoverTeam().
- Make sure all team members (other movers in a chain) are able to move -- G_MoverPush().
- Establish boundaries of mover and entire movement area covered.
- Unlink mover temporarily -- trap_UnlinkEntity().
- Find entities within mover's movement area and store into list listedEntities[] -- trap_EntitiesInBox().
- Move pusher to final position.
- Link mover back into the game -- trap_LinkEntity().
- For each entity in listedEntities[]:
- Try pushing proxmine (Team Arena only).
- Ignore entity if not an item nor a player.
- Move entities standing on mover, and ensure it doesn't try to occupy the same space as the mover -- G_TestEntityPosition().
- Push entity -- G_TryPushingEntity().
- Any entites that bob (such as items) get killed if stuck inside a mover position (such as between doors), move on to next pushed object.
- Otherwise move entities back, since this is an obstacle.
- Restore old position(s) if any mover member can't move.
- Run blocked() function for any mover member that couldn't move -- part->blocked().
- Otherwise calculate and set new positions.
- If a mover member reachd one end of its movement, call its reached() function -- part->reached();.
- Run entity-specific think function -- G_RunThunk().
- If a client, run client think -- G_RunClient().
- Check if a bot AI, return if so.
- Record levelTime
- Call ClientThink_real().
- Otherwise, just run think -- G_RunThink().
- Check if there is any thinktime.
- Check if levelTime exceeded thinktime, return if not.
- Disable nextthink and run entity's think -- ent->think().
- Record current timestamp -- trap_Milliseconds().
- (Time elapsed during run cycle can be calculated (but isn't)).
- Do final fixups on players -- ClientEndFrame().
- Check for tournament restart -- CheckTournament().
- Check for end of level -- CheckExitRules().
- If still intermission time, check that all non-bot clients are READY to leave intermission, return if not ready to exit level/map -- CheckIntermissionExit().
- Check for queued intermission (???)
- Ignore if queue time not yet exceeded.
- Unqueue intermission.
- Begin intermission -- BeginIntermission().
- Return if intermission already in progress.
- For tournament mode, adjust tournament scores -- AdjustTournamentScores().
- Update number of wins or losses for the two competitors.
- Record the current levelTime as the intermission time.
- Find the intermission location -- FindIntermissionPoint().
- If single-player game:
- Update tournament information -- UpdateTournamentInfo()
- Take note of (the only) player's record/slot/entity.
- Calculate ranks -- CalculateRanks().
- Record postgame data?
- Calculate accuracy percentage.
- Check for
Perfect
reward.
- Record rewards information.
- show the victory podium -- SpawnModelsOnVictoryPads()
- Spawn the podium -- SpawnPodium().
- Create podium entity.
- Place podium in front of intermission view.
- Place the top three players in their appropriate places -- SpawnModelOnVictoryPad().
- Copy entity properties of the player into a new game entity.
- Set entity location relative to podium and intermission viewpoint.
- Move all clients to intermission point -- MoveClientToIntermission()
- Send current scores to all clients -- SendScoreboardMessageToAllClients().
- For each client:
- Send scoreboard info -- DeathmatchScoreboardMessage()
- For all clients:
- Construct string based on client number, frags, ping time, play time, score flags, powerups, rewards, and captures.
- Send this huge-ass string, along with blue team score and red team score, to client -- SendServerCommand().
- Update team status -- CheckTeamStatus().
- Check if time to do team location update.
- For all clients:
- Ignore clients still connecting.
- Determine team.
- Store team location information into client record.
- For all clients (again):
- Ignore clients still connecting.
- Determine team.
- Transmit team location information to client -- TeamplayInfoMessage().
- Return if client has no (doesn't want?) teaminfo.
- Extract top eight teammates on player's team.
- Sort the eight teammates by client number.
- For all clients or the first 32 (TEAM_MAXOVERLAY) (whichever is less):
- Ignore if this client is not in use, or is not on the same team.
- Store client's health and armor.
- Construct a string based on the client's list location (cycle in this particular loop), location, health, armor, current weapon, and active powerup.
- Truncate constructed string if too long (8192 bytes).
- Transmit the constructed string to the client -- trap_SendServerCommand().
- Check global votes -- CheckVote().
- If vote string is to be executed and it's time to execute, execute the string as a command -- trap_SendConsoleCommand().
- Return if no vote in progress.
- Check if vote time expired, report vote having failed if so.
- Otherwise check for votes:
- If Yes has simple majority, report success and execute vote string within 3 seconds.
- If No has simple majority, report failure.
- Otherwise keep waiting for a majority one way or another.
- Update ConfigString CS_VOTE_TIME accordingly.
- Check team votes -- CheckTeamVote().
- Determine which team to check (blue or red).
- Return if no vote is in progress.
- If voting time limit is exceeded, report failure to... everyone(!).
- Otherwise:
- Check if Yes votes has simple majority.
- If the vote was to change leader, set new team leader -- SetLeader().
- Otherwise execute vote string as a command -- trap_SendConsoleCommand().
- Check if No votes has simple majority; cause vote to fail if so.
- Otherwise keep waiting for a majority vote.
- Set CS_TEAMVOTE_TIME (+1 for blue) accordingly.
- Check on changes in cvars -- CheckCvars().
- Do nothing (return) if cvar
g_password
has not changed.
- If cvar
g_password
is set, and is not none
, set g_needpass
to 1.
- Otherwise, set cvar
g_needpass
to 0.
- Dump entities list if cvar
g_listEntity
is non-zero.
When a console command is entered directly to the server from the server console (admin commands).
No arguments.
Immediate branch to ConsoleCommand().
- Retrieve command name -- trap_Argv().
- Check command:
entitylist
forceteam
game_memory
addbot
botlist
abort_podium
addip
removeip
listip
- If command is not found and server is running in dedicated mode (cvar
dedicated
is 1 or 2), repeat the command line as global chat text from console.
Created 2002.08.26
Updated 2002.09.16 - re-wordings suggested by members of Quake 3 World Modifications Programming Forum (MPF).
Updated 2003.11.10 - corrections sent in by cyrri.
Updated 2011.07.11 - change of contact e-mail.
PhaethonH
< PhaethonH@gmail.com >