Quake C Builtins

Warning
The definitions below are valid only for Quake version 1.00 and 1.01. Future versions may differ.

Copyright
This document is part of the Unofficial Quake Specifications, Copyright (c) 1996 by Olivier Montanuy. All the informations below are Copyright (c) 1996, id software. The content of this file was derived from code and comments released by John Carmack, of id software.

These are the types, definitions and functions that are built in Quake C. Various comments and code bits, scattered around all the .C and .QC files, were used to compile this document. A lot of these comments were cryptic or outdated. As John Carmack himself stated, Quake C deserves a rewrite: meanwhile, that document should help you clarify it a bit.

I wish some day they decided to use a fast and reliable scripting language, safely compilable to byte code or to machine code... Just take a look at Objective CAML ;-)

Simple Types

Type: void

An empty result, mostly used for definition of procedures (i.e. functions that return no result at all).

Type: float

A floating point value
Also used to store booleans (TRUE, FALSE) or integer values.
Valid syntax: 12 1.6 0.5 -100
Invalid syntax: .5

Type: vector

A vector, made of 3 float coordinates.
Used to represent positions or directions in 3D space.
Valid syntax: '0 0 0' or '20.5 -10 0.00001'

Type: string

A character string.
Used to indicate file names, or messages to be broadcast to players.
Valid syntax: "maps/jrwiz1.bsp" or "ouch!\n"
Use \n for newline.

Type: entity

The reference of an entity in the game, like things, players, monsters.
There are two default entity references available to functions, as global variables:


Definition of entities

Here are the fields available in entity definitions (like self, other):
(only modify fields in boldface. others are managed by C code.)
Technicals
float   modelindex;            // index of model, in the precached list
string  classname;             // spawn function
float   spawnflags;                 // see possible values
float   ltime;                 // local time for entity
float   teleport_time;         // don't back up
float   solid;                 // ?
entity  groundentity;          // ?
entity  chain;                 // next entity, in a chain list of entities
Appearance of entity
string  model;          // name of the entity model
float   frame;          // frame in the model
float   skin;           // index of the skin, in model
float   effects;        // special light effects on model
Position in 3D
vector  origin;                 // position of model
//      origin_x 
//      origin_y 
//      origin_z
vector  mins;                   // bounding box extents reletive to origin
//      mins_x, mins_y, mins_z
vector  maxs;                   // bounding box extents reletive to origin
//      maxs_x, maxs_y, maxs_z
vector  size;                   // maxs - mins
//      size_x
//      size_y
//      size_z
vector  absmin;                 // origin + mins and maxs
//      absmin_x absmin_y absmin_z
vector  absmax;                 // origin + mins and maxs
vector  oldorigin;              // old position
vector  angles;                 // 'yaw       pitch       0'
float   waterlevel;             // 0 = not in water, 1 = feet, 2 = waist, 3 = eyes
float   watertype;              // a content value
Movement in 3D
vector  velocity;               // 'speedx    speedy     speedz'
vector  avelocity;              // 'pitchspeed  yawspeed  0'
vector  punchangle;             // temp angle adjust from damage or recoil
float   movetype;               // type of movement
float   yaw_speed;              // rotation speed
Monster's Behavior
entity  goalentity;             // Monster's movetarget or enemy
float   ideal_yaw;              // Monster's ideal direction, on paths
float   nextthink;              // next time when entity must act
string  target;
string  targetname;
Automatic Behavior
void()  touch;                  // function invoked if entity is touched
void()  use;                    // function invoked if entity is used
void()  think;                  // function invoked when entity must act
void()  blocked;                // function for doors or plats, called when can't push other
vector  movedir;                // mostly for doors, but also used for waterjump
string  message;                // trigger messages
float   sounds;                 // either a cd track number or sound number
string  noise;                  // soudn played on entity noise channel 1
string  noise1;
string  noise2;
string  noise3;                 

Player/Monster Stats
float   health;                 // health level
float   max_health;             // players maximum health is stored here
Player inventory
float   items;                  // bit flags
float   armortype;              // save this fraction of incoming damage
float   armorvalue;             // armor level
float   impulse;                // weapon changes
float   weapon;                 // one of the IT_SHOTGUN, etc flags
string  weaponmodel;            // entity model for weapon 
float   weaponframe;            // frame for weapon model
float   currentammo;            // ammo for current weapon
float   ammo_shells;
float   ammo_nails;
float   ammo_rockets;
float   ammo_cells;
Fight
float   takedamage;                  // boolean, TRUE if entity can be damaged
  // DAMAGE_NO=0  FALSE
  // DAMAGE_YES=1 TRUE
  // DAMAGE_AIM=2 (like YES, except for Ogre Grenade)
float   deadflag;             // DEAD_DEAD
entity  enemy;                  // personal enemy (only for monster entities)
float   button0;                // fire
float   button1;                // use
float   button2;                // jump
vector  view_ofs;               // position of player eye, relative to origin
float   fixangle;
vector  v_angle;                // view or targeting angle for players
float   idealpitch;             // calculated pitch angle for lookup up slopes
entity  aiment;                 // aimed antity?
float   dmg_take;               // damage is accumulated through a frame. and sent as one single
float   dmg_save;               // message, so the super shotgun doesn't generate huge messages
entity  dmg_inflictor;          // entity that inflicted the damage (player, monster, missile, door)
entity  owner;                  // Entity that owns this one (missiles, bubbles are owned by the player)
Deathmatch
float   frags;                  // number of frags
string  netname;                // name, in network play
float   colormap;               // colors of shirt and pants
float   team;                    // team number
float   flags;                  // ?
Player Only
float   walkframe;
float   attack_finished;
float   pain_finished;         // time when pain sound is finished
float   invincible_finished;
float   invisible_finished;
float   super_damage_finished;
float   radsuit_finished;
float   invincible_time;       // time when player cease to be invincible
float   invincible_sound;
float   invisible_time;        // time when player cease to be invisible
float   invisible_sound;
float   super_time;            // time when quad shot expires?
float   super_sound;
float   rad_time;
float   fly_sound;
float   axhitme;                // TRUE if hit by axe
float   show_hostile;           // set to time+0.2 whenever a client fires a
                                // weapon or takes damage.  Used to alert
                                // monsters that otherwise would let the player go
float   jump_flag;              // player jump flag
float   swim_flag;              // player swimming sound flag
float   air_finished;           // when time > air_finished, start drowning
float   bubble_count;           // keeps track of the number of bubbles
string  deathtype;              // keeps track of how the player died
Object stuff
string  mdl;                    // model name?
vector  mangle;                 // angle at start
vector  oldorigin;              // only used by secret door
float   t_length;
float   t_width;
Doors
vector  dest;
vector  dest1;
vector  dest2;
float   wait;                   // time from firing to restarting
float   delay;                  // time from activation to firing
entity  trigger_field;          // door's trigger entity
string  noise4;
float   aflag;
float   dmg;                    // damage done by door when hit
Monsters
float   pausetime;
entity  movetarget;
Miscellaneous
float   cnt;                    // counter
void()  think1;
vector  finaldest;
vector  finalangle;
//
// triggers
//
float   count;                  // for counting triggers
//
// plats / doors / buttons
//
float   lip;
float   state;
vector  pos1;
vector  pos2;             // top and bottom positions
float   height;
//
// sounds
//
float   waitmin;
float   waitmax;
float   distance;
float   volume;

Definitions

Values: Contents of areas

CONTENT_EMPTY = -1;   // Empty area
CONTENT_SOLID = -2;   // Totally solid area (rock)
CONTENT_WATER = -3;   // Pool of water
CONTENT_SLIME = -4;   // Pool of slime
CONTENT_LAVA  = -5;   // Lava
CONTENT_SKY   = -6;   // Sky

Values: Spawnflags

The spawn flags are bit fields, whose interpretation depend on the concerned entity. There is quite a bit of a hack, that could cause unexpected bugs in the Quake C code.
DOOR_START_OPEN = 1;      // allow entity to be lighted in closed position
SPAWN_CRUCIFIED= 1;       // for zombie
PLAT_LOW_TRIGGER = 1;     // for func_plat
SPAWNFLAG_NOTOUCH= 1;
SPAWNFLAG_NOMESSAGE= 1;
PLAYER_ONLY = 1;
SPAWNFLAG_SUPERSPIKE = 1;  // for spike shooter
SECRET_OPEN_ONCE = 1;      // secret door, stays open
PUSH_ONCE = 1;
WEAPON_SHOTGUN = 1;        // weapon, shotgun
H_ROTTEN = 1;              // health, rotten (5-10 points)
WEAPON_BIG2 = 1;           // items 
START_OFF = 1;             // light, is off at start.
SILENT = 2;
SPAWNFLAG_LASER = 2;       // for spike shooter
SECRET_1ST_LEFT = 2;       // secret door, 1st move is left of arrow
WEAPON_ROCKET = 2;         // weapon, rocket
H_MEGA = 2;		   // health, mega (100 points)
DOOR_DONT_LINK = 4;
SECRET_1ST_DOWN = 4;       // secret door, 1st move is down from arrow
WEAPON_SPIKES = 4;         // weapon, nailgun
DOOR_GOLD_KEY = 8;
SECRET_NO_SHOOT = 8;       // secret door, only opened by trigger
WEAPON_BIG = 8;            // weapon, super model
DOOR_SILVER_KEY = 16;
SECRET_YES_SHOOT = 16;	   // secret door, shootable even if targeted
DOOR_TOGGLE = 32;

Names: Console variables

These variables can be read or modified from the console, during game play. The player can change them, to affect the program behavior.
"samelevel"     // boolean, stay on same level.
"registered"    // boolean, game is registred (no not change).
"noexit"        // boolean, true if can't exit level in deathmatch.
"timelimit" 	// number of minutes.
"fraglimit"     // maximum number of frags before deathmatch ends.
"temp1"         // custom variable
"skill"         // a message.
"sv_gravity"    // gravity pull, normal value is 800.
"teamplay"      // boolean, true if playing in teams.

Known messages structure

How messages are send

MSG_BROADCAST = 0; // unreliable message, sent to all
MSG_ONE       = 1; // reliable message, sent to the entity
                   // defined by msg_entity
MSG_ALL       = 2; // reliable message, sent to all
MSG_INIT      = 3; // write to the init string

Message: Temporary Sound

  WriteByte (MSG_BROADCAST, SVC_TEMPENTITY);
  WriteByte (MSG_BROADCAST, soundname);
  WriteCoord (MSG_BROADCAST, origin_x);
  WriteCoord (MSG_BROADCAST, origin_y);
  WriteCoord (MSG_BROADCAST, origin_z);
Where soundname is one of TE_SPIKE, TE_SUPERSPIKE, TE_GUNSHOT ,TE_EXPLOSION, TE_TAREXPLOSION, TE_LIGHTNING1, TE_LIGHTNING2, TE_WIZSPIKE, TE_KNIGHTSPIKE, TE_LIGHTNING3, TE_LAVASPLASH, TE_TELEPORT.

Message: CD Track

  WriteByte (MSG_ALL, SVC_CDTRACK);
  WriteByte (MSG_ALL, val1); // CD track?
  WriteByte (MSG_ALL, val2); // ?

Message: Final Message

  WriteByte (MSG_ALL, SVC_FINALE);
  WriteString (MSG_ALL, "any text you like\n");

Message: Sell Screen

WriteByte (MSG_ALL, SVC_SELLSCREEN);
Shows the infamous sell screen (like you needed it to understand).

Message: Inter Mission

WriteByte (MSG_ALL, SVC_INTERMISSION);
Shows the inter mission camera view.

Message: Killed Monster

WriteByte (MSG_ALL, SVC_KILLEDMONSTER);
Dunno why monster is not indicated...

Message: Found Secrets

WriteByte (MSG_ALL, SVC_FOUNDSECRET);

Global Variables

These variables are accessible in every functions.
Quake C function are not supposed to modify them directly.

Variable: world

the server's world object, which holds all global state for the server, like the deathmatch flags and the body ques.

Variable: time

The current game time, a floating point value in seconds.
Note that because the entities in the world are simulated sequentially, time is NOT strictly increasing. An impact late in one entity's time slice may set time higher than the think function of the next entity.
The difference is limited to 0.1 seconds.

Variable: self

the entity the function is executing for.

Variable: other

the other object in an impact, not used for thinks

Built in functions

These are the built-in functions of Quake C. Since they are hard-coded in C, they cannot be redefined, but they are very fast.

Basic math functions

Function: anglemod

float anglemod (float angle)
returns angle in degree, module 360.

Function: rint

 
 float rint(float val)
Returns val, rounded up to the closest integer value.

Function: floor

 
 float floor(float val)
Returns val, rounded up to the integer below (like the equivalent function in C).

Function: ceil

 
 float ceil(float val)
Returns val, rounded up to the integer above (like the equivalent function in C).

Function: fabs

 
 float fabs(float val)
Returns absolute value of val (like the equivalent function in C).

Function: random

Returns a random floating point number between 0.0 and 1.0

Function: ftos

string ftos(float value)
Float to string: converts value to string.

Basic vector maths

Function: normalise

vector normalise(vector v)
   returns a vector of length 1
Gives the vector colinear to v, but of length 1. This can be useful for calculation of distance along an axis.

Function: vlen

float vlen(vector v)
Returns the length of vector v (never < 0).

Function: vectoyaw

float vectoyaw(vector v)
   returns and angle in degree
Vector to yaw: calculates the yaw angle (bearing) corresponding to a given 3D direction v.

Function: vectoangles

vector vectoangles(vector v)
   returns vector 'pitch  yaw  0 '
Vector to angles: calculates the pitch angle (aiming) and yaw angle (bearing) corresponding to a given 3D direction v.

Function: vtos

string vtos(vector v)
Vector to String: print a vector, as a string.

Function: makevectors

void makevectors(vector angles)
  angle = 'pitch yaw 0' 
Calculate the vectors pointing forward, right and up, according to the provided angles.
Returns result in the global variables vector v_forward, vector v_up, vector v_right.

Emit Sounds

Function: sound

void sound (entity source, float channel, string sample, float volume, float attenuation)
  source = entity emiting the sound (ex: self)
  channel = channel to use for sound (0 to 7)
     to create a new channel: CHAN_AUTO
     to overide a channel:  CHAN_WEAPON, CHAN_VOICE, CHAN_ITEM,CHAN_BODY 
  sample = name of the sample WAV file (ex: "ogre/ogdrag.wav")
  volume = volume of sound (0.0 to 1.0)
  attenuation= attenuation of sound (0 to 4)
     full volume everywhere in the level: ATTN_NONE
     otherwise: ATTN_IDLE, ATTN_STATIC, ATTN_NORM
The entity emits a sound, on one of it's 8 channels.

Function: ambientsound

void ambientsound(vector position, string sample, float volume, float attenuation)
  position = position, in 3D space, inside the level
  sample = name of the sample WAV file (ex: "ogre/ogdrag.wav")
  volume = volume of sound (0.0 to 1.0)
  attenuation= attenuation of sound (0 to 4)
     full volume everywhere in the level: ATTN_NONE
     otherwise: ATTN_IDLE, ATTN_STATIC, ATTN_NORM
An ambient sound is emited

Entity management

Function: spawn

entity spawn ()
       returns an empty entity.
Create a new entity, totally empty. You can manually set every field, or just set the origin and call one of the existing entity setup functions.

Function: remove

void remove (entity e)
Removes entity e from the world (R.I.P.).

Function: nextent

entity nextent(entity e)
Returns entity that is just after e in the entity list.
Useful to browse the list of entities, because it skips the undefined ones.

Function: find

entity find (entity start, string field, string match)
	start = begining of list to search (world, for the begining of list)
	field = entity field that must be examined (ex: targetname)
	match = value that must be matched (ex: other.target)
	returns the entity found, or world if no entity was found.
Searches the server entity list beginning at start, looking for an entity that has entity.field = match.

Function: findradius

entity findradius (vector origin, float radius)
        origin = origin of sphere
        radius = radius of sphere
Returns a chain of entities that have their origins within a spherical area.
The entity returned is e, and the next in the chain is e.chain, until e==FALSE.
Typical usage: find and harm the victims of an explosion.
  e = findradius( origin, radius)
  while(e)
  {
    T_Damage(e, ... ) // Let God sort his ones!
    e = e.chain
  }

Function: setmodel

void setmodel (entity e, string model)
  e = entity whose model is to be set
  model = name of the model (ex: "progs/soldier.mdl")
Changes the model associated to an entity. This model should also be declared by precache_model. Please set e.movetype and e.solid first.

Function: lightstyle

void lightstyle(float style, string value)
        style = index of the light style, from 0 to 63.
        value = (ex: "abcdefghijklmlkjihgfedcb")
Modifies a given light style. The light style is used to create cyclic lighting effects, like torches or teleporter lighting.
There are 64 light styles, from 0 to 63. If style is not strictly comprised in these values, the game may crash.
styles 32-62 are assigned by the light program for switchable lights.
value is a set of characters, whose ascii value indicates a light level, from "a" (0) to "z" (30).

Move Entities

Function: ChangeYaw

void ChangeYaw()
Change the horizontal orientation of self. Turns towards self.ideal_yaw at self.yaw_speed, and sets the global variable current_yaw.
Called every 0.1 sec by monsters

Function: walkmove

float walkmove(float yaw, float dist)
       returns TRUE or FALSE 
Moves self in the given direction.
Returns FALSE if could not move (used to detect blocked monsters).

Function: droptofloor

float droptofloor()
       returns TRUE or FALSE 
Drops self to the floor, if the floor is less than -256 coordinates below.
Returns TRUE if landed on floor.
Mainly used to spawn items or walking monsters on the floor.

Function: setorigin

void setorigin (entity e, vector position)
  e = entity to be moved
  position = new position for the entity
Move an entity to a given location. That function is to be used when spawning an entity or when teleporting it.
This is the only valid way to move an object without using the physics of the world (setting velocity and waiting).
DO NOT change directly e.origin, otherwise internal links would be screwed, and entity clipping would be messed up.

Function: setsize

void setsize (entity e, vector min, vector max)
  e = entity whose bounding box is to be set  
  min = minimum, for bounding box (ex: VEC_HULL2_MIN)
  max = maximum, for bounding box (ex: VEC_HULL2_MAX)
Set the size of the entity bounding box, relative to the entity origin. The size box is rotated by the current angle.

Function: movetogoal

void movetogoal (float step)
Move self toward it's goal.
Used for monsters.

Fights and Shots

Function: aim

vector aim(entity e, float missilespeed)
Returns a vector along which the entity e can shoot.
Usually, e is a player, and the vector returned is calculated by auto-aiming to the closest enemy entity.

Function: particle

void particle(vector origin, vector dir, float color, float count)
    origin = initial position
    dir = initial direction
    color = color index (73,75, 
    count = time to live, in seconds
Create a particle effect (small dot that flies away).
color = 0   for chunk
color = 75  for yellow
color = 73  for blood red
color = 225 for entity damage

Function: checkclient

entity checkclient()
Returns client (or object that has a client enemy) that would be a valid target.
If there are more than one valid options, they are cycled each frame.
If (self.origin + self.viewofs) is not in the PVS of the target, FALSE is returned.

Collision checking

Function: traceline

traceline (vector v1, vector v2, float nomonsters, entity forent)
  v1= start of line
  v2= end of line
  nomonster= if TRUE, then see through other monsters, else FALSE.
  forent= ignore this entity, it's owner, and it's owned entities.
    if forent = world, then ignore no entity.
Trace a line of sight, possibly ignoring monsters, and possibly ignoring the entity forent (usually, forent = self).
This function is used very often, tracing and shot targeting.
Traces are blocked by bounding boxes and exact bsp entities.
Returns result in the global variables:
float trace_allsolid;	//
float trace_startsolid;	//
float trace_fraction;	// 
vector trace_endpos;	// end of line
vector trace_plane_normal;
float trace_plane_dist;	// distance
entity trace_ent;	// entity hit by the line
float trace_inopen;
float trace_inwater;

Function: checkpos

CURRENTLY DISABLED. DO NOT USE.
scalar checkpos (entity e, vector position)
Returns true if the given entity can move to the given position from it's current position by walking or rolling.

Function: checkbottom

float checkbottom(entity e)
       e = entity that is to be checked
       return TRUE or FALSE
Returns TRUE if on the ground.
Used only for jumping monster, that need to jump randomly not to get hung up (or whatever it actually means).

Function: pointcontents

float pointcontents(vector pos) 
Returns the contents of the area situated at position pos.
Used to know if an area is in water, in slime or in lava.
Makes use of the BSP tree, and is supposed to be very fast.

Network Messages

Function: makestatic

void makestatic (entity e)
Make an entity static to the world, by sending a broadcast message to the network, and then remove it from the dynamic list of entities in the world.
Typically used when spawning static lights (and also illusionary objects).

Function: changelevel

void changelevel (string mapname)
Warp to the game map named mapname. Actually executes the console command "changelevel" + mapname, so if you want to alias it...

Function: setspawnparms

void setspawnparms (entity client)
Restore the original spawn parameters of a client entity.
Doesn't work if client is not a player.

Function: stuffcmd

stuffcmd (entity client, string text)
       client = player that is to receive the command
       text = text of the command, ended by \n (newline).
Send a command to a given client, as if it had been typed on the client's console.
Mostly used to send the command bf

Print messages

Function: bprint

void bprint (string text)
	text = text of the message
Broadcast a message to all players on the current server.

Function: centerprint

void centerprint( entity client, string text)
	client = player that is to receive the message
	text = text of the message
Sends a message to a specific player, and print it centered.

Function: sprint

void sprint (entity client, string text)
        client = player that is to receive the message
	text = text of the message
Sends a message to a player.

Console

Function: localcmd

void localcmd (string text)
       text = text of the command, ended by \n (newline).
Execute a command on the server, as if it had been typed on the console.
Mostly used to send command restart or killserver.

Function: dprint

void dprint (string text)
	text = text of the message
Prints a message to the server console.

Function: cvar

float cvar (string variable)
      variable = see console variables
returns the value of a console variable.

Function: cvar_set

float cvar_set (string variable, string value)
      variable = see console variables
sets the value of a console variable.

Debugging

Function: eprint

void eprint (entity e)
	e = entity to print
Print details about a given entity (for debug purposes).

Function: coredump

void coredump()
Print all entities

Function: traceon

void traceon()
Start tracing functions, end them with traceoff()

Function: traceoff

void traceoff()
End traces started by traceon()

Function: break

void break()
Exit the programs. Never used?

Function: error

void error (string text)
Print an error message.

Function: objerror

void objerror (string text)
Print an error message related to object self.

Precaching files

When the Quake game runs, those function do nothing at all. But they are not useless: they are used to declare models, sounds and stuff, before the PAK file is built.

Just follow this rule: whenever one of your functions makes use of a file that's not defined in Quake, precache this file. Then, the QCC compiler can automatically include in the PAK file all the files that you really need to run your programs.

Function: precache_file

void precache_file(string file)
  file = name of the file to include in PAK file.
Does nothing during game play.
Use precache_file2 for registered Quake.

Function: precache_model

void precache_model(string file)
  file = name of the MDL or BSP file to include in PAK file.
Does nothing during game play.
Must be used in a model's spawn function, to declare the model file.
Use precache_model2 for registered Quake.

Function: precache_sound

void precache_sound(string file)
  file = name of the WAV file to include in PAK file.
Does nothing during game play.
Must be used in a model's spawn function, to declare the sound files.
Use precache_sound2 for registered Quake.

Raw Network Messages

Beware: when generating messages, you had better respect the format of the existing messages. Otherwise the game clients might not be able to interpret them (and will likely crash).

The functions below all write to clients (players connected via the network, or the local player).

Function: WriteByte

void WriteByte(float to, float value)
       to = see messages

Function: WriteChar

void WriteChar(float to, float value)
       to = see messages

Function: WriteShort

void WriteShort(float to, float value)
       to = see messages

Function: WriteLong

void WriteLong(float to, float value)
       to = see messages

Function: WriteCoord

void WriteCoord(float to, float value)
       to = see messages

Function: WriteAngle

void WriteAngle(float to, float value)
       to = see messages

Function: WriteString

void WriteString(float to, string value)
       to = see messages

Function: WriteEntity

void WriteEntity(float to, entity value)
       to = see messages