Import OA 0.8.8 tree

This commit is contained in:
Izuru Yakumo
2025-07-05 01:30:19 +00:00
committed by Izuru Yakumo
commit 733fac10f2
303 changed files with 175169 additions and 0 deletions

17
.gitignore vendored Normal file
View File

@@ -0,0 +1,17 @@
# A simulation of Subversion default ignores, generated by reposurgeon.
*.o
*.lo
*.la
*.al
*.libs
*.so
*.so.[0-9]*
*.a
*.pyc
*.pyo
*.rej
*~
*.#*
.*.swp
.DS_store
# Simulated Subversion default ignores end here

2196
Makefile Normal file

File diff suppressed because it is too large Load Diff

45
admin.dat Normal file
View File

@@ -0,0 +1,45 @@
[level]
level = 0
name = ^4Unknown Player
flags = iahC
[level]
level = 1
name = ^5Server Regular
flags = iahC
[level]
level = 2
name = ^6Team Manager
flags = iahCpP
[level]
level = 3
name = ^2Junior Admin
flags = iahCpPkm?
[level]
level = 4
name = ^3Senior Admin
flags = iahCpPkmBbe?
[level]
level = 5
name = ^1Server Operator
flags = *
[admin]
name = UnnamedPlayer
guid =
level = 5
flags =
[warning]
name = UnnamedPlayer
guid =
ip = localhost
warning = Dumb Move
made = 06/11/09 01:23:48
expires = 1244701428
warner = UnnamedPlayer

267
code/botlib/aasfile.h Normal file
View File

@@ -0,0 +1,267 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//NOTE: int = default signed
// default long
#define AASID (('S'<<24)+('A'<<16)+('A'<<8)+'E')
#define AASVERSION_OLD 4
#define AASVERSION 5
//presence types
#define PRESENCE_NONE 1
#define PRESENCE_NORMAL 2
#define PRESENCE_CROUCH 4
//travel types
#define MAX_TRAVELTYPES 32
#define TRAVEL_INVALID 1 //temporary not possible
#define TRAVEL_WALK 2 //walking
#define TRAVEL_CROUCH 3 //crouching
#define TRAVEL_BARRIERJUMP 4 //jumping onto a barrier
#define TRAVEL_JUMP 5 //jumping
#define TRAVEL_LADDER 6 //climbing a ladder
#define TRAVEL_WALKOFFLEDGE 7 //walking of a ledge
#define TRAVEL_SWIM 8 //swimming
#define TRAVEL_WATERJUMP 9 //jump out of the water
#define TRAVEL_TELEPORT 10 //teleportation
#define TRAVEL_ELEVATOR 11 //travel by elevator
#define TRAVEL_ROCKETJUMP 12 //rocket jumping required for travel
#define TRAVEL_BFGJUMP 13 //bfg jumping required for travel
#define TRAVEL_GRAPPLEHOOK 14 //grappling hook required for travel
#define TRAVEL_DOUBLEJUMP 15 //double jump
#define TRAVEL_RAMPJUMP 16 //ramp jump
#define TRAVEL_STRAFEJUMP 17 //strafe jump
#define TRAVEL_JUMPPAD 18 //jump pad
#define TRAVEL_FUNCBOB 19 //func bob
//additional travel flags
#define TRAVELTYPE_MASK 0xFFFFFF
#define TRAVELFLAG_NOTTEAM1 (1 << 24)
#define TRAVELFLAG_NOTTEAM2 (2 << 24)
//face flags
#define FACE_SOLID 1 //just solid at the other side
#define FACE_LADDER 2 //ladder
#define FACE_GROUND 4 //standing on ground when in this face
#define FACE_GAP 8 //gap in the ground
#define FACE_LIQUID 16 //face seperating two areas with liquid
#define FACE_LIQUIDSURFACE 32 //face seperating liquid and air
#define FACE_BRIDGE 64 //can walk over this face if bridge is closed
//area contents
#define AREACONTENTS_WATER 1
#define AREACONTENTS_LAVA 2
#define AREACONTENTS_SLIME 4
#define AREACONTENTS_CLUSTERPORTAL 8
#define AREACONTENTS_TELEPORTAL 16
#define AREACONTENTS_ROUTEPORTAL 32
#define AREACONTENTS_TELEPORTER 64
#define AREACONTENTS_JUMPPAD 128
#define AREACONTENTS_DONOTENTER 256
#define AREACONTENTS_VIEWPORTAL 512
#define AREACONTENTS_MOVER 1024
#define AREACONTENTS_NOTTEAM1 2048
#define AREACONTENTS_NOTTEAM2 4096
//number of model of the mover inside this area
#define AREACONTENTS_MODELNUMSHIFT 24
#define AREACONTENTS_MAXMODELNUM 0xFF
#define AREACONTENTS_MODELNUM (AREACONTENTS_MAXMODELNUM << AREACONTENTS_MODELNUMSHIFT)
//area flags
#define AREA_GROUNDED 1 //bot can stand on the ground
#define AREA_LADDER 2 //area contains one or more ladder faces
#define AREA_LIQUID 4 //area contains a liquid
#define AREA_DISABLED 8 //area is disabled for routing when set
#define AREA_BRIDGE 16 //area ontop of a bridge
//aas file header lumps
#define AAS_LUMPS 14
#define AASLUMP_BBOXES 0
#define AASLUMP_VERTEXES 1
#define AASLUMP_PLANES 2
#define AASLUMP_EDGES 3
#define AASLUMP_EDGEINDEX 4
#define AASLUMP_FACES 5
#define AASLUMP_FACEINDEX 6
#define AASLUMP_AREAS 7
#define AASLUMP_AREASETTINGS 8
#define AASLUMP_REACHABILITY 9
#define AASLUMP_NODES 10
#define AASLUMP_PORTALS 11
#define AASLUMP_PORTALINDEX 12
#define AASLUMP_CLUSTERS 13
//========== bounding box =========
//bounding box
typedef struct aas_bbox_s
{
int presencetype;
int flags;
vec3_t mins, maxs;
} aas_bbox_t;
//============ settings ===========
//reachability to another area
typedef struct aas_reachability_s
{
int areanum; //number of the reachable area
int facenum; //number of the face towards the other area
int edgenum; //number of the edge towards the other area
vec3_t start; //start point of inter area movement
vec3_t end; //end point of inter area movement
int traveltype; //type of travel required to get to the area
unsigned short int traveltime;//travel time of the inter area movement
} aas_reachability_t;
//area settings
typedef struct aas_areasettings_s
{
//could also add all kind of statistic fields
int contents; //contents of the area
int areaflags; //several area flags
int presencetype; //how a bot can be present in this area
int cluster; //cluster the area belongs to, if negative it's a portal
int clusterareanum; //number of the area in the cluster
int numreachableareas; //number of reachable areas from this one
int firstreachablearea; //first reachable area in the reachable area index
} aas_areasettings_t;
//cluster portal
typedef struct aas_portal_s
{
int areanum; //area that is the actual portal
int frontcluster; //cluster at front of portal
int backcluster; //cluster at back of portal
int clusterareanum[2]; //number of the area in the front and back cluster
} aas_portal_t;
//cluster portal index
typedef int aas_portalindex_t;
//cluster
typedef struct aas_cluster_s
{
int numareas; //number of areas in the cluster
int numreachabilityareas; //number of areas with reachabilities
int numportals; //number of cluster portals
int firstportal; //first cluster portal in the index
} aas_cluster_t;
//============ 3d definition ============
typedef vec3_t aas_vertex_t;
//just a plane in the third dimension
typedef struct aas_plane_s
{
vec3_t normal; //normal vector of the plane
float dist; //distance of the plane (normal vector * distance = point in plane)
int type;
} aas_plane_t;
//edge
typedef struct aas_edge_s
{
int v[2]; //numbers of the vertexes of this edge
} aas_edge_t;
//edge index, negative if vertexes are reversed
typedef int aas_edgeindex_t;
//a face bounds an area, often it will also seperate two areas
typedef struct aas_face_s
{
int planenum; //number of the plane this face is in
int faceflags; //face flags (no use to create face settings for just this field)
int numedges; //number of edges in the boundary of the face
int firstedge; //first edge in the edge index
int frontarea; //area at the front of this face
int backarea; //area at the back of this face
} aas_face_t;
//face index, stores a negative index if backside of face
typedef int aas_faceindex_t;
//area with a boundary of faces
typedef struct aas_area_s
{
int areanum; //number of this area
//3d definition
int numfaces; //number of faces used for the boundary of the area
int firstface; //first face in the face index used for the boundary of the area
vec3_t mins; //mins of the area
vec3_t maxs; //maxs of the area
vec3_t center; //'center' of the area
} aas_area_t;
//nodes of the bsp tree
typedef struct aas_node_s
{
int planenum;
int children[2]; //child nodes of this node, or areas as leaves when negative
//when a child is zero it's a solid leaf
} aas_node_t;
//=========== aas file ===============
//header lump
typedef struct
{
int fileofs;
int filelen;
} aas_lump_t;
//aas file header
typedef struct aas_header_s
{
int ident;
int version;
int bspchecksum;
//data entries
aas_lump_t lumps[AAS_LUMPS];
} aas_header_t;
//====== additional information ======
/*
- when a node child is a solid leaf the node child number is zero
- two adjacent areas (sharing a plane at opposite sides) share a face
this face is a portal between the areas
- when an area uses a face from the faceindex with a positive index
then the face plane normal points into the area
- the face edges are stored counter clockwise using the edgeindex
- two adjacent convex areas (sharing a face) only share One face
this is a simple result of the areas being convex
- the areas can't have a mixture of ground and gap faces
other mixtures of faces in one area are allowed
- areas with the AREACONTENTS_CLUSTERPORTAL in the settings have
the cluster number set to the negative portal number
- edge zero is a dummy
- face zero is a dummy
- area zero is a dummy
- node zero is a dummy
*/

221
code/botlib/be_aas.h Normal file
View File

@@ -0,0 +1,221 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: be_aas.h
*
* desc: Area Awareness System, stuff exported to the AI
*
* $Archive: /source/code/botlib/be_aas.h $
*
*****************************************************************************/
#ifndef MAX_STRINGFIELD
#define MAX_STRINGFIELD 80
#endif
//travel flags
#define TFL_INVALID 0x00000001 //traveling temporary not possible
#define TFL_WALK 0x00000002 //walking
#define TFL_CROUCH 0x00000004 //crouching
#define TFL_BARRIERJUMP 0x00000008 //jumping onto a barrier
#define TFL_JUMP 0x00000010 //jumping
#define TFL_LADDER 0x00000020 //climbing a ladder
#define TFL_WALKOFFLEDGE 0x00000080 //walking of a ledge
#define TFL_SWIM 0x00000100 //swimming
#define TFL_WATERJUMP 0x00000200 //jumping out of the water
#define TFL_TELEPORT 0x00000400 //teleporting
#define TFL_ELEVATOR 0x00000800 //elevator
#define TFL_ROCKETJUMP 0x00001000 //rocket jumping
#define TFL_BFGJUMP 0x00002000 //bfg jumping
#define TFL_GRAPPLEHOOK 0x00004000 //grappling hook
#define TFL_DOUBLEJUMP 0x00008000 //double jump
#define TFL_RAMPJUMP 0x00010000 //ramp jump
#define TFL_STRAFEJUMP 0x00020000 //strafe jump
#define TFL_JUMPPAD 0x00040000 //jump pad
#define TFL_AIR 0x00080000 //travel through air
#define TFL_WATER 0x00100000 //travel through water
#define TFL_SLIME 0x00200000 //travel through slime
#define TFL_LAVA 0x00400000 //travel through lava
#define TFL_DONOTENTER 0x00800000 //travel through donotenter area
#define TFL_FUNCBOB 0x01000000 //func bobbing
#define TFL_FLIGHT 0x02000000 //flight
#define TFL_BRIDGE 0x04000000 //move over a bridge
//
#define TFL_NOTTEAM1 0x08000000 //not team 1
#define TFL_NOTTEAM2 0x10000000 //not team 2
//default travel flags
#define TFL_DEFAULT TFL_WALK|TFL_CROUCH|TFL_BARRIERJUMP|\
TFL_JUMP|TFL_LADDER|\
TFL_WALKOFFLEDGE|TFL_SWIM|TFL_WATERJUMP|\
TFL_TELEPORT|TFL_ELEVATOR|\
TFL_AIR|TFL_WATER|TFL_JUMPPAD|TFL_FUNCBOB
typedef enum
{
SOLID_NOT, // no interaction with other objects
SOLID_TRIGGER, // only touch when inside, after moving
SOLID_BBOX, // touch on edge
SOLID_BSP // bsp clip, touch on edge
} solid_t;
//a trace is returned when a box is swept through the AAS world
typedef struct aas_trace_s
{
qboolean startsolid; // if true, the initial point was in a solid area
float fraction; // time completed, 1.0 = didn't hit anything
vec3_t endpos; // final position
int ent; // entity blocking the trace
int lastarea; // last area the trace was in (zero if none)
int area; // area blocking the trace (zero if none)
int planenum; // number of the plane that was hit
} aas_trace_t;
/* Defined in botlib.h
//bsp_trace_t hit surface
typedef struct bsp_surface_s
{
char name[16];
int flags;
int value;
} bsp_surface_t;
//a trace is returned when a box is swept through the BSP world
typedef struct bsp_trace_s
{
qboolean allsolid; // if true, plane is not valid
qboolean startsolid; // if true, the initial point was in a solid area
float fraction; // time completed, 1.0 = didn't hit anything
vec3_t endpos; // final position
cplane_t plane; // surface normal at impact
float exp_dist; // expanded plane distance
int sidenum; // number of the brush side hit
bsp_surface_t surface; // hit surface
int contents; // contents on other side of surface hit
int ent; // number of entity hit
} bsp_trace_t;
//
*/
//entity info
typedef struct aas_entityinfo_s
{
int valid; // true if updated this frame
int type; // entity type
int flags; // entity flags
float ltime; // local time
float update_time; // time between last and current update
int number; // number of the entity
vec3_t origin; // origin of the entity
vec3_t angles; // angles of the model
vec3_t old_origin; // for lerping
vec3_t lastvisorigin; // last visible origin
vec3_t mins; // bounding box minimums
vec3_t maxs; // bounding box maximums
int groundent; // ground entity
int solid; // solid type
int modelindex; // model used
int modelindex2; // weapons, CTF flags, etc
int frame; // model frame number
int event; // impulse events -- muzzle flashes, footsteps, etc
int eventParm; // even parameter
int powerups; // bit flags
int weapon; // determines weapon and flash model, etc
int legsAnim; // mask off ANIM_TOGGLEBIT
int torsoAnim; // mask off ANIM_TOGGLEBIT
} aas_entityinfo_t;
// area info
typedef struct aas_areainfo_s
{
int contents;
int flags;
int presencetype;
int cluster;
vec3_t mins;
vec3_t maxs;
vec3_t center;
} aas_areainfo_t;
// client movement prediction stop events, stop as soon as:
#define SE_NONE 0
#define SE_HITGROUND 1 // the ground is hit
#define SE_LEAVEGROUND 2 // there's no ground
#define SE_ENTERWATER 4 // water is entered
#define SE_ENTERSLIME 8 // slime is entered
#define SE_ENTERLAVA 16 // lava is entered
#define SE_HITGROUNDDAMAGE 32 // the ground is hit with damage
#define SE_GAP 64 // there's a gap
#define SE_TOUCHJUMPPAD 128 // touching a jump pad area
#define SE_TOUCHTELEPORTER 256 // touching teleporter
#define SE_ENTERAREA 512 // the given stoparea is entered
#define SE_HITGROUNDAREA 1024 // a ground face in the area is hit
#define SE_HITBOUNDINGBOX 2048 // hit the specified bounding box
#define SE_TOUCHCLUSTERPORTAL 4096 // touching a cluster portal
typedef struct aas_clientmove_s
{
vec3_t endpos; //position at the end of movement prediction
int endarea; //area at end of movement prediction
vec3_t velocity; //velocity at the end of movement prediction
aas_trace_t trace; //last trace
int presencetype; //presence type at end of movement prediction
int stopevent; //event that made the prediction stop
int endcontents; //contents at the end of movement prediction
float time; //time predicted ahead
int frames; //number of frames predicted ahead
} aas_clientmove_t;
// alternate route goals
#define ALTROUTEGOAL_ALL 1
#define ALTROUTEGOAL_CLUSTERPORTALS 2
#define ALTROUTEGOAL_VIEWPORTALS 4
typedef struct aas_altroutegoal_s
{
vec3_t origin;
int areanum;
unsigned short starttraveltime;
unsigned short goaltraveltime;
unsigned short extratraveltime;
} aas_altroutegoal_t;
// route prediction stop events
#define RSE_NONE 0
#define RSE_NOROUTE 1 //no route to goal
#define RSE_USETRAVELTYPE 2 //stop as soon as on of the given travel types is used
#define RSE_ENTERCONTENTS 4 //stop when entering the given contents
#define RSE_ENTERAREA 8 //stop when entering the given area
typedef struct aas_predictroute_s
{
vec3_t endpos; //position at the end of movement prediction
int endarea; //area at end of movement prediction
int stopevent; //event that made the prediction stop
int endcontents; //contents at the end of movement prediction
int endtravelflags; //end travel flags
int numareas; //number of areas predicted ahead
int time; //time predicted ahead (in hundreth of a sec)
} aas_predictroute_t;

89
code/botlib/be_aas_bsp.h Normal file
View File

@@ -0,0 +1,89 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_bsp.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_bsp.h $
*
*****************************************************************************/
#ifdef AASINTERN
//loads the given BSP file
int AAS_LoadBSPFile(void);
//dump the loaded BSP data
void AAS_DumpBSPData(void);
//unlink the given entity from the bsp tree leaves
void AAS_UnlinkFromBSPLeaves(bsp_link_t *leaves);
//link the given entity to the bsp tree leaves of the given model
bsp_link_t *AAS_BSPLinkEntity(vec3_t absmins,
vec3_t absmaxs,
int entnum,
int modelnum);
//calculates collision with given entity
qboolean AAS_EntityCollision(int entnum,
vec3_t start,
vec3_t boxmins,
vec3_t boxmaxs,
vec3_t end,
int contentmask,
bsp_trace_t *trace);
//for debugging
void AAS_PrintFreeBSPLinks(char *str);
//
#endif //AASINTERN
#define MAX_EPAIRKEY 128
//trace through the world
bsp_trace_t AAS_Trace( vec3_t start,
vec3_t mins,
vec3_t maxs,
vec3_t end,
int passent,
int contentmask);
//returns the contents at the given point
int AAS_PointContents(vec3_t point);
//returns true when p2 is in the PVS of p1
qboolean AAS_inPVS(vec3_t p1, vec3_t p2);
//returns true when p2 is in the PHS of p1
qboolean AAS_inPHS(vec3_t p1, vec3_t p2);
//returns true if the given areas are connected
qboolean AAS_AreasConnected(int area1, int area2);
//creates a list with entities totally or partly within the given box
int AAS_BoxEntities(vec3_t absmins, vec3_t absmaxs, int *list, int maxcount);
//gets the mins, maxs and origin of a BSP model
void AAS_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t mins, vec3_t maxs, vec3_t origin);
//handle to the next bsp entity
int AAS_NextBSPEntity(int ent);
//return the value of the BSP epair key
int AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size);
//get a vector for the BSP epair key
int AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v);
//get a float for the BSP epair key
int AAS_FloatForBSPEpairKey(int ent, char *key, float *value);
//get an integer for the BSP epair key
int AAS_IntForBSPEpairKey(int ent, char *key, int *value);

View File

@@ -0,0 +1,38 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_cluster.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_cluster.h $
*
*****************************************************************************/
#ifdef AASINTERN
//initialize the AAS clustering
void AAS_InitClustering(void);
//
void AAS_SetViewPortalsAsClusterPortals(void);
#endif //AASINTERN

View File

@@ -0,0 +1,62 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_debug.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_debug.h $
*
*****************************************************************************/
//clear the shown debug lines
void AAS_ClearShownDebugLines(void);
//
void AAS_ClearShownPolygons(void);
//show a debug line
void AAS_DebugLine(vec3_t start, vec3_t end, int color);
//show a permenent line
void AAS_PermanentLine(vec3_t start, vec3_t end, int color);
//show a permanent cross
void AAS_DrawPermanentCross(vec3_t origin, float size, int color);
//draw a cross in the plane
void AAS_DrawPlaneCross(vec3_t point, vec3_t normal, float dist, int type, int color);
//show a bounding box
void AAS_ShowBoundingBox(vec3_t origin, vec3_t mins, vec3_t maxs);
//show a face
void AAS_ShowFace(int facenum);
//show an area
void AAS_ShowArea(int areanum, int groundfacesonly);
//
void AAS_ShowAreaPolygons(int areanum, int color, int groundfacesonly);
//draw a cros
void AAS_DrawCross(vec3_t origin, float size, int color);
//print the travel type
void AAS_PrintTravelType(int traveltype);
//draw an arrow
void AAS_DrawArrow(vec3_t start, vec3_t end, int linecolor, int arrowcolor);
//visualize the given reachability
void AAS_ShowReachability(struct aas_reachability_s *reach);
//show the reachable areas from the given area
void AAS_ShowReachableAreas(int areanum);

306
code/botlib/be_aas_def.h Normal file
View File

@@ -0,0 +1,306 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_def.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_def.h $
*
*****************************************************************************/
//debugging on
#define AAS_DEBUG
#define MAX_CLIENTS 64
#define MAX_MODELS 256 // these are sent over the net as 8 bits
#define MAX_SOUNDS 256 // so they cannot be blindly increased
#define MAX_CONFIGSTRINGS 1024
#define CS_SCORES 32
#define CS_MODELS (CS_SCORES+MAX_CLIENTS)
#define CS_SOUNDS (CS_MODELS+MAX_MODELS)
#define DF_AASENTNUMBER(x) (x - aasworld.entities)
#define DF_NUMBERAASENT(x) (&aasworld.entities[x])
#define DF_AASENTCLIENT(x) (x - aasworld.entities - 1)
#define DF_CLIENTAASENT(x) (&aasworld.entities[x + 1])
#ifndef MAX_PATH
#define MAX_PATH MAX_QPATH
#endif
//string index (for model, sound and image index)
typedef struct aas_stringindex_s
{
int numindexes;
char **index;
} aas_stringindex_t;
//structure to link entities to areas and areas to entities
typedef struct aas_link_s
{
int entnum;
int areanum;
struct aas_link_s *next_ent, *prev_ent;
struct aas_link_s *next_area, *prev_area;
} aas_link_t;
//structure to link entities to leaves and leaves to entities
typedef struct bsp_link_s
{
int entnum;
int leafnum;
struct bsp_link_s *next_ent, *prev_ent;
struct bsp_link_s *next_leaf, *prev_leaf;
} bsp_link_t;
typedef struct bsp_entdata_s
{
vec3_t origin;
vec3_t angles;
vec3_t absmins;
vec3_t absmaxs;
int solid;
int modelnum;
} bsp_entdata_t;
//entity
typedef struct aas_entity_s
{
//entity info
aas_entityinfo_t i;
//links into the AAS areas
aas_link_t *areas;
//links into the BSP leaves
bsp_link_t *leaves;
} aas_entity_t;
typedef struct aas_settings_s
{
vec3_t phys_gravitydirection;
float phys_friction;
float phys_stopspeed;
float phys_gravity;
float phys_waterfriction;
float phys_watergravity;
float phys_maxvelocity;
float phys_maxwalkvelocity;
float phys_maxcrouchvelocity;
float phys_maxswimvelocity;
float phys_walkaccelerate;
float phys_airaccelerate;
float phys_swimaccelerate;
float phys_maxstep;
float phys_maxsteepness;
float phys_maxwaterjump;
float phys_maxbarrier;
float phys_jumpvel;
float phys_falldelta5;
float phys_falldelta10;
float rs_waterjump;
float rs_teleport;
float rs_barrierjump;
float rs_startcrouch;
float rs_startgrapple;
float rs_startwalkoffledge;
float rs_startjump;
float rs_rocketjump;
float rs_bfgjump;
float rs_jumppad;
float rs_aircontrolledjumppad;
float rs_funcbob;
float rs_startelevator;
float rs_falldamage5;
float rs_falldamage10;
float rs_maxfallheight;
float rs_maxjumpfallheight;
} aas_settings_t;
#define CACHETYPE_PORTAL 0
#define CACHETYPE_AREA 1
//routing cache
typedef struct aas_routingcache_s
{
byte type; //portal or area cache
float time; //last time accessed or updated
int size; //size of the routing cache
int cluster; //cluster the cache is for
int areanum; //area the cache is created for
vec3_t origin; //origin within the area
float starttraveltime; //travel time to start with
int travelflags; //combinations of the travel flags
struct aas_routingcache_s *prev, *next;
struct aas_routingcache_s *time_prev, *time_next;
unsigned char *reachabilities; //reachabilities used for routing
unsigned short int traveltimes[1]; //travel time for every area (variable sized)
} aas_routingcache_t;
//fields for the routing algorithm
typedef struct aas_routingupdate_s
{
int cluster;
int areanum; //area number of the update
vec3_t start; //start point the area was entered
unsigned short int tmptraveltime; //temporary travel time
unsigned short int *areatraveltimes; //travel times within the area
qboolean inlist; //true if the update is in the list
struct aas_routingupdate_s *next;
struct aas_routingupdate_s *prev;
} aas_routingupdate_t;
//reversed reachability link
typedef struct aas_reversedlink_s
{
int linknum; //the aas_areareachability_t
int areanum; //reachable from this area
struct aas_reversedlink_s *next; //next link
} aas_reversedlink_t;
//reversed area reachability
typedef struct aas_reversedreachability_s
{
int numlinks;
aas_reversedlink_t *first;
} aas_reversedreachability_t;
//areas a reachability goes through
typedef struct aas_reachabilityareas_s
{
int firstarea, numareas;
} aas_reachabilityareas_t;
typedef struct aas_s
{
int loaded; //true when an AAS file is loaded
int initialized; //true when AAS has been initialized
int savefile; //set true when file should be saved
int bspchecksum;
//current time
float time;
int numframes;
//name of the aas file
char filename[MAX_PATH];
char mapname[MAX_PATH];
//bounding boxes
int numbboxes;
aas_bbox_t *bboxes;
//vertexes
int numvertexes;
aas_vertex_t *vertexes;
//planes
int numplanes;
aas_plane_t *planes;
//edges
int numedges;
aas_edge_t *edges;
//edge index
int edgeindexsize;
aas_edgeindex_t *edgeindex;
//faces
int numfaces;
aas_face_t *faces;
//face index
int faceindexsize;
aas_faceindex_t *faceindex;
//convex areas
int numareas;
aas_area_t *areas;
//convex area settings
int numareasettings;
aas_areasettings_t *areasettings;
//reachablity list
int reachabilitysize;
aas_reachability_t *reachability;
//nodes of the bsp tree
int numnodes;
aas_node_t *nodes;
//cluster portals
int numportals;
aas_portal_t *portals;
//cluster portal index
int portalindexsize;
aas_portalindex_t *portalindex;
//clusters
int numclusters;
aas_cluster_t *clusters;
//
int numreachabilityareas;
float reachabilitytime;
//enities linked in the areas
aas_link_t *linkheap; //heap with link structures
int linkheapsize; //size of the link heap
aas_link_t *freelinks; //first free link
aas_link_t **arealinkedentities; //entities linked into areas
//entities
int maxentities;
int maxclients;
aas_entity_t *entities;
//string indexes
char *configstrings[MAX_CONFIGSTRINGS];
int indexessetup;
//index to retrieve travel flag for a travel type
int travelflagfortype[MAX_TRAVELTYPES];
//travel flags for each area based on contents
int *areacontentstravelflags;
//routing update
aas_routingupdate_t *areaupdate;
aas_routingupdate_t *portalupdate;
//number of routing updates during a frame (reset every frame)
int frameroutingupdates;
//reversed reachability links
aas_reversedreachability_t *reversedreachability;
//travel times within the areas
unsigned short ***areatraveltimes;
//array of size numclusters with cluster cache
aas_routingcache_t ***clusterareacache;
aas_routingcache_t **portalcache;
//cache list sorted on time
aas_routingcache_t *oldestcache; // start of cache list sorted on time
aas_routingcache_t *newestcache; // end of cache list sorted on time
//maximum travel time through portal areas
int *portalmaxtraveltimes;
//areas the reachabilities go through
int *reachabilityareaindex;
aas_reachabilityareas_t *reachabilityareas;
} aas_t;
#define AASINTERN
#ifndef BSPCINCLUDE
#include "be_aas_main.h"
#include "be_aas_entity.h"
#include "be_aas_sample.h"
#include "be_aas_cluster.h"
#include "be_aas_reach.h"
#include "be_aas_route.h"
#include "be_aas_routealt.h"
#include "be_aas_debug.h"
#include "be_aas_file.h"
#include "be_aas_optimize.h"
#include "be_aas_bsp.h"
#include "be_aas_move.h"
#endif //BSPCINCLUDE

View File

@@ -0,0 +1,63 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_entity.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_entity.h $
*
*****************************************************************************/
#ifdef AASINTERN
//invalidates all entity infos
void AAS_InvalidateEntities(void);
//unlink not updated entities
void AAS_UnlinkInvalidEntities(void);
//resets the entity AAS and BSP links (sets areas and leaves pointers to NULL)
void AAS_ResetEntityLinks(void);
//updates an entity
int AAS_UpdateEntity(int ent, bot_entitystate_t *state);
//gives the entity data used for collision detection
void AAS_EntityBSPData(int entnum, bsp_entdata_t *entdata);
#endif //AASINTERN
//returns the size of the entity bounding box in mins and maxs
void AAS_EntitySize(int entnum, vec3_t mins, vec3_t maxs);
//returns the BSP model number of the entity
int AAS_EntityModelNum(int entnum);
//returns the origin of an entity with the given model number
int AAS_OriginOfMoverWithModelNum(int modelnum, vec3_t origin);
//returns the best reachable area the entity is situated in
int AAS_BestReachableEntityArea(int entnum);
//returns the info of the given entity
void AAS_EntityInfo(int entnum, aas_entityinfo_t *info);
//returns the next entity
int AAS_NextEntity(int entnum);
//returns the origin of the entity
void AAS_EntityOrigin(int entnum, vec3_t origin);
//returns the entity type
int AAS_EntityType(int entnum);
//returns the model index of the entity
int AAS_EntityModelindex(int entnum);

42
code/botlib/be_aas_file.h Normal file
View File

@@ -0,0 +1,42 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_file.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_file.h $
*
*****************************************************************************/
#ifdef AASINTERN
//loads the AAS file with the given name
int AAS_LoadAASFile(char *filename);
//writes an AAS file with the given name
qboolean AAS_WriteAASFile(char *filename);
//dumps the loaded AAS data
void AAS_DumpAASData(void);
//print AAS file information
void AAS_FileInfo(void);
#endif //AASINTERN

View File

@@ -0,0 +1,47 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_funcs.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_funcs.h $
*
*****************************************************************************/
#ifndef BSPCINCLUDE
#include "be_aas_main.h"
#include "be_aas_entity.h"
#include "be_aas_sample.h"
#include "be_aas_cluster.h"
#include "be_aas_reach.h"
#include "be_aas_route.h"
#include "be_aas_routealt.h"
#include "be_aas_debug.h"
#include "be_aas_file.h"
#include "be_aas_optimize.h"
#include "be_aas_bsp.h"
#include "be_aas_move.h"
#endif //BSPCINCLUDE

61
code/botlib/be_aas_main.h Normal file
View File

@@ -0,0 +1,61 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_main.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_main.h $
*
*****************************************************************************/
#ifdef AASINTERN
extern aas_t aasworld;
//AAS error message
void QDECL AAS_Error(char *fmt, ...);
//set AAS initialized
void AAS_SetInitialized(void);
//setup AAS with the given number of entities and clients
int AAS_Setup(void);
//shutdown AAS
void AAS_Shutdown(void);
//start a new map
int AAS_LoadMap(const char *mapname);
//start a new time frame
int AAS_StartFrame(float time);
#endif //AASINTERN
//returns true if AAS is initialized
int AAS_Initialized(void);
//returns true if the AAS file is loaded
int AAS_Loaded(void);
//returns the model name from the given index
char *AAS_ModelFromIndex(int index);
//returns the index from the given model name
int AAS_IndexFromModel(char *modelname);
//returns the current time
float AAS_Time(void);
//
void AAS_ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vEnd, vec3_t vProj );

71
code/botlib/be_aas_move.h Normal file
View File

@@ -0,0 +1,71 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_move.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_move.h $
*
*****************************************************************************/
#ifdef AASINTERN
extern aas_settings_t aassettings;
#endif //AASINTERN
//movement prediction
int AAS_PredictClientMovement(struct aas_clientmove_s *move,
int entnum, vec3_t origin,
int presencetype, int onground,
vec3_t velocity, vec3_t cmdmove,
int cmdframes,
int maxframes, float frametime,
int stopevent, int stopareanum, int visualize);
//predict movement until bounding box is hit
int AAS_ClientMovementHitBBox(struct aas_clientmove_s *move,
int entnum, vec3_t origin,
int presencetype, int onground,
vec3_t velocity, vec3_t cmdmove,
int cmdframes,
int maxframes, float frametime,
vec3_t mins, vec3_t maxs, int visualize);
//returns true if on the ground at the given origin
int AAS_OnGround(vec3_t origin, int presencetype, int passent);
//returns true if swimming at the given origin
int AAS_Swimming(vec3_t origin);
//returns the jump reachability run start point
void AAS_JumpReachRunStart(struct aas_reachability_s *reach, vec3_t runstart);
//returns true if against a ladder at the given origin
int AAS_AgainstLadder(vec3_t origin);
//rocket jump Z velocity when rocket-jumping at origin
float AAS_RocketJumpZVelocity(vec3_t origin);
//bfg jump Z velocity when bfg-jumping at origin
float AAS_BFGJumpZVelocity(vec3_t origin);
//calculates the horizontal velocity needed for a jump and returns true this velocity could be calculated
int AAS_HorizontalVelocityForJump(float zvel, vec3_t start, vec3_t end, float *velocity);
//
void AAS_SetMovedir(vec3_t angles, vec3_t movedir);
//
int AAS_DropToFloor(vec3_t origin, vec3_t mins, vec3_t maxs);
//
void AAS_InitSettings(void);

View File

@@ -0,0 +1,33 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_optimize.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_optimize.h $
*
*****************************************************************************/
void AAS_Optimize(void);

View File

@@ -0,0 +1,68 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_reach.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_reach.h $
*
*****************************************************************************/
#ifdef AASINTERN
//initialize calculating the reachabilities
void AAS_InitReachability(void);
//continue calculating the reachabilities
int AAS_ContinueInitReachability(float time);
//
int AAS_BestReachableLinkArea(aas_link_t *areas);
#endif //AASINTERN
//returns true if the are has reachabilities to other areas
int AAS_AreaReachability(int areanum);
//returns the best reachable area and goal origin for a bounding box at the given origin
int AAS_BestReachableArea(vec3_t origin, vec3_t mins, vec3_t maxs, vec3_t goalorigin);
//returns the best jumppad area from which the bbox at origin is reachable
int AAS_BestReachableFromJumpPadArea(vec3_t origin, vec3_t mins, vec3_t maxs);
//returns the next reachability using the given model
int AAS_NextModelReachability(int num, int modelnum);
//returns the total area of the ground faces of the given area
float AAS_AreaGroundFaceArea(int areanum);
//returns true if the area is crouch only
int AAS_AreaCrouch(int areanum);
//returns true if a player can swim in this area
int AAS_AreaSwim(int areanum);
//returns true if the area is filled with a liquid
int AAS_AreaLiquid(int areanum);
//returns true if the area contains lava
int AAS_AreaLava(int areanum);
//returns true if the area contains slime
int AAS_AreaSlime(int areanum);
//returns true if the area has one or more ground faces
int AAS_AreaGrounded(int areanum);
//returns true if the area has one or more ladder faces
int AAS_AreaLadder(int areanum);
//returns true if the area is a jump pad
int AAS_AreaJumpPad(int areanum);
//returns true if the area is donotenter
int AAS_AreaDoNotEnter(int areanum);

View File

@@ -0,0 +1,67 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_route.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_route.h $
*
*****************************************************************************/
#ifdef AASINTERN
//initialize the AAS routing
void AAS_InitRouting(void);
//free the AAS routing caches
void AAS_FreeRoutingCaches(void);
//returns the travel time from start to end in the given area
unsigned short int AAS_AreaTravelTime(int areanum, vec3_t start, vec3_t end);
//
void AAS_CreateAllRoutingCache(void);
void AAS_WriteRouteCache(void);
//
void AAS_RoutingInfo(void);
#endif //AASINTERN
//returns the travel flag for the given travel type
int AAS_TravelFlagForType(int traveltype);
//return the travel flag(s) for traveling through this area
int AAS_AreaContentsTravelFlags(int areanum);
//returns the index of the next reachability for the given area
int AAS_NextAreaReachability(int areanum, int reachnum);
//returns the reachability with the given index
void AAS_ReachabilityFromNum(int num, struct aas_reachability_s *reach);
//returns a random goal area and goal origin
int AAS_RandomGoalArea(int areanum, int travelflags, int *goalareanum, vec3_t goalorigin);
//enable or disable an area for routing
int AAS_EnableRoutingArea(int areanum, int enable);
//returns the travel time within the given area from start to end
unsigned short int AAS_AreaTravelTime(int areanum, vec3_t start, vec3_t end);
//returns the travel time from the area to the goal area using the given travel flags
int AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags);
//predict a route up to a stop event
int AAS_PredictRoute(struct aas_predictroute_s *route, int areanum, vec3_t origin,
int goalareanum, int travelflags, int maxareas, int maxtime,
int stopevent, int stopcontents, int stoptfl, int stopareanum);

View File

@@ -0,0 +1,40 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_routealt.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_routealt.h $
*
*****************************************************************************/
#ifdef AASINTERN
void AAS_InitAlternativeRouting(void);
void AAS_ShutdownAlternativeRouting(void);
#endif //AASINTERN
int AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags,
aas_altroutegoal_t *altroutegoals, int maxaltroutegoals,
int type);

View File

@@ -0,0 +1,69 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_aas_sample.h
*
* desc: AAS
*
* $Archive: /source/code/botlib/be_aas_sample.h $
*
*****************************************************************************/
#ifdef AASINTERN
void AAS_InitAASLinkHeap(void);
void AAS_InitAASLinkedEntities(void);
void AAS_FreeAASLinkHeap(void);
void AAS_FreeAASLinkedEntities(void);
aas_face_t *AAS_AreaGroundFace(int areanum, vec3_t point);
aas_face_t *AAS_TraceEndFace(aas_trace_t *trace);
aas_plane_t *AAS_PlaneFromNum(int planenum);
aas_link_t *AAS_AASLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum);
aas_link_t *AAS_LinkEntityClientBBox(vec3_t absmins, vec3_t absmaxs, int entnum, int presencetype);
qboolean AAS_PointInsideFace(int facenum, vec3_t point, float epsilon);
qboolean AAS_InsideFace(aas_face_t *face, vec3_t pnormal, vec3_t point, float epsilon);
void AAS_UnlinkFromAreas(aas_link_t *areas);
#endif //AASINTERN
//returns the mins and maxs of the bounding box for the given presence type
void AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs);
//returns the cluster the area is in (negative portal number if the area is a portal)
int AAS_AreaCluster(int areanum);
//returns the presence type(s) of the area
int AAS_AreaPresenceType(int areanum);
//returns the presence type(s) at the given point
int AAS_PointPresenceType(vec3_t point);
//returns the result of the trace of a client bbox
aas_trace_t AAS_TraceClientBBox(vec3_t start, vec3_t end, int presencetype, int passent);
//stores the areas the trace went through and returns the number of passed areas
int AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas);
//returns the areas the bounding box is in
int AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas);
//return area information
int AAS_AreaInfo( int areanum, aas_areainfo_t *info );
//returns the area the point is in
int AAS_PointAreaNum(vec3_t point);
//
int AAS_PointReachabilityAreaIndex( vec3_t point );
//returns the plane the given face is in
void AAS_FacePlane(int facenum, vec3_t normal, float *dist);

48
code/botlib/be_ai_char.h Normal file
View File

@@ -0,0 +1,48 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: be_ai_char.h
*
* desc: bot characters
*
* $Archive: /source/code/botlib/be_ai_char.h $
*
*****************************************************************************/
//loads a bot character from a file
int BotLoadCharacter(char *charfile, float skill);
//frees a bot character
void BotFreeCharacter(int character);
//returns a float characteristic
float Characteristic_Float(int character, int index);
//returns a bounded float characteristic
float Characteristic_BFloat(int character, int index, float min, float max);
//returns an integer characteristic
int Characteristic_Integer(int character, int index);
//returns a bounded integer characteristic
int Characteristic_BInteger(int character, int index, int min, int max);
//returns a string characteristic
void Characteristic_String(int character, int index, char *buf, int size);
//free cached bot characters
void BotShutdownCharacters(void);

113
code/botlib/be_ai_chat.h Normal file
View File

@@ -0,0 +1,113 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: be_ai_chat.h
*
* desc: char AI
*
* $Archive: /source/code/botlib/be_ai_chat.h $
*
*****************************************************************************/
#define MAX_MESSAGE_SIZE 256
#define MAX_CHATTYPE_NAME 32
#define MAX_MATCHVARIABLES 8
#define CHAT_GENDERLESS 0
#define CHAT_GENDERFEMALE 1
#define CHAT_GENDERMALE 2
#define CHAT_ALL 0
#define CHAT_TEAM 1
#define CHAT_TELL 2
//a console message
typedef struct bot_consolemessage_s
{
int handle;
float time; //message time
int type; //message type
char message[MAX_MESSAGE_SIZE]; //message
struct bot_consolemessage_s *prev, *next; //prev and next in list
} bot_consolemessage_t;
//match variable
typedef struct bot_matchvariable_s
{
char offset;
int length;
} bot_matchvariable_t;
//returned to AI when a match is found
typedef struct bot_match_s
{
char string[MAX_MESSAGE_SIZE];
int type;
int subtype;
bot_matchvariable_t variables[MAX_MATCHVARIABLES];
} bot_match_t;
//setup the chat AI
int BotSetupChatAI(void);
//shutdown the chat AI
void BotShutdownChatAI(void);
//returns the handle to a newly allocated chat state
int BotAllocChatState(void);
//frees the chatstate
void BotFreeChatState(int handle);
//adds a console message to the chat state
void BotQueueConsoleMessage(int chatstate, int type, char *message);
//removes the console message from the chat state
void BotRemoveConsoleMessage(int chatstate, int handle);
//returns the next console message from the state
int BotNextConsoleMessage(int chatstate, bot_consolemessage_t *cm);
//returns the number of console messages currently stored in the state
int BotNumConsoleMessages(int chatstate);
//selects a chat message of the given type
void BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7);
//returns the number of initial chat messages of the given type
int BotNumInitialChats(int chatstate, char *type);
//find and select a reply for the given message
int BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7);
//returns the length of the currently selected chat message
int BotChatLength(int chatstate);
//enters the selected chat message
void BotEnterChat(int chatstate, int clientto, int sendto);
//get the chat message ready to be output
void BotGetChatMessage(int chatstate, char *buf, int size);
//checks if the first string contains the second one, returns index into first string or -1 if not found
int StringContains(char *str1, char *str2, int casesensitive);
//finds a match for the given string using the match templates
int BotFindMatch(char *str, bot_match_t *match, unsigned long int context);
//returns a variable from a match
void BotMatchVariable(bot_match_t *match, int variable, char *buf, int size);
//unify all the white spaces in the string
void UnifyWhiteSpaces(char *string);
//replace all the context related synonyms in the string
void BotReplaceSynonyms(char *string, unsigned long int context);
//loads a chat file for the chat state
int BotLoadChatFile(int chatstate, char *chatfile, char *chatname);
//store the gender of the bot in the chat state
void BotSetChatGender(int chatstate, int gender);
//store the bot name in the chat state
void BotSetChatName(int chatstate, char *name, int client);

33
code/botlib/be_ai_gen.h Normal file
View File

@@ -0,0 +1,33 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: be_ai_gen.h
*
* desc: genetic selection
*
* $Archive: /source/code/botlib/be_ai_gen.h $
*
*****************************************************************************/
int GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child);

118
code/botlib/be_ai_goal.h Normal file
View File

@@ -0,0 +1,118 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: be_ai_goal.h
*
* desc: goal AI
*
* $Archive: /source/code/botlib/be_ai_goal.h $
*
*****************************************************************************/
#define MAX_AVOIDGOALS 256
#define MAX_GOALSTACK 8
#define GFL_NONE 0
#define GFL_ITEM 1
#define GFL_ROAM 2
#define GFL_DROPPED 4
//a bot goal
typedef struct bot_goal_s
{
vec3_t origin; //origin of the goal
int areanum; //area number of the goal
vec3_t mins, maxs; //mins and maxs of the goal
int entitynum; //number of the goal entity
int number; //goal number
int flags; //goal flags
int iteminfo; //item information
} bot_goal_t;
//reset the whole goal state, but keep the item weights
void BotResetGoalState(int goalstate);
//reset avoid goals
void BotResetAvoidGoals(int goalstate);
//remove the goal with the given number from the avoid goals
void BotRemoveFromAvoidGoals(int goalstate, int number);
//push a goal onto the goal stack
void BotPushGoal(int goalstate, bot_goal_t *goal);
//pop a goal from the goal stack
void BotPopGoal(int goalstate);
//empty the bot's goal stack
void BotEmptyGoalStack(int goalstate);
//dump the avoid goals
void BotDumpAvoidGoals(int goalstate);
//dump the goal stack
void BotDumpGoalStack(int goalstate);
//get the name name of the goal with the given number
void BotGoalName(int number, char *name, int size);
//get the top goal from the stack
int BotGetTopGoal(int goalstate, bot_goal_t *goal);
//get the second goal on the stack
int BotGetSecondGoal(int goalstate, bot_goal_t *goal);
//choose the best long term goal item for the bot
int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags);
//choose the best nearby goal item for the bot
//the item may not be further away from the current bot position than maxtime
//also the travel time from the nearby goal towards the long term goal may not
//be larger than the travel time towards the long term goal from the current bot position
int BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags,
bot_goal_t *ltg, float maxtime);
//returns true if the bot touches the goal
int BotTouchingGoal(vec3_t origin, bot_goal_t *goal);
//returns true if the goal should be visible but isn't
int BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, bot_goal_t *goal);
//search for a goal for the given classname, the index can be used
//as a start point for the search when multiple goals are available with that same classname
int BotGetLevelItemGoal(int index, char *classname, bot_goal_t *goal);
//get the next camp spot in the map
int BotGetNextCampSpotGoal(int num, bot_goal_t *goal);
//get the map location with the given name
int BotGetMapLocationGoal(char *name, bot_goal_t *goal);
//returns the avoid goal time
float BotAvoidGoalTime(int goalstate, int number);
//set the avoid goal time
void BotSetAvoidGoalTime(int goalstate, int number, float avoidtime);
//initializes the items in the level
void BotInitLevelItems(void);
//regularly update dynamic entity items (dropped weapons, flags etc.)
void BotUpdateEntityItems(void);
//interbreed the goal fuzzy logic
void BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child);
//save the goal fuzzy logic to disk
void BotSaveGoalFuzzyLogic(int goalstate, char *filename);
//mutate the goal fuzzy logic
void BotMutateGoalFuzzyLogic(int goalstate, float range);
//loads item weights for the bot
int BotLoadItemWeights(int goalstate, char *filename);
//frees the item weights of the bot
void BotFreeItemWeights(int goalstate);
//returns the handle of a newly allocated goal state
int BotAllocGoalState(int client);
//free the given goal state
void BotFreeGoalState(int handle);
//setup the goal AI
int BotSetupGoalAI(void);
//shut down the goal AI
void BotShutdownGoalAI(void);

142
code/botlib/be_ai_move.h Normal file
View File

@@ -0,0 +1,142 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: be_ai_move.h
*
* desc: movement AI
*
* $Archive: /source/code/botlib/be_ai_move.h $
*
*****************************************************************************/
//movement types
#define MOVE_WALK 1
#define MOVE_CROUCH 2
#define MOVE_JUMP 4
#define MOVE_GRAPPLE 8
#define MOVE_ROCKETJUMP 16
#define MOVE_BFGJUMP 32
//move flags
#define MFL_BARRIERJUMP 1 //bot is performing a barrier jump
#define MFL_ONGROUND 2 //bot is in the ground
#define MFL_SWIMMING 4 //bot is swimming
#define MFL_AGAINSTLADDER 8 //bot is against a ladder
#define MFL_WATERJUMP 16 //bot is waterjumping
#define MFL_TELEPORTED 32 //bot is being teleported
#define MFL_GRAPPLEPULL 64 //bot is being pulled by the grapple
#define MFL_ACTIVEGRAPPLE 128 //bot is using the grapple hook
#define MFL_GRAPPLERESET 256 //bot has reset the grapple
#define MFL_WALK 512 //bot should walk slowly
// move result flags
#define MOVERESULT_MOVEMENTVIEW 1 //bot uses view for movement
#define MOVERESULT_SWIMVIEW 2 //bot uses view for swimming
#define MOVERESULT_WAITING 4 //bot is waiting for something
#define MOVERESULT_MOVEMENTVIEWSET 8 //bot has set the view in movement code
#define MOVERESULT_MOVEMENTWEAPON 16 //bot uses weapon for movement
#define MOVERESULT_ONTOPOFOBSTACLE 32 //bot is ontop of obstacle
#define MOVERESULT_ONTOPOF_FUNCBOB 64 //bot is ontop of a func_bobbing
#define MOVERESULT_ONTOPOF_ELEVATOR 128 //bot is ontop of an elevator (func_plat)
#define MOVERESULT_BLOCKEDBYAVOIDSPOT 256 //bot is blocked by an avoid spot
//
#define MAX_AVOIDREACH 1
#define MAX_AVOIDSPOTS 32
// avoid spot types
#define AVOID_CLEAR 0 //clear all avoid spots
#define AVOID_ALWAYS 1 //avoid always
#define AVOID_DONTBLOCK 2 //never totally block
// restult types
#define RESULTTYPE_ELEVATORUP 1 //elevator is up
#define RESULTTYPE_WAITFORFUNCBOBBING 2 //waiting for func bobbing to arrive
#define RESULTTYPE_BADGRAPPLEPATH 4 //grapple path is obstructed
#define RESULTTYPE_INSOLIDAREA 8 //stuck in solid area, this is bad
//structure used to initialize the movement state
//the or_moveflags MFL_ONGROUND, MFL_TELEPORTED and MFL_WATERJUMP come from the playerstate
typedef struct bot_initmove_s
{
vec3_t origin; //origin of the bot
vec3_t velocity; //velocity of the bot
vec3_t viewoffset; //view offset
int entitynum; //entity number of the bot
int client; //client number of the bot
float thinktime; //time the bot thinks
int presencetype; //presencetype of the bot
vec3_t viewangles; //view angles of the bot
int or_moveflags; //values ored to the movement flags
} bot_initmove_t;
//NOTE: the ideal_viewangles are only valid if MFL_MOVEMENTVIEW is set
typedef struct bot_moveresult_s
{
int failure; //true if movement failed all together
int type; //failure or blocked type
int blocked; //true if blocked by an entity
int blockentity; //entity blocking the bot
int traveltype; //last executed travel type
int flags; //result flags
int weapon; //weapon used for movement
vec3_t movedir; //movement direction
vec3_t ideal_viewangles; //ideal viewangles for the movement
} bot_moveresult_t;
#define bot_moveresult_t_cleared(x) bot_moveresult_t (x) = {0, 0, 0, 0, 0, 0, 0, {0, 0, 0}, {0, 0, 0}}
typedef struct bot_avoidspot_s
{
vec3_t origin;
float radius;
int type;
} bot_avoidspot_t;
//resets the whole move state
void BotResetMoveState(int movestate);
//moves the bot to the given goal
void BotMoveToGoal(bot_moveresult_t *result, int movestate, bot_goal_t *goal, int travelflags);
//moves the bot in the specified direction using the specified type of movement
int BotMoveInDirection(int movestate, vec3_t dir, float speed, int type);
//reset avoid reachability
void BotResetAvoidReach(int movestate);
//resets the last avoid reachability
void BotResetLastAvoidReach(int movestate);
//returns a reachability area if the origin is in one
int BotReachabilityArea(vec3_t origin, int client);
//view target based on movement
int BotMovementViewTarget(int movestate, bot_goal_t *goal, int travelflags, float lookahead, vec3_t target);
//predict the position of a player based on movement towards a goal
int BotPredictVisiblePosition(vec3_t origin, int areanum, bot_goal_t *goal, int travelflags, vec3_t target);
//returns the handle of a newly allocated movestate
int BotAllocMoveState(void);
//frees the movestate with the given handle
void BotFreeMoveState(int handle);
//initialize movement state before performing any movement
void BotInitMoveState(int handle, bot_initmove_t *initmove);
//add a spot to avoid (if type == AVOID_CLEAR all spots are removed)
void BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type);
//must be called every map change
void BotSetBrushModelTypes(void);
//setup movement AI
int BotSetupMoveAI(void);
//shutdown movement AI
void BotShutdownMoveAI(void);

104
code/botlib/be_ai_weap.h Normal file
View File

@@ -0,0 +1,104 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: be_ai_weap.h
*
* desc: weapon AI
*
* $Archive: /source/code/botlib/be_ai_weap.h $
*
*****************************************************************************/
//projectile flags
#define PFL_WINDOWDAMAGE 1 //projectile damages through window
#define PFL_RETURN 2 //set when projectile returns to owner
//weapon flags
#define WFL_FIRERELEASED 1 //set when projectile is fired with key-up event
//damage types
#define DAMAGETYPE_IMPACT 1 //damage on impact
#define DAMAGETYPE_RADIAL 2 //radial damage
#define DAMAGETYPE_VISIBLE 4 //damage to all entities visible to the projectile
typedef struct projectileinfo_s
{
char name[MAX_STRINGFIELD];
char model[MAX_STRINGFIELD];
int flags;
float gravity;
int damage;
float radius;
int visdamage;
int damagetype;
int healthinc;
float push;
float detonation;
float bounce;
float bouncefric;
float bouncestop;
} projectileinfo_t;
typedef struct weaponinfo_s
{
int valid; //true if the weapon info is valid
int number; //number of the weapon
char name[MAX_STRINGFIELD];
char model[MAX_STRINGFIELD];
int level;
int weaponindex;
int flags;
char projectile[MAX_STRINGFIELD];
int numprojectiles;
float hspread;
float vspread;
float speed;
float acceleration;
vec3_t recoil;
vec3_t offset;
vec3_t angleoffset;
float extrazvelocity;
int ammoamount;
int ammoindex;
float activate;
float reload;
float spinup;
float spindown;
projectileinfo_t proj; //pointer to the used projectile
} weaponinfo_t;
//setup the weapon AI
int BotSetupWeaponAI(void);
//shut down the weapon AI
void BotShutdownWeaponAI(void);
//returns the best weapon to fight with
int BotChooseBestFightWeapon(int weaponstate, int *inventory);
//returns the information of the current weapon
void BotGetWeaponInfo(int weaponstate, int weapon, weaponinfo_t *weaponinfo);
//loads the weapon weights
int BotLoadWeaponWeights(int weaponstate, char *filename);
//returns a handle to a newly allocated weapon state
int BotAllocWeaponState(void);
//frees the weapon state
void BotFreeWeaponState(int weaponstate);
//resets the whole weapon state
void BotResetWeaponState(int weaponstate);

View File

@@ -0,0 +1,83 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_ai_weight.h
*
* desc: fuzzy weights
*
* $Archive: /source/code/botlib/be_ai_weight.h $
*
*****************************************************************************/
#define WT_BALANCE 1
#define MAX_WEIGHTS 128
//fuzzy seperator
typedef struct fuzzyseperator_s
{
int index;
int value;
int type;
float weight;
float minweight;
float maxweight;
struct fuzzyseperator_s *child;
struct fuzzyseperator_s *next;
} fuzzyseperator_t;
//fuzzy weight
typedef struct weight_s
{
char *name;
struct fuzzyseperator_s *firstseperator;
} weight_t;
//weight configuration
typedef struct weightconfig_s
{
int numweights;
weight_t weights[MAX_WEIGHTS];
char filename[MAX_QPATH];
} weightconfig_t;
//reads a weight configuration
weightconfig_t *ReadWeightConfig(char *filename);
//free a weight configuration
void FreeWeightConfig(weightconfig_t *config);
//writes a weight configuration, returns true if successfull
qboolean WriteWeightConfig(char *filename, weightconfig_t *config);
//find the fuzzy weight with the given name
int FindFuzzyWeight(weightconfig_t *wc, char *name);
//returns the fuzzy weight for the given inventory and weight
float FuzzyWeight(int *inventory, weightconfig_t *wc, int weightnum);
float FuzzyWeightUndecided(int *inventory, weightconfig_t *wc, int weightnum);
//scales the weight with the given name
void ScaleWeight(weightconfig_t *config, char *name, float scale);
//scale the balance range
void ScaleBalanceRange(weightconfig_t *config, float scale);
//evolves the weight configuration
void EvolveWeightConfig(weightconfig_t *config);
//interbreed the weight configurations and stores the interbreeded one in configout
void InterbreedWeightConfigs(weightconfig_t *config1, weightconfig_t *config2, weightconfig_t *configout);
//frees cached weight configurations
void BotShutdownWeights(void);

66
code/botlib/be_ea.h Normal file
View File

@@ -0,0 +1,66 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: be_ea.h
*
* desc: elementary actions
*
* $Archive: /source/code/botlib/be_ea.h $
*
*****************************************************************************/
//ClientCommand elementary actions
void EA_Say(int client, char *str);
void EA_SayTeam(int client, char *str);
void EA_Command(int client, char *command );
void EA_Action(int client, int action);
void EA_Crouch(int client);
void EA_Walk(int client);
void EA_MoveUp(int client);
void EA_MoveDown(int client);
void EA_MoveForward(int client);
void EA_MoveBack(int client);
void EA_MoveLeft(int client);
void EA_MoveRight(int client);
void EA_Attack(int client);
void EA_Respawn(int client);
void EA_Talk(int client);
void EA_Gesture(int client);
void EA_Use(int client);
//regular elementary actions
void EA_SelectWeapon(int client, int weapon);
void EA_Jump(int client);
void EA_DelayedJump(int client);
void EA_Move(int client, vec3_t dir, float speed);
void EA_View(int client, vec3_t viewangles);
//send regular input to the server
void EA_EndRegular(int client, float thinktime);
void EA_GetInput(int client, float thinktime, bot_input_t *input);
void EA_ResetInput(int client);
//setup and shutdown routines
int EA_Setup(void);
void EA_Shutdown(void);

View File

@@ -0,0 +1,57 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_interface.h
*
* desc: botlib interface
*
* $Archive: /source/code/botlib/be_interface.h $
*
*****************************************************************************/
//#define DEBUG //debug code
#define RANDOMIZE //randomize bot behaviour
//FIXME: get rid of this global structure
typedef struct botlib_globals_s
{
int botlibsetup; //true when the bot library has been setup
int maxentities; //maximum number of entities
int maxclients; //maximum number of clients
float time; //the global time
#ifdef DEBUG
qboolean debug; //true if debug is on
int goalareanum;
vec3_t goalorigin;
int runai;
#endif
} botlib_globals_t;
extern botlib_globals_t botlibglobals;
extern botlib_import_t botimport;
extern int bot_developer; //true if developer is on
//
int Sys_MilliSeconds(void);

516
code/botlib/botlib.h Normal file
View File

@@ -0,0 +1,516 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: botlib.h
*
* desc: bot AI library
*
* $Archive: /source/code/game/botai.h $
*
*****************************************************************************/
#define BOTLIB_API_VERSION 2
struct aas_clientmove_s;
struct aas_entityinfo_s;
struct aas_areainfo_s;
struct aas_altroutegoal_s;
struct aas_predictroute_s;
struct bot_consolemessage_s;
struct bot_match_s;
struct bot_goal_s;
struct bot_moveresult_s;
struct bot_initmove_s;
struct weaponinfo_s;
#define BOTFILESBASEFOLDER "botfiles"
//debug line colors
#define LINECOLOR_NONE -1
#define LINECOLOR_RED 1//0xf2f2f0f0L
#define LINECOLOR_GREEN 2//0xd0d1d2d3L
#define LINECOLOR_BLUE 3//0xf3f3f1f1L
#define LINECOLOR_YELLOW 4//0xdcdddedfL
#define LINECOLOR_ORANGE 5//0xe0e1e2e3L
//Print types
#define PRT_MESSAGE 1
#define PRT_WARNING 2
#define PRT_ERROR 3
#define PRT_FATAL 4
#define PRT_EXIT 5
//console message types
#define CMS_NORMAL 0
#define CMS_CHAT 1
//botlib error codes
#define BLERR_NOERROR 0 //no error
#define BLERR_LIBRARYNOTSETUP 1 //library not setup
#define BLERR_INVALIDENTITYNUMBER 2 //invalid entity number
#define BLERR_NOAASFILE 3 //no AAS file available
#define BLERR_CANNOTOPENAASFILE 4 //cannot open AAS file
#define BLERR_WRONGAASFILEID 5 //incorrect AAS file id
#define BLERR_WRONGAASFILEVERSION 6 //incorrect AAS file version
#define BLERR_CANNOTREADAASLUMP 7 //cannot read AAS file lump
#define BLERR_CANNOTLOADICHAT 8 //cannot load initial chats
#define BLERR_CANNOTLOADITEMWEIGHTS 9 //cannot load item weights
#define BLERR_CANNOTLOADITEMCONFIG 10 //cannot load item config
#define BLERR_CANNOTLOADWEAPONWEIGHTS 11 //cannot load weapon weights
#define BLERR_CANNOTLOADWEAPONCONFIG 12 //cannot load weapon config
//action flags
#define ACTION_ATTACK 0x0000001
#define ACTION_USE 0x0000002
#define ACTION_RESPAWN 0x0000008
#define ACTION_JUMP 0x0000010
#define ACTION_MOVEUP 0x0000020
#define ACTION_CROUCH 0x0000080
#define ACTION_MOVEDOWN 0x0000100
#define ACTION_MOVEFORWARD 0x0000200
#define ACTION_MOVEBACK 0x0000800
#define ACTION_MOVELEFT 0x0001000
#define ACTION_MOVERIGHT 0x0002000
#define ACTION_DELAYEDJUMP 0x0008000
#define ACTION_TALK 0x0010000
#define ACTION_GESTURE 0x0020000
#define ACTION_WALK 0x0080000
#define ACTION_AFFIRMATIVE 0x0100000
#define ACTION_NEGATIVE 0x0200000
#define ACTION_GETFLAG 0x0800000
#define ACTION_GUARDBASE 0x1000000
#define ACTION_PATROL 0x2000000
#define ACTION_FOLLOWME 0x8000000
//the bot input, will be converted to an usercmd_t
typedef struct bot_input_s
{
float thinktime; //time since last output (in seconds)
vec3_t dir; //movement direction
float speed; //speed in the range [0, 400]
vec3_t viewangles; //the view angles
int actionflags; //one of the ACTION_? flags
int weapon; //weapon to use
} bot_input_t;
#ifndef BSPTRACE
#define BSPTRACE
//bsp_trace_t hit surface
typedef struct bsp_surface_s
{
char name[16];
int flags;
int value;
} bsp_surface_t;
//remove the bsp_trace_s structure definition l8r on
//a trace is returned when a box is swept through the world
typedef struct bsp_trace_s
{
qboolean allsolid; // if true, plane is not valid
qboolean startsolid; // if true, the initial point was in a solid area
float fraction; // time completed, 1.0 = didn't hit anything
vec3_t endpos; // final position
cplane_t plane; // surface normal at impact
float exp_dist; // expanded plane distance
int sidenum; // number of the brush side hit
bsp_surface_t surface; // the hit point surface
int contents; // contents on other side of surface hit
int ent; // number of entity hit
} bsp_trace_t;
#endif // BSPTRACE
//entity state
typedef struct bot_entitystate_s
{
int type; // entity type
int flags; // entity flags
vec3_t origin; // origin of the entity
vec3_t angles; // angles of the model
vec3_t old_origin; // for lerping
vec3_t mins; // bounding box minimums
vec3_t maxs; // bounding box maximums
int groundent; // ground entity
int solid; // solid type
int modelindex; // model used
int modelindex2; // weapons, CTF flags, etc
int frame; // model frame number
int event; // impulse events -- muzzle flashes, footsteps, etc
int eventParm; // even parameter
int powerups; // bit flags
int weapon; // determines weapon and flash model, etc
int legsAnim; // mask off ANIM_TOGGLEBIT
int torsoAnim; // mask off ANIM_TOGGLEBIT
} bot_entitystate_t;
//bot AI library exported functions
typedef struct botlib_import_s
{
//print messages from the bot library
void (QDECL *Print)(int type, char *fmt, ...);
//trace a bbox through the world
void (*Trace)(bsp_trace_t *trace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask);
//trace a bbox against a specific entity
void (*EntityTrace)(bsp_trace_t *trace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int entnum, int contentmask);
//retrieve the contents at the given point
int (*PointContents)(vec3_t point);
//check if the point is in potential visible sight
int (*inPVS)(vec3_t p1, vec3_t p2);
//retrieve the BSP entity data lump
char *(*BSPEntityData)(void);
//
void (*BSPModelMinsMaxsOrigin)(int modelnum, vec3_t angles, vec3_t mins, vec3_t maxs, vec3_t origin);
//send a bot client command
void (*BotClientCommand)(int client, char *command);
//memory allocation
void *(*GetMemory)(int size); // allocate from Zone
void (*FreeMemory)(void *ptr); // free memory from Zone
int (*AvailableMemory)(void); // available Zone memory
void *(*HunkAlloc)(int size); // allocate from hunk
//file system access
int (*FS_FOpenFile)( const char *qpath, fileHandle_t *file, fsMode_t mode );
int (*FS_Read)( void *buffer, int len, fileHandle_t f );
int (*FS_Write)( const void *buffer, int len, fileHandle_t f );
void (*FS_FCloseFile)( fileHandle_t f );
int (*FS_Seek)( fileHandle_t f, long offset, int origin );
//debug visualisation stuff
int (*DebugLineCreate)(void);
void (*DebugLineDelete)(int line);
void (*DebugLineShow)(int line, vec3_t start, vec3_t end, int color);
//
int (*DebugPolygonCreate)(int color, int numPoints, vec3_t *points);
void (*DebugPolygonDelete)(int id);
} botlib_import_t;
typedef struct aas_export_s
{
//-----------------------------------
// be_aas_entity.h
//-----------------------------------
void (*AAS_EntityInfo)(int entnum, struct aas_entityinfo_s *info);
//-----------------------------------
// be_aas_main.h
//-----------------------------------
int (*AAS_Initialized)(void);
void (*AAS_PresenceTypeBoundingBox)(int presencetype, vec3_t mins, vec3_t maxs);
float (*AAS_Time)(void);
//--------------------------------------------
// be_aas_sample.c
//--------------------------------------------
int (*AAS_PointAreaNum)(vec3_t point);
int (*AAS_PointReachabilityAreaIndex)( vec3_t point );
int (*AAS_TraceAreas)(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas);
int (*AAS_BBoxAreas)(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas);
int (*AAS_AreaInfo)( int areanum, struct aas_areainfo_s *info );
//--------------------------------------------
// be_aas_bspq3.c
//--------------------------------------------
int (*AAS_PointContents)(vec3_t point);
int (*AAS_NextBSPEntity)(int ent);
int (*AAS_ValueForBSPEpairKey)(int ent, char *key, char *value, int size);
int (*AAS_VectorForBSPEpairKey)(int ent, char *key, vec3_t v);
int (*AAS_FloatForBSPEpairKey)(int ent, char *key, float *value);
int (*AAS_IntForBSPEpairKey)(int ent, char *key, int *value);
//--------------------------------------------
// be_aas_reach.c
//--------------------------------------------
int (*AAS_AreaReachability)(int areanum);
//--------------------------------------------
// be_aas_route.c
//--------------------------------------------
int (*AAS_AreaTravelTimeToGoalArea)(int areanum, vec3_t origin, int goalareanum, int travelflags);
int (*AAS_EnableRoutingArea)(int areanum, int enable);
int (*AAS_PredictRoute)(struct aas_predictroute_s *route, int areanum, vec3_t origin,
int goalareanum, int travelflags, int maxareas, int maxtime,
int stopevent, int stopcontents, int stoptfl, int stopareanum);
//--------------------------------------------
// be_aas_altroute.c
//--------------------------------------------
int (*AAS_AlternativeRouteGoals)(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags,
struct aas_altroutegoal_s *altroutegoals, int maxaltroutegoals,
int type);
//--------------------------------------------
// be_aas_move.c
//--------------------------------------------
int (*AAS_Swimming)(vec3_t origin);
int (*AAS_PredictClientMovement)(struct aas_clientmove_s *move,
int entnum, vec3_t origin,
int presencetype, int onground,
vec3_t velocity, vec3_t cmdmove,
int cmdframes,
int maxframes, float frametime,
int stopevent, int stopareanum, int visualize);
} aas_export_t;
typedef struct ea_export_s
{
//ClientCommand elementary actions
void (*EA_Command)(int client, char *command );
void (*EA_Say)(int client, char *str);
void (*EA_SayTeam)(int client, char *str);
//
void (*EA_Action)(int client, int action);
void (*EA_Gesture)(int client);
void (*EA_Talk)(int client);
void (*EA_Attack)(int client);
void (*EA_Use)(int client);
void (*EA_Respawn)(int client);
void (*EA_MoveUp)(int client);
void (*EA_MoveDown)(int client);
void (*EA_MoveForward)(int client);
void (*EA_MoveBack)(int client);
void (*EA_MoveLeft)(int client);
void (*EA_MoveRight)(int client);
void (*EA_Crouch)(int client);
void (*EA_SelectWeapon)(int client, int weapon);
void (*EA_Jump)(int client);
void (*EA_DelayedJump)(int client);
void (*EA_Move)(int client, vec3_t dir, float speed);
void (*EA_View)(int client, vec3_t viewangles);
//send regular input to the server
void (*EA_EndRegular)(int client, float thinktime);
void (*EA_GetInput)(int client, float thinktime, bot_input_t *input);
void (*EA_ResetInput)(int client);
} ea_export_t;
typedef struct ai_export_s
{
//-----------------------------------
// be_ai_char.h
//-----------------------------------
int (*BotLoadCharacter)(char *charfile, float skill);
void (*BotFreeCharacter)(int character);
float (*Characteristic_Float)(int character, int index);
float (*Characteristic_BFloat)(int character, int index, float min, float max);
int (*Characteristic_Integer)(int character, int index);
int (*Characteristic_BInteger)(int character, int index, int min, int max);
void (*Characteristic_String)(int character, int index, char *buf, int size);
//-----------------------------------
// be_ai_chat.h
//-----------------------------------
int (*BotAllocChatState)(void);
void (*BotFreeChatState)(int handle);
void (*BotQueueConsoleMessage)(int chatstate, int type, char *message);
void (*BotRemoveConsoleMessage)(int chatstate, int handle);
int (*BotNextConsoleMessage)(int chatstate, struct bot_consolemessage_s *cm);
int (*BotNumConsoleMessages)(int chatstate);
void (*BotInitialChat)(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7);
int (*BotNumInitialChats)(int chatstate, char *type);
int (*BotReplyChat)(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7);
int (*BotChatLength)(int chatstate);
void (*BotEnterChat)(int chatstate, int client, int sendto);
void (*BotGetChatMessage)(int chatstate, char *buf, int size);
int (*StringContains)(char *str1, char *str2, int casesensitive);
int (*BotFindMatch)(char *str, struct bot_match_s *match, unsigned long int context);
void (*BotMatchVariable)(struct bot_match_s *match, int variable, char *buf, int size);
void (*UnifyWhiteSpaces)(char *string);
void (*BotReplaceSynonyms)(char *string, unsigned long int context);
int (*BotLoadChatFile)(int chatstate, char *chatfile, char *chatname);
void (*BotSetChatGender)(int chatstate, int gender);
void (*BotSetChatName)(int chatstate, char *name, int client);
//-----------------------------------
// be_ai_goal.h
//-----------------------------------
void (*BotResetGoalState)(int goalstate);
void (*BotResetAvoidGoals)(int goalstate);
void (*BotRemoveFromAvoidGoals)(int goalstate, int number);
void (*BotPushGoal)(int goalstate, struct bot_goal_s *goal);
void (*BotPopGoal)(int goalstate);
void (*BotEmptyGoalStack)(int goalstate);
void (*BotDumpAvoidGoals)(int goalstate);
void (*BotDumpGoalStack)(int goalstate);
void (*BotGoalName)(int number, char *name, int size);
int (*BotGetTopGoal)(int goalstate, struct bot_goal_s *goal);
int (*BotGetSecondGoal)(int goalstate, struct bot_goal_s *goal);
int (*BotChooseLTGItem)(int goalstate, vec3_t origin, int *inventory, int travelflags);
int (*BotChooseNBGItem)(int goalstate, vec3_t origin, int *inventory, int travelflags,
struct bot_goal_s *ltg, float maxtime);
int (*BotTouchingGoal)(vec3_t origin, struct bot_goal_s *goal);
int (*BotItemGoalInVisButNotVisible)(int viewer, vec3_t eye, vec3_t viewangles, struct bot_goal_s *goal);
int (*BotGetLevelItemGoal)(int index, char *classname, struct bot_goal_s *goal);
int (*BotGetNextCampSpotGoal)(int num, struct bot_goal_s *goal);
int (*BotGetMapLocationGoal)(char *name, struct bot_goal_s *goal);
float (*BotAvoidGoalTime)(int goalstate, int number);
void (*BotSetAvoidGoalTime)(int goalstate, int number, float avoidtime);
void (*BotInitLevelItems)(void);
void (*BotUpdateEntityItems)(void);
int (*BotLoadItemWeights)(int goalstate, char *filename);
void (*BotFreeItemWeights)(int goalstate);
void (*BotInterbreedGoalFuzzyLogic)(int parent1, int parent2, int child);
void (*BotSaveGoalFuzzyLogic)(int goalstate, char *filename);
void (*BotMutateGoalFuzzyLogic)(int goalstate, float range);
int (*BotAllocGoalState)(int client);
void (*BotFreeGoalState)(int handle);
//-----------------------------------
// be_ai_move.h
//-----------------------------------
void (*BotResetMoveState)(int movestate);
void (*BotMoveToGoal)(struct bot_moveresult_s *result, int movestate, struct bot_goal_s *goal, int travelflags);
int (*BotMoveInDirection)(int movestate, vec3_t dir, float speed, int type);
void (*BotResetAvoidReach)(int movestate);
void (*BotResetLastAvoidReach)(int movestate);
int (*BotReachabilityArea)(vec3_t origin, int testground);
int (*BotMovementViewTarget)(int movestate, struct bot_goal_s *goal, int travelflags, float lookahead, vec3_t target);
int (*BotPredictVisiblePosition)(vec3_t origin, int areanum, struct bot_goal_s *goal, int travelflags, vec3_t target);
int (*BotAllocMoveState)(void);
void (*BotFreeMoveState)(int handle);
void (*BotInitMoveState)(int handle, struct bot_initmove_s *initmove);
void (*BotAddAvoidSpot)(int movestate, vec3_t origin, float radius, int type);
//-----------------------------------
// be_ai_weap.h
//-----------------------------------
int (*BotChooseBestFightWeapon)(int weaponstate, int *inventory);
void (*BotGetWeaponInfo)(int weaponstate, int weapon, struct weaponinfo_s *weaponinfo);
int (*BotLoadWeaponWeights)(int weaponstate, char *filename);
int (*BotAllocWeaponState)(void);
void (*BotFreeWeaponState)(int weaponstate);
void (*BotResetWeaponState)(int weaponstate);
//-----------------------------------
// be_ai_gen.h
//-----------------------------------
int (*GeneticParentsAndChildSelection)(int numranks, float *ranks, int *parent1, int *parent2, int *child);
} ai_export_t;
//bot AI library imported functions
typedef struct botlib_export_s
{
//Area Awareness System functions
aas_export_t aas;
//Elementary Action functions
ea_export_t ea;
//AI functions
ai_export_t ai;
//setup the bot library, returns BLERR_
int (*BotLibSetup)(void);
//shutdown the bot library, returns BLERR_
int (*BotLibShutdown)(void);
//sets a library variable returns BLERR_
int (*BotLibVarSet)(char *var_name, char *value);
//gets a library variable returns BLERR_
int (*BotLibVarGet)(char *var_name, char *value, int size);
//sets a C-like define returns BLERR_
int (*PC_AddGlobalDefine)(char *string);
int (*PC_LoadSourceHandle)(const char *filename);
int (*PC_FreeSourceHandle)(int handle);
int (*PC_ReadTokenHandle)(int handle, pc_token_t *pc_token);
int (*PC_SourceFileAndLine)(int handle, char *filename, int *line);
//start a frame in the bot library
int (*BotLibStartFrame)(float time);
//load a new map in the bot library
int (*BotLibLoadMap)(const char *mapname);
//entity updates
int (*BotLibUpdateEntity)(int ent, bot_entitystate_t *state);
//just for testing
int (*Test)(int parm0, char *parm1, vec3_t parm2, vec3_t parm3);
} botlib_export_t;
//linking of bot library
botlib_export_t *GetBotLibAPI( int apiVersion, botlib_import_t *import );
/* Library variables:
name: default: module(s): description:
"basedir" "" l_utils.c base directory
"gamedir" "" l_utils.c game directory
"cddir" "" l_utils.c CD directory
"log" "0" l_log.c enable/disable creating a log file
"maxclients" "4" be_interface.c maximum number of clients
"maxentities" "1024" be_interface.c maximum number of entities
"bot_developer" "0" be_interface.c bot developer mode
"phys_friction" "6" be_aas_move.c ground friction
"phys_stopspeed" "100" be_aas_move.c stop speed
"phys_gravity" "800" be_aas_move.c gravity value
"phys_waterfriction" "1" be_aas_move.c water friction
"phys_watergravity" "400" be_aas_move.c gravity in water
"phys_maxvelocity" "320" be_aas_move.c maximum velocity
"phys_maxwalkvelocity" "320" be_aas_move.c maximum walk velocity
"phys_maxcrouchvelocity" "100" be_aas_move.c maximum crouch velocity
"phys_maxswimvelocity" "150" be_aas_move.c maximum swim velocity
"phys_walkaccelerate" "10" be_aas_move.c walk acceleration
"phys_airaccelerate" "1" be_aas_move.c air acceleration
"phys_swimaccelerate" "4" be_aas_move.c swim acceleration
"phys_maxstep" "18" be_aas_move.c maximum step height
"phys_maxsteepness" "0.7" be_aas_move.c maximum floor steepness
"phys_maxbarrier" "32" be_aas_move.c maximum barrier height
"phys_maxwaterjump" "19" be_aas_move.c maximum waterjump height
"phys_jumpvel" "270" be_aas_move.c jump z velocity
"phys_falldelta5" "40" be_aas_move.c
"phys_falldelta10" "60" be_aas_move.c
"rs_waterjump" "400" be_aas_move.c
"rs_teleport" "50" be_aas_move.c
"rs_barrierjump" "100" be_aas_move.c
"rs_startcrouch" "300" be_aas_move.c
"rs_startgrapple" "500" be_aas_move.c
"rs_startwalkoffledge" "70" be_aas_move.c
"rs_startjump" "300" be_aas_move.c
"rs_rocketjump" "500" be_aas_move.c
"rs_bfgjump" "500" be_aas_move.c
"rs_jumppad" "250" be_aas_move.c
"rs_aircontrolledjumppad" "300" be_aas_move.c
"rs_funcbob" "300" be_aas_move.c
"rs_startelevator" "50" be_aas_move.c
"rs_falldamage5" "300" be_aas_move.c
"rs_falldamage10" "500" be_aas_move.c
"rs_maxjumpfallheight" "450" be_aas_move.c
"max_aaslinks" "4096" be_aas_sample.c maximum links in the AAS
"max_routingcache" "4096" be_aas_route.c maximum routing cache size in KB
"forceclustering" "0" be_aas_main.c force recalculation of clusters
"forcereachability" "0" be_aas_main.c force recalculation of reachabilities
"forcewrite" "0" be_aas_main.c force writing of aas file
"aasoptimize" "0" be_aas_main.c enable aas optimization
"sv_mapChecksum" "0" be_aas_main.c BSP file checksum
"bot_visualizejumppads" "0" be_aas_reach.c visualize jump pads
"bot_reloadcharacters" "0" - reload bot character files
"ai_gametype" "0" be_ai_goal.c game type
"droppedweight" "1000" be_ai_goal.c additional dropped item weight
"weapindex_rocketlauncher" "5" be_ai_move.c rl weapon index for rocket jumping
"weapindex_bfg10k" "9" be_ai_move.c bfg weapon index for bfg jumping
"weapindex_grapple" "10" be_ai_move.c grapple weapon index for grappling
"entitytypemissile" "3" be_ai_move.c ET_MISSILE
"offhandgrapple" "0" be_ai_move.c enable off hand grapple hook
"cmd_grappleon" "grappleon" be_ai_move.c command to activate off hand grapple
"cmd_grappleoff" "grappleoff" be_ai_move.c command to deactivate off hand grapple
"itemconfig" "items.c" be_ai_goal.c item configuration file
"weaponconfig" "weapons.c" be_ai_weap.c weapon configuration file
"synfile" "syn.c" be_ai_chat.c file with synonyms
"rndfile" "rnd.c" be_ai_chat.c file with random strings
"matchfile" "match.c" be_ai_chat.c file with match strings
"nochat" "0" be_ai_chat.c disable chats
"max_messages" "1024" be_ai_chat.c console message heap size
"max_weaponinfo" "32" be_ai_weap.c maximum number of weapon info
"max_projectileinfo" "32" be_ai_weap.c maximum number of projectile info
"max_iteminfo" "256" be_ai_goal.c maximum number of item info
"max_levelitems" "256" be_ai_goal.c maximum number of level items
*/

29
code/botlib/l_crc.h Normal file
View File

@@ -0,0 +1,29 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
typedef unsigned short crc_t;
void CRC_Init(unsigned short *crcvalue);
void CRC_ProcessByte(unsigned short *crcvalue, byte data);
unsigned short CRC_Value(unsigned short crcvalue);
unsigned short CRC_ProcessString(unsigned char *data, int length);
void CRC_ContinueProcessString(unsigned short *crc, char *data, int length);

63
code/botlib/l_libvar.h Normal file
View File

@@ -0,0 +1,63 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: l_libvar.h
*
* desc: botlib vars
*
* $Archive: /source/code/botlib/l_libvar.h $
*
*****************************************************************************/
//library variable
typedef struct libvar_s
{
char *name;
char *string;
int flags;
qboolean modified; // set each time the cvar is changed
float value;
struct libvar_s *next;
} libvar_t;
//removes all library variables
void LibVarDeAllocAll(void);
//gets the library variable with the given name
libvar_t *LibVarGet(char *var_name);
//gets the string of the library variable with the given name
char *LibVarGetString(char *var_name);
//gets the value of the library variable with the given name
float LibVarGetValue(char *var_name);
//creates the library variable if not existing already and returns it
libvar_t *LibVar(char *var_name, char *value);
//creates the library variable if not existing already and returns the value
float LibVarValue(char *var_name, char *value);
//creates the library variable if not existing already and returns the value string
char *LibVarString(char *var_name, char *value);
//sets the library variable
void LibVarSet(char *var_name, char *value);
//returns true if the library variable has been modified
qboolean LibVarChanged(char *var_name);
//sets the library variable to unmodified
void LibVarSetNotModified(char *var_name);

46
code/botlib/l_log.h Normal file
View File

@@ -0,0 +1,46 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: l_log.h
*
* desc: log file
*
* $Archive: /source/code/botlib/l_log.h $
*
*****************************************************************************/
//open a log file
void Log_Open(char *filename);
//close the current log file
void Log_Close(void);
//close log file if present
void Log_Shutdown(void);
//write to the current opened log file
void QDECL Log_Write(char *fmt, ...);
//write to the current opened log file with a time stamp
void QDECL Log_WriteTimeStamped(char *fmt, ...);
//returns a pointer to the log file
FILE *Log_FilePointer(void);
//flush log file
void Log_Flush(void);

76
code/botlib/l_memory.h Normal file
View File

@@ -0,0 +1,76 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: l_memory.h
*
* desc: memory management
*
* $Archive: /source/code/botlib/l_memory.h $
*
*****************************************************************************/
//#define MEMDEBUG
#ifdef MEMDEBUG
#define GetMemory(size) GetMemoryDebug(size, #size, __FILE__, __LINE__);
#define GetClearedMemory(size) GetClearedMemoryDebug(size, #size, __FILE__, __LINE__);
//allocate a memory block of the given size
void *GetMemoryDebug(unsigned long size, char *label, char *file, int line);
//allocate a memory block of the given size and clear it
void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line);
//
#define GetHunkMemory(size) GetHunkMemoryDebug(size, #size, __FILE__, __LINE__);
#define GetClearedHunkMemory(size) GetClearedHunkMemoryDebug(size, #size, __FILE__, __LINE__);
//allocate a memory block of the given size
void *GetHunkMemoryDebug(unsigned long size, char *label, char *file, int line);
//allocate a memory block of the given size and clear it
void *GetClearedHunkMemoryDebug(unsigned long size, char *label, char *file, int line);
#else
//allocate a memory block of the given size
void *GetMemory(unsigned long size);
//allocate a memory block of the given size and clear it
void *GetClearedMemory(unsigned long size);
//
#ifdef BSPC
#define GetHunkMemory GetMemory
#define GetClearedHunkMemory GetClearedMemory
#else
//allocate a memory block of the given size
void *GetHunkMemory(unsigned long size);
//allocate a memory block of the given size and clear it
void *GetClearedHunkMemory(unsigned long size);
#endif
#endif
//free the given memory block
void FreeMemory(void *ptr);
//returns the amount available memory
int AvailableMemory(void);
//prints the total used memory size
void PrintUsedMemorySize(void);
//print all memory blocks with label
void PrintMemoryLabels(void);
//returns the size of the memory block in bytes
int MemoryByteSize(void *ptr);
//free all allocated memory
void DumpMemory(void);

180
code/botlib/l_precomp.h Normal file
View File

@@ -0,0 +1,180 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: l_precomp.h
*
* desc: pre compiler
*
* $Archive: /source/code/botlib/l_precomp.h $
*
*****************************************************************************/
#ifndef MAX_PATH
#define MAX_PATH MAX_QPATH
#endif
#ifndef PATH_SEPERATORSTR
#if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__)
#define PATHSEPERATOR_STR "\\"
#else
#define PATHSEPERATOR_STR "/"
#endif
#endif
#ifndef PATH_SEPERATORCHAR
#if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__)
#define PATHSEPERATOR_CHAR '\\'
#else
#define PATHSEPERATOR_CHAR '/'
#endif
#endif
#if defined(BSPC) && !defined(QDECL)
#define QDECL
#endif
#define DEFINE_FIXED 0x0001
#define BUILTIN_LINE 1
#define BUILTIN_FILE 2
#define BUILTIN_DATE 3
#define BUILTIN_TIME 4
#define BUILTIN_STDC 5
#define INDENT_IF 0x0001
#define INDENT_ELSE 0x0002
#define INDENT_ELIF 0x0004
#define INDENT_IFDEF 0x0008
#define INDENT_IFNDEF 0x0010
//macro definitions
typedef struct define_s
{
char *name; //define name
int flags; //define flags
int builtin; // > 0 if builtin define
int numparms; //number of define parameters
token_t *parms; //define parameters
token_t *tokens; //macro tokens (possibly containing parm tokens)
struct define_s *next; //next defined macro in a list
struct define_s *hashnext; //next define in the hash chain
} define_t;
//indents
//used for conditional compilation directives:
//#if, #else, #elif, #ifdef, #ifndef
typedef struct indent_s
{
int type; //indent type
int skip; //true if skipping current indent
script_t *script; //script the indent was in
struct indent_s *next; //next indent on the indent stack
} indent_t;
//source file
typedef struct source_s
{
char filename[1024]; //file name of the script
char includepath[1024]; //path to include files
punctuation_t *punctuations; //punctuations to use
script_t *scriptstack; //stack with scripts of the source
token_t *tokens; //tokens to read first
define_t *defines; //list with macro definitions
define_t **definehash; //hash chain with defines
indent_t *indentstack; //stack with indents
int skip; // > 0 if skipping conditional code
token_t token; //last read token
} source_t;
//read a token from the source
int PC_ReadToken(source_t *source, token_t *token);
//expect a certain token
int PC_ExpectTokenString(source_t *source, char *string);
//expect a certain token type
int PC_ExpectTokenType(source_t *source, int type, int subtype, token_t *token);
//expect a token
int PC_ExpectAnyToken(source_t *source, token_t *token);
//returns true when the token is available
int PC_CheckTokenString(source_t *source, char *string);
//returns true an reads the token when a token with the given type is available
int PC_CheckTokenType(source_t *source, int type, int subtype, token_t *token);
//skip tokens until the given token string is read
int PC_SkipUntilString(source_t *source, char *string);
//unread the last token read from the script
void PC_UnreadLastToken(source_t *source);
//unread the given token
void PC_UnreadToken(source_t *source, token_t *token);
//read a token only if on the same line, lines are concatenated with a slash
int PC_ReadLine(source_t *source, token_t *token);
//returns true if there was a white space in front of the token
int PC_WhiteSpaceBeforeToken(token_t *token);
//add a define to the source
int PC_AddDefine(source_t *source, char *string);
//add a globals define that will be added to all opened sources
int PC_AddGlobalDefine(char *string);
//remove the given global define
int PC_RemoveGlobalDefine(char *name);
//remove all globals defines
void PC_RemoveAllGlobalDefines(void);
//add builtin defines
void PC_AddBuiltinDefines(source_t *source);
//set the source include path
void PC_SetIncludePath(source_t *source, char *path);
//set the punction set
void PC_SetPunctuations(source_t *source, punctuation_t *p);
//set the base folder to load files from
void PC_SetBaseFolder(char *path);
//load a source file
source_t *LoadSourceFile(const char *filename);
//load a source from memory
source_t *LoadSourceMemory(char *ptr, int length, char *name);
//free the given source
void FreeSource(source_t *source);
//print a source error
void QDECL SourceError(source_t *source, char *str, ...);
//print a source warning
void QDECL SourceWarning(source_t *source, char *str, ...);
#ifdef BSPC
// some of BSPC source does include game/q_shared.h and some does not
// we define pc_token_s pc_token_t if needed (yes, it's ugly)
#ifndef __Q_SHARED_H
#define MAX_TOKENLENGTH 1024
typedef struct pc_token_s
{
int type;
int subtype;
int intvalue;
float floatvalue;
char string[MAX_TOKENLENGTH];
} pc_token_t;
#endif //!_Q_SHARED_H
#endif //BSPC
//
int PC_LoadSourceHandle(const char *filename);
int PC_FreeSourceHandle(int handle);
int PC_ReadTokenHandle(int handle, pc_token_t *pc_token);
int PC_SourceFileAndLine(int handle, char *filename, int *line);
void PC_CheckOpenSourceHandles(void);

247
code/botlib/l_script.h Normal file
View File

@@ -0,0 +1,247 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: l_script.h
*
* desc: lexicographical parser
*
* $Archive: /source/code/botlib/l_script.h $
*
*****************************************************************************/
//undef if binary numbers of the form 0b... or 0B... are not allowed
#define BINARYNUMBERS
//undef if not using the token.intvalue and token.floatvalue
#define NUMBERVALUE
//use dollar sign also as punctuation
#define DOLLAR
//maximum token length
#define MAX_TOKEN 1024
#if defined(BSPC) && !defined(QDECL)
#define QDECL
#endif
//script flags
#define SCFL_NOERRORS 0x0001
#define SCFL_NOWARNINGS 0x0002
#define SCFL_NOSTRINGWHITESPACES 0x0004
#define SCFL_NOSTRINGESCAPECHARS 0x0008
#define SCFL_PRIMITIVE 0x0010
#define SCFL_NOBINARYNUMBERS 0x0020
#define SCFL_NONUMBERVALUES 0x0040
//token types
#define TT_STRING 1 // string
#define TT_LITERAL 2 // literal
#define TT_NUMBER 3 // number
#define TT_NAME 4 // name
#define TT_PUNCTUATION 5 // punctuation
//string sub type
//---------------
// the length of the string
//literal sub type
//----------------
// the ASCII code of the literal
//number sub type
//---------------
#define TT_DECIMAL 0x0008 // decimal number
#define TT_HEX 0x0100 // hexadecimal number
#define TT_OCTAL 0x0200 // octal number
#ifdef BINARYNUMBERS
#define TT_BINARY 0x0400 // binary number
#endif //BINARYNUMBERS
#define TT_FLOAT 0x0800 // floating point number
#define TT_INTEGER 0x1000 // integer number
#define TT_LONG 0x2000 // long number
#define TT_UNSIGNED 0x4000 // unsigned number
//punctuation sub type
//--------------------
#define P_RSHIFT_ASSIGN 1
#define P_LSHIFT_ASSIGN 2
#define P_PARMS 3
#define P_PRECOMPMERGE 4
#define P_LOGIC_AND 5
#define P_LOGIC_OR 6
#define P_LOGIC_GEQ 7
#define P_LOGIC_LEQ 8
#define P_LOGIC_EQ 9
#define P_LOGIC_UNEQ 10
#define P_MUL_ASSIGN 11
#define P_DIV_ASSIGN 12
#define P_MOD_ASSIGN 13
#define P_ADD_ASSIGN 14
#define P_SUB_ASSIGN 15
#define P_INC 16
#define P_DEC 17
#define P_BIN_AND_ASSIGN 18
#define P_BIN_OR_ASSIGN 19
#define P_BIN_XOR_ASSIGN 20
#define P_RSHIFT 21
#define P_LSHIFT 22
#define P_POINTERREF 23
#define P_CPP1 24
#define P_CPP2 25
#define P_MUL 26
#define P_DIV 27
#define P_MOD 28
#define P_ADD 29
#define P_SUB 30
#define P_ASSIGN 31
#define P_BIN_AND 32
#define P_BIN_OR 33
#define P_BIN_XOR 34
#define P_BIN_NOT 35
#define P_LOGIC_NOT 36
#define P_LOGIC_GREATER 37
#define P_LOGIC_LESS 38
#define P_REF 39
#define P_COMMA 40
#define P_SEMICOLON 41
#define P_COLON 42
#define P_QUESTIONMARK 43
#define P_PARENTHESESOPEN 44
#define P_PARENTHESESCLOSE 45
#define P_BRACEOPEN 46
#define P_BRACECLOSE 47
#define P_SQBRACKETOPEN 48
#define P_SQBRACKETCLOSE 49
#define P_BACKSLASH 50
#define P_PRECOMP 51
#define P_DOLLAR 52
//name sub type
//-------------
// the length of the name
//punctuation
typedef struct punctuation_s
{
char *p; //punctuation character(s)
int n; //punctuation indication
struct punctuation_s *next; //next punctuation
} punctuation_t;
//token
typedef struct token_s
{
char string[MAX_TOKEN]; //available token
int type; //last read token type
int subtype; //last read token sub type
#ifdef NUMBERVALUE
unsigned long int intvalue; //integer value
float floatvalue; //floating point value
#endif //NUMBERVALUE
char *whitespace_p; //start of white space before token
char *endwhitespace_p; //start of white space before token
int line; //line the token was on
int linescrossed; //lines crossed in white space
struct token_s *next; //next token in chain
} token_t;
//script file
typedef struct script_s
{
char filename[1024]; //file name of the script
char *buffer; //buffer containing the script
char *script_p; //current pointer in the script
char *end_p; //pointer to the end of the script
char *lastscript_p; //script pointer before reading token
char *whitespace_p; //begin of the white space
char *endwhitespace_p; //end of the white space
int length; //length of the script in bytes
int line; //current line in script
int lastline; //line before reading token
int tokenavailable; //set by UnreadLastToken
int flags; //several script flags
punctuation_t *punctuations; //the punctuations used in the script
punctuation_t **punctuationtable;
token_t token; //available token
struct script_s *next; //next script in a chain
} script_t;
//read a token from the script
int PS_ReadToken(script_t *script, token_t *token);
//expect a certain token
int PS_ExpectTokenString(script_t *script, char *string);
//expect a certain token type
int PS_ExpectTokenType(script_t *script, int type, int subtype, token_t *token);
//expect a token
int PS_ExpectAnyToken(script_t *script, token_t *token);
//returns true when the token is available
int PS_CheckTokenString(script_t *script, char *string);
//returns true an reads the token when a token with the given type is available
int PS_CheckTokenType(script_t *script, int type, int subtype, token_t *token);
//skip tokens until the given token string is read
int PS_SkipUntilString(script_t *script, char *string);
//unread the last token read from the script
void PS_UnreadLastToken(script_t *script);
//unread the given token
void PS_UnreadToken(script_t *script, token_t *token);
//returns the next character of the read white space, returns NULL if none
char PS_NextWhiteSpaceChar(script_t *script);
//remove any leading and trailing double quotes from the token
void StripDoubleQuotes(char *string);
//remove any leading and trailing single quotes from the token
void StripSingleQuotes(char *string);
//read a possible signed integer
signed long int ReadSignedInt(script_t *script);
//read a possible signed floating point number
float ReadSignedFloat(script_t *script);
//set an array with punctuations, NULL restores default C/C++ set
void SetScriptPunctuations(script_t *script, punctuation_t *p);
//set script flags
void SetScriptFlags(script_t *script, int flags);
//get script flags
int GetScriptFlags(script_t *script);
//reset a script
void ResetScript(script_t *script);
//returns true if at the end of the script
int EndOfScript(script_t *script);
//returns a pointer to the punctuation with the given number
char *PunctuationFromNum(script_t *script, int num);
//load a script from the given file at the given offset with the given length
script_t *LoadScriptFile(const char *filename);
//load a script from the given memory with the given length
script_t *LoadScriptMemory(char *ptr, int length, char *name);
//free a script
void FreeScript(script_t *script);
//set the base folder to load files from
void PS_SetBaseFolder(char *path);
//print a script error with filename and line number
void QDECL ScriptError(script_t *script, char *str, ...);
//print a script warning with filename and line number
void QDECL ScriptWarning(script_t *script, char *str, ...);

75
code/botlib/l_struct.h Normal file
View File

@@ -0,0 +1,75 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: l_struct.h
*
* desc: structure reading/writing
*
* $Archive: /source/code/botlib/l_struct.h $
*
*****************************************************************************/
#define MAX_STRINGFIELD 80
//field types
#define FT_CHAR 1 // char
#define FT_INT 2 // int
#define FT_FLOAT 3 // float
#define FT_STRING 4 // char [MAX_STRINGFIELD]
#define FT_STRUCT 6 // struct (sub structure)
//type only mask
#define FT_TYPE 0x00FF // only type, clear subtype
//sub types
#define FT_ARRAY 0x0100 // array of type
#define FT_BOUNDED 0x0200 // bounded value
#define FT_UNSIGNED 0x0400
//structure field definition
typedef struct fielddef_s
{
char *name; //name of the field
int offset; //offset in the structure
int type; //type of the field
//type specific fields
int maxarray; //maximum array size
float floatmin, floatmax; //float min and max
struct structdef_s *substruct; //sub structure
} fielddef_t;
//structure definition
typedef struct structdef_s
{
int size;
fielddef_t *fields;
} structdef_t;
//read a structure from a script
int ReadStructure(source_t *source, structdef_t *def, char *structure);
//write a structure to a file
int WriteStructure(FILE *fp, structdef_t *def, char *structure);
//writes indents
int WriteIndent(FILE *fp, int indent);
//writes a float without traling zeros
int WriteFloat(FILE *fp, float value);

37
code/botlib/l_utils.h Normal file
View File

@@ -0,0 +1,37 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: l_util.h
*
* desc: utils
*
* $Archive: /source/code/botlib/l_util.h $
*
*****************************************************************************/
#define Vector2Angles(v,a) vectoangles(v,a)
#ifndef MAX_PATH
#define MAX_PATH MAX_QPATH
#endif
#define Maximum(x,y) (x > y ? x : y)
#define Minimum(x,y) (x < y ? x : y)

55
code/botlib/lcc.mak Normal file
View File

@@ -0,0 +1,55 @@
#
# Makefile for Gladiator Bot library: gladiator.dll
# Intended for LCC-Win32
#
CC=lcc
CFLAGS=-DC_ONLY -o
OBJS= be_aas_bspq2.obj \
be_aas_bsphl.obj \
be_aas_cluster.obj \
be_aas_debug.obj \
be_aas_entity.obj \
be_aas_file.obj \
be_aas_light.obj \
be_aas_main.obj \
be_aas_move.obj \
be_aas_optimize.obj \
be_aas_reach.obj \
be_aas_route.obj \
be_aas_routealt.obj \
be_aas_sample.obj \
be_aas_sound.obj \
be_ai2_dm.obj \
be_ai2_dmnet.obj \
be_ai2_main.obj \
be_ai_char.obj \
be_ai_chat.obj \
be_ai_goal.obj \
be_ai_load.obj \
be_ai_move.obj \
be_ai_weap.obj \
be_ai_weight.obj \
be_ea.obj \
be_interface.obj \
l_crc.obj \
l_libvar.obj \
l_log.obj \
l_memory.obj \
l_precomp.obj \
l_script.obj \
l_struct.obj \
l_utils.obj \
q_shared.obj
all: gladiator.dll
gladiator.dll: $(OBJS)
lcclnk -dll -entry GetBotAPI *.obj botlib.def -o gladiator.dll
clean:
del *.obj gladiator.dll
%.obj: %.c
$(CC) $(CFLAGS) $<

View File

@@ -0,0 +1,92 @@
#
# Makefile for Gladiator Bot library: gladiator.so
# Intended for gcc/Linux
#
ARCH=i386
CC=gcc
BASE_CFLAGS=-Dstricmp=strcasecmp
#use these cflags to optimize it
CFLAGS=$(BASE_CFLAGS) -m486 -O6 -ffast-math -funroll-loops \
-fomit-frame-pointer -fexpensive-optimizations -malign-loops=2 \
-malign-jumps=2 -malign-functions=2
#use these when debugging
#CFLAGS=$(BASE_CFLAGS) -g
LDFLAGS=-ldl -lm
SHLIBEXT=so
SHLIBCFLAGS=-fPIC
SHLIBLDFLAGS=-shared
DO_CC=$(CC) $(CFLAGS) $(SHLIBCFLAGS) -o $@ -c $<
#############################################################################
# SETUP AND BUILD
# GLADIATOR BOT
#############################################################################
.c.o:
$(DO_CC)
GAME_OBJS = \
be_aas_bsphl.o\
be_aas_bspq2.o\
be_aas_cluster.o\
be_aas_debug.o\
be_aas_entity.o\
be_aas_file.o\
be_aas_light.o\
be_aas_main.o\
be_aas_move.o\
be_aas_optimize.o\
be_aas_reach.o\
be_aas_route.o\
be_aas_routealt.o\
be_aas_sample.o\
be_aas_sound.o\
be_ai2_dmq2.o\
be_ai2_dmhl.o\
be_ai2_dmnet.o\
be_ai2_main.o\
be_ai_char.o\
be_ai_chat.o\
be_ai_goal.o\
be_ai_load.o\
be_ai_move.o\
be_ai_weap.o\
be_ai_weight.o\
be_ea.o\
be_interface.o\
l_crc.o\
l_libvar.o\
l_log.o\
l_memory.o\
l_precomp.o\
l_script.o\
l_struct.o\
l_utils.o\
q_shared.o
glad$(ARCH).$(SHLIBEXT) : $(GAME_OBJS)
$(CC) $(CFLAGS) $(SHLIBLDFLAGS) -o $@ $(GAME_OBJS)
#############################################################################
# MISC
#############################################################################
clean:
-rm -f $(GAME_OBJS)
depend:
gcc -MM $(GAME_OBJS:.o=.c)
install:
cp gladiator.so ..
#
# From "make depend"
#

132
code/cgame/cg_challenges.c Normal file
View File

@@ -0,0 +1,132 @@
/*
===========================================================================
Copyright (C) 2008 Poul Sander
This file is part of Open Arena source code.
Open Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Open Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Open Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//#include "cg_local.h"
#include "../qcommon/q_shared.h"
#include "../renderer/tr_types.h"
#include "../game/bg_public.h"
#include "../game/challenges.h"
#ifdef PARTofUI
#include "../q3_ui/ui_local.h"
#else
#include "../cgame/cg_local.h"
#endif
#define FILENAME "challenges.dat"
//First two static variables that may only be accessed throgh functions in this file
//The challengeTable is of constant size so there is room for more challenges being added in the furture
static unsigned int challengeTable[CHALLENGES_MAX];
//We have a variable to see if the system is initialized
static qboolean challengesInitialized = qfalse;
//This function initializes the challenge system. It has no effect if the system is already intialized.
void challenges_init(void)
{
fileHandle_t file;
int fileLen;
int i;
//If already initialized then do nothing
if(challengesInitialized)
return;
//Else open file
fileLen = trap_FS_FOpenFile(FILENAME, &file, FS_READ);
//If the file not is big enough to contain all challenges then initialize from zero
if(fileLen<sizeof(challengeTable))
{
trap_FS_FCloseFile(file); //Lets remeber to close the file before all returns
for(i=0;i<CHALLENGES_MAX;i++)
challengeTable[i]=0; //Init all challenges to zero
challengesInitialized = qtrue; //Still consider the system loaded!
return; //Not enough data to actually read
}
//If the file is big enough:
trap_FS_Read(challengeTable,sizeof(challengeTable),file);
trap_FS_FCloseFile(file); //Lets remember to close the file
challengesInitialized = qtrue; //We are initialized!
return;
}
//This functions saves the challenges. It only needs to be called once for each game. It should be called from the shutdown function
void challenges_save(void)
{
fileHandle_t file;
int fileStatus;
int i;
if(!challengesInitialized)
{
//The challenge system has not been initialized and therefore cannot be saved
//CG_Printf("Challenge system not initialized.\n");
return;
}
//Open the challenges file for writing:
fileStatus = trap_FS_FOpenFile(FILENAME, &file, FS_WRITE);
if(fileStatus<0)
{
//For some reason file opening failed
#ifndef PARTofUI
CG_Printf("Failed to open challenges.dat for writing\n");
#endif
return;
}
for(i=0;i<CHALLENGES_MAX;i++)
{
//Write the table to disk
trap_FS_Write((const void*)&challengeTable[i],sizeof(unsigned int),file);
}
//Always close the file in id tech 3
trap_FS_FCloseFile(file);
//Lets make the challenges system uninitialized since changes after this will most likely not be saved anyway.
challengesInitialized = qfalse;
#ifndef PARTofUI
CG_Printf("Wrote challenges.cfg\n");
#endif
}
//Get the number of times a given challenge has been completed
unsigned int getChallenge(int challenge)
{
challenges_init();
if(challenge>=CHALLENGES_MAX)
return 0;
return challengeTable[challenge];
}
void addChallenge(int challenge)
{
if(challenge>=CHALLENGES_MAX)
{
#ifndef PARTofUI
CG_Printf("Challenge #%u is >=CHALLENGES_MAX\n",challenge);
#endif
return; //Maybe also print an error?
}
challenges_init();
challengeTable[challenge]++;
//CG_Printf("Increased challenge #%u by one. Is now %u\n",challenge,challengeTable[challenge]);
}

622
code/cgame/cg_consolecmds.c Normal file
View File

@@ -0,0 +1,622 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_consolecmds.c -- text commands typed in at the local console, or
// executed by a key binding
#include "cg_local.h"
#include "../ui/ui_shared.h"
#ifdef MISSIONPACK
extern menuDef_t *menuScoreboard;
#endif
void CG_PrintClientNumbers( void ) {
int i;
CG_Printf( "slot score ping name\n" );
CG_Printf( "---- ----- ---- ----\n" );
for(i=0;i<cg.numScores;i++) {
CG_Printf("%-4d",cg.scores[i].client);
CG_Printf(" %-5d",cg.scores[i].score);
CG_Printf(" %-4d",cg.scores[i].ping);
CG_Printf(" %s\n",cgs.clientinfo[cg.scores[i].client].name);
}
}
void CG_TargetCommand_f( void ) {
int targetNum;
char test[4];
targetNum = CG_CrosshairPlayer();
if (!targetNum ) {
return;
}
trap_Argv( 1, test, 4 );
trap_SendConsoleCommand( va( "gc %i %i", targetNum, atoi( test ) ) );
}
/*
=================
CG_SizeUp_f
Keybinding command
=================
*/
static void CG_SizeUp_f (void) {
trap_Cvar_Set("cg_viewsize", va("%i",(int)(cg_viewsize.integer+10)));
}
/*
=================
CG_SizeDown_f
Keybinding command
=================
*/
static void CG_SizeDown_f (void) {
trap_Cvar_Set("cg_viewsize", va("%i",(int)(cg_viewsize.integer-10)));
}
/*
=============
CG_Viewpos_f
Debugging command to print the current position
=============
*/
static void CG_Viewpos_f (void) {
CG_Printf ("(%i %i %i) : %i\n", (int)cg.refdef.vieworg[0],
(int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2],
(int)cg.refdefViewAngles[YAW]);
}
static void CG_ScoresDown_f( void ) {
#ifdef MISSIONPACK
CG_BuildSpectatorString();
#endif
if ( cg.scoresRequestTime + 2000 < cg.time ) {
// the scores are more than two seconds out of data,
// so request new ones
cg.scoresRequestTime = cg.time;
trap_SendClientCommand( "score" );
// leave the current scores up if they were already
// displayed, but if this is the first hit, clear them out
if ( !cg.showScores ) {
cg.showScores = qtrue;
cg.numScores = 0;
}
} else {
// show the cached contents even if they just pressed if it
// is within two seconds
cg.showScores = qtrue;
}
}
static void CG_ScoresUp_f( void ) {
if ( cg.showScores ) {
cg.showScores = qfalse;
cg.scoreFadeTime = cg.time;
}
}
static void CG_AccDown_f( void ) {
if ( cg.accRequestTime + 2000 < cg.time ) {
cg.accRequestTime = cg.time;
trap_SendClientCommand( "acc" );
if ( !cg.showAcc ) {
cg.showAcc = qtrue;
}
} else {
cg.showAcc = qtrue;
}
}
static void CG_AccUp_f( void ) {
if ( cg.showAcc ) {
cg.showAcc = qfalse;
cg.accFadeTime = cg.time;
}
}
#ifdef MISSIONPACK
extern menuDef_t *menuScoreboard;
void Menu_Reset( void ); // FIXME: add to right include file
static void CG_LoadHud_f( void) {
char buff[1024];
const char *hudSet;
memset(buff, 0, sizeof(buff));
String_Init();
Menu_Reset();
trap_Cvar_VariableStringBuffer("cg_hudFiles", buff, sizeof(buff));
hudSet = buff;
if (hudSet[0] == '\0') {
hudSet = "ui/hud.txt";
}
CG_LoadMenus(hudSet);
menuScoreboard = NULL;
}
static void CG_scrollScoresDown_f( void) {
if (menuScoreboard && cg.scoreBoardShowing) {
Menu_ScrollFeeder(menuScoreboard, FEEDER_SCOREBOARD, qtrue);
Menu_ScrollFeeder(menuScoreboard, FEEDER_REDTEAM_LIST, qtrue);
Menu_ScrollFeeder(menuScoreboard, FEEDER_BLUETEAM_LIST, qtrue);
}
}
static void CG_scrollScoresUp_f( void) {
if (menuScoreboard && cg.scoreBoardShowing) {
Menu_ScrollFeeder(menuScoreboard, FEEDER_SCOREBOARD, qfalse);
Menu_ScrollFeeder(menuScoreboard, FEEDER_REDTEAM_LIST, qfalse);
Menu_ScrollFeeder(menuScoreboard, FEEDER_BLUETEAM_LIST, qfalse);
}
}
static void CG_spWin_f( void) {
trap_Cvar_Set("cg_cameraOrbit", "2");
trap_Cvar_Set("cg_cameraOrbitDelay", "35");
trap_Cvar_Set("cg_thirdPerson", "1");
trap_Cvar_Set("cg_thirdPersonAngle", "0");
trap_Cvar_Set("cg_thirdPersonRange", "100");
CG_AddBufferedSound(cgs.media.winnerSound);
//trap_S_StartLocalSound(cgs.media.winnerSound, CHAN_ANNOUNCER);
CG_CenterPrint("YOU WIN!", SCREEN_HEIGHT * .30, 0);
}
static void CG_spLose_f( void) {
trap_Cvar_Set("cg_cameraOrbit", "2");
trap_Cvar_Set("cg_cameraOrbitDelay", "35");
trap_Cvar_Set("cg_thirdPerson", "1");
trap_Cvar_Set("cg_thirdPersonAngle", "0");
trap_Cvar_Set("cg_thirdPersonRange", "100");
CG_AddBufferedSound(cgs.media.loserSound);
//trap_S_StartLocalSound(cgs.media.loserSound, CHAN_ANNOUNCER);
CG_CenterPrint("YOU LOSE...", SCREEN_HEIGHT * .30, 0);
}
#endif
static void CG_TellTarget_f( void ) {
int clientNum;
char command[128];
char message[128];
clientNum = CG_CrosshairPlayer();
if ( clientNum == -1 ) {
return;
}
trap_Args( message, 128 );
Com_sprintf( command, 128, "tell %i %s", clientNum, message );
trap_SendClientCommand( command );
}
static void CG_TellAttacker_f( void ) {
int clientNum;
char command[128];
char message[128];
clientNum = CG_LastAttacker();
if ( clientNum == -1 ) {
return;
}
trap_Args( message, 128 );
Com_sprintf( command, 128, "tell %i %s", clientNum, message );
trap_SendClientCommand( command );
}
static void CG_VoiceTellTarget_f( void ) {
int clientNum;
char command[128];
char message[128];
clientNum = CG_CrosshairPlayer();
if ( clientNum == -1 ) {
return;
}
trap_Args( message, 128 );
Com_sprintf( command, 128, "vtell %i %s", clientNum, message );
trap_SendClientCommand( command );
}
static void CG_VoiceTellAttacker_f( void ) {
int clientNum;
char command[128];
char message[128];
clientNum = CG_LastAttacker();
if ( clientNum == -1 ) {
return;
}
trap_Args( message, 128 );
Com_sprintf( command, 128, "vtell %i %s", clientNum, message );
trap_SendClientCommand( command );
}
#ifdef MISSIONPACK
static void CG_NextTeamMember_f( void ) {
CG_SelectNextPlayer();
}
static void CG_PrevTeamMember_f( void ) {
CG_SelectPrevPlayer();
}
// ASS U ME's enumeration order as far as task specific orders, OFFENSE is zero, CAMP is last
//
static void CG_NextOrder_f( void ) {
clientInfo_t *ci = cgs.clientinfo + cg.snap->ps.clientNum;
if (ci) {
if (!ci->teamLeader && sortedTeamPlayers[cg_currentSelectedPlayer.integer] != cg.snap->ps.clientNum) {
return;
}
}
if (cgs.currentOrder < TEAMTASK_CAMP) {
cgs.currentOrder++;
if (cgs.currentOrder == TEAMTASK_RETRIEVE) {
if (!CG_OtherTeamHasFlag()) {
cgs.currentOrder++;
}
}
if (cgs.currentOrder == TEAMTASK_ESCORT) {
if (!CG_YourTeamHasFlag()) {
cgs.currentOrder++;
}
}
} else {
cgs.currentOrder = TEAMTASK_OFFENSE;
}
cgs.orderPending = qtrue;
cgs.orderTime = cg.time + 3000;
}
static void CG_ConfirmOrder_f (void ) {
trap_SendConsoleCommand(va("cmd vtell %d %s\n", cgs.acceptLeader, VOICECHAT_YES));
trap_SendConsoleCommand("+button5; wait; -button5");
if (cg.time < cgs.acceptOrderTime) {
trap_SendClientCommand(va("teamtask %d\n", cgs.acceptTask));
cgs.acceptOrderTime = 0;
}
}
static void CG_DenyOrder_f (void ) {
trap_SendConsoleCommand(va("cmd vtell %d %s\n", cgs.acceptLeader, VOICECHAT_NO));
trap_SendConsoleCommand("+button6; wait; -button6");
if (cg.time < cgs.acceptOrderTime) {
cgs.acceptOrderTime = 0;
}
}
static void CG_TaskOffense_f (void ) {
if (cgs.gametype == GT_CTF || cgs.gametype == GT_CTF_ELIMINATION || cgs.gametype == GT_1FCTF) {
trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONGETFLAG));
} else {
trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONOFFENSE));
}
trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_OFFENSE));
}
static void CG_TaskDefense_f (void ) {
trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONDEFENSE));
trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_DEFENSE));
}
static void CG_TaskPatrol_f (void ) {
trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONPATROL));
trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_PATROL));
}
static void CG_TaskCamp_f (void ) {
trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONCAMPING));
trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_CAMP));
}
static void CG_TaskFollow_f (void ) {
trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONFOLLOW));
trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_FOLLOW));
}
static void CG_TaskRetrieve_f (void ) {
trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONRETURNFLAG));
trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_RETRIEVE));
}
static void CG_TaskEscort_f (void ) {
trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_ONFOLLOWCARRIER));
trap_SendClientCommand(va("teamtask %d\n", TEAMTASK_ESCORT));
}
static void CG_TaskOwnFlag_f (void ) {
trap_SendConsoleCommand(va("cmd vsay_team %s\n", VOICECHAT_IHAVEFLAG));
}
static void CG_TauntKillInsult_f (void ) {
trap_SendConsoleCommand("cmd vsay kill_insult\n");
}
static void CG_TauntPraise_f (void ) {
trap_SendConsoleCommand("cmd vsay praise\n");
}
static void CG_TauntTaunt_f (void ) {
trap_SendConsoleCommand("cmd vtaunt\n");
}
static void CG_TauntDeathInsult_f (void ) {
trap_SendConsoleCommand("cmd vsay death_insult\n");
}
static void CG_TauntGauntlet_f (void ) {
trap_SendConsoleCommand("cmd vsay kill_guantlet\n");
}
static void CG_TaskSuicide_f (void ) {
int clientNum;
char command[128];
clientNum = CG_CrosshairPlayer();
if ( clientNum == -1 ) {
return;
}
Com_sprintf( command, 128, "tell %i suicide", clientNum );
trap_SendClientCommand( command );
}
/*
==================
CG_TeamMenu_f
==================
*/
/*
static void CG_TeamMenu_f( void ) {
if (trap_Key_GetCatcher() & KEYCATCH_CGAME) {
CG_EventHandling(CGAME_EVENT_NONE);
trap_Key_SetCatcher(0);
} else {
CG_EventHandling(CGAME_EVENT_TEAMMENU);
//trap_Key_SetCatcher(KEYCATCH_CGAME);
}
}
*/
/*
==================
CG_EditHud_f
==================
*/
/*
static void CG_EditHud_f( void ) {
//cls.keyCatchers ^= KEYCATCH_CGAME;
//VM_Call (cgvm, CG_EVENT_HANDLING, (cls.keyCatchers & KEYCATCH_CGAME) ? CGAME_EVENT_EDITHUD : CGAME_EVENT_NONE);
}
*/
#endif
/*
==================
CG_StartOrbit_f
==================
*/
static void CG_StartOrbit_f( void ) {
char var[MAX_TOKEN_CHARS];
trap_Cvar_VariableStringBuffer( "developer", var, sizeof( var ) );
if ( !atoi(var) ) {
return;
}
if (cg_cameraOrbit.value != 0) {
trap_Cvar_Set ("cg_cameraOrbit", "0");
trap_Cvar_Set("cg_thirdPerson", "0");
} else {
trap_Cvar_Set("cg_cameraOrbit", "5");
trap_Cvar_Set("cg_thirdPerson", "1");
trap_Cvar_Set("cg_thirdPersonAngle", "0");
trap_Cvar_Set("cg_thirdPersonRange", "100");
}
}
/*
static void CG_Camera_f( void ) {
char name[1024];
trap_Argv( 1, name, sizeof(name));
if (trap_loadCamera(name)) {
cg.cameraMode = qtrue;
trap_startCamera(cg.time);
} else {
CG_Printf ("Unable to load camera %s\n",name);
}
}
*/
typedef struct {
char *cmd;
void (*function)(void);
} consoleCommand_t;
static consoleCommand_t commands[] = {
{ "testgun", CG_TestGun_f },
{ "testmodel", CG_TestModel_f },
{ "nextframe", CG_TestModelNextFrame_f },
{ "prevframe", CG_TestModelPrevFrame_f },
{ "nextskin", CG_TestModelNextSkin_f },
{ "prevskin", CG_TestModelPrevSkin_f },
{ "viewpos", CG_Viewpos_f },
{ "+scores", CG_ScoresDown_f },
{ "-scores", CG_ScoresUp_f },
{ "+zoom", CG_ZoomDown_f },
{ "-zoom", CG_ZoomUp_f },
{ "sizeup", CG_SizeUp_f },
{ "sizedown", CG_SizeDown_f },
{ "weapnext", CG_NextWeapon_f },
{ "weapprev", CG_PrevWeapon_f },
{ "weapon", CG_Weapon_f },
{ "tell_target", CG_TellTarget_f },
{ "tell_attacker", CG_TellAttacker_f },
{ "vtell_target", CG_VoiceTellTarget_f },
{ "vtell_attacker", CG_VoiceTellAttacker_f },
{ "tcmd", CG_TargetCommand_f },
#ifdef MISSIONPACK
{ "loadhud", CG_LoadHud_f },
{ "nextTeamMember", CG_NextTeamMember_f },
{ "prevTeamMember", CG_PrevTeamMember_f },
{ "nextOrder", CG_NextOrder_f },
{ "confirmOrder", CG_ConfirmOrder_f },
{ "denyOrder", CG_DenyOrder_f },
{ "taskOffense", CG_TaskOffense_f },
{ "taskDefense", CG_TaskDefense_f },
{ "taskPatrol", CG_TaskPatrol_f },
{ "taskCamp", CG_TaskCamp_f },
{ "taskFollow", CG_TaskFollow_f },
{ "taskRetrieve", CG_TaskRetrieve_f },
{ "taskEscort", CG_TaskEscort_f },
{ "taskSuicide", CG_TaskSuicide_f },
{ "taskOwnFlag", CG_TaskOwnFlag_f },
{ "tauntKillInsult", CG_TauntKillInsult_f },
{ "tauntPraise", CG_TauntPraise_f },
{ "tauntTaunt", CG_TauntTaunt_f },
{ "tauntDeathInsult", CG_TauntDeathInsult_f },
{ "tauntGauntlet", CG_TauntGauntlet_f },
{ "spWin", CG_spWin_f },
{ "spLose", CG_spLose_f },
{ "scoresDown", CG_scrollScoresDown_f },
{ "scoresUp", CG_scrollScoresUp_f },
#endif
{ "startOrbit", CG_StartOrbit_f },
// { "camera", CG_Camera_f },
{ "loaddeferred", CG_LoadDeferredPlayers },
{ "+acc", CG_AccDown_f },
{ "-acc", CG_AccUp_f },
{ "clients", CG_PrintClientNumbers }
};
/*
=================
CG_ConsoleCommand
The string has been tokenized and can be retrieved with
Cmd_Argc() / Cmd_Argv()
=================
*/
qboolean CG_ConsoleCommand( void ) {
const char *cmd;
int i;
cmd = CG_Argv(0);
for ( i = 0 ; i < sizeof( commands ) / sizeof( commands[0] ) ; i++ ) {
if ( !Q_stricmp( cmd, commands[i].cmd ) ) {
commands[i].function();
return qtrue;
}
}
return qfalse;
}
/*
=================
CG_InitConsoleCommands
Let the client system know about all of our commands
so it can perform tab completion
=================
*/
void CG_InitConsoleCommands( void ) {
int i;
for ( i = 0 ; i < sizeof( commands ) / sizeof( commands[0] ) ; i++ ) {
trap_AddCommand( commands[i].cmd );
}
//
// the game server will interpret these commands, which will be automatically
// forwarded to the server after they are not recognized locally
//
trap_AddCommand ("kill");
trap_AddCommand ("say");
trap_AddCommand ("say_team");
trap_AddCommand ("tell");
trap_AddCommand ("vsay");
trap_AddCommand ("vsay_team");
trap_AddCommand ("vtell");
trap_AddCommand ("vtaunt");
trap_AddCommand ("vosay");
trap_AddCommand ("vosay_team");
trap_AddCommand ("votell");
trap_AddCommand ("give");
trap_AddCommand ("god");
trap_AddCommand ("notarget");
trap_AddCommand ("noclip");
trap_AddCommand ("team");
trap_AddCommand ("follow");
trap_AddCommand ("levelshot");
trap_AddCommand ("addbot");
trap_AddCommand ("setviewpos");
trap_AddCommand ("callvote");
trap_AddCommand ("getmappage");
trap_AddCommand ("vote");
trap_AddCommand ("callteamvote");
trap_AddCommand ("teamvote");
trap_AddCommand ("stats");
trap_AddCommand ("teamtask");
trap_AddCommand ("loaddefered"); // spelled wrong, but not changing for demo
}

3408
code/cgame/cg_draw.c Normal file

File diff suppressed because it is too large Load Diff

821
code/cgame/cg_drawtools.c Normal file
View File

@@ -0,0 +1,821 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_drawtools.c -- helper functions called by cg_draw, cg_scoreboard, cg_info, etc
#include "cg_local.h"
/*
================
CG_AdjustFrom640
Adjusted for resolution and screen aspect ratio
================
*/
void CG_AdjustFrom640( float *x, float *y, float *w, float *h ) {
#if 0
// adjust for wide screens
if ( cgs.glconfig.vidWidth * 480 > cgs.glconfig.vidHeight * 640 ) {
*x += 0.5 * ( cgs.glconfig.vidWidth - ( cgs.glconfig.vidHeight * 640 / 480 ) );
}
#endif
// scale for screen sizes
*x *= cgs.screenXScale;
*y *= cgs.screenYScale;
*w *= cgs.screenXScale;
*h *= cgs.screenYScale;
}
/*
================
CG_FillRect
Coordinates are 640*480 virtual values
=================
*/
void CG_FillRect( float x, float y, float width, float height, const float *color ) {
trap_R_SetColor( color );
CG_AdjustFrom640( &x, &y, &width, &height );
trap_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader );
trap_R_SetColor( NULL );
}
/*
================
CG_DrawSides
Coords are virtual 640x480
================
*/
void CG_DrawSides(float x, float y, float w, float h, float size) {
CG_AdjustFrom640( &x, &y, &w, &h );
size *= cgs.screenXScale;
trap_R_DrawStretchPic( x, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader );
trap_R_DrawStretchPic( x + w - size, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader );
}
void CG_DrawTopBottom(float x, float y, float w, float h, float size) {
CG_AdjustFrom640( &x, &y, &w, &h );
size *= cgs.screenYScale;
trap_R_DrawStretchPic( x, y, w, size, 0, 0, 0, 0, cgs.media.whiteShader );
trap_R_DrawStretchPic( x, y + h - size, w, size, 0, 0, 0, 0, cgs.media.whiteShader );
}
/*
================
UI_DrawRect
Coordinates are 640*480 virtual values
=================
*/
void CG_DrawRect( float x, float y, float width, float height, float size, const float *color ) {
trap_R_SetColor( color );
CG_DrawTopBottom(x, y, width, height, size);
CG_DrawSides(x, y, width, height, size);
trap_R_SetColor( NULL );
}
/*
================
CG_DrawPic
Coordinates are 640*480 virtual values
=================
*/
void CG_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) {
CG_AdjustFrom640( &x, &y, &width, &height );
trap_R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader );
}
/*
===============
CG_DrawChar
Coordinates and size in 640*480 virtual screen size
===============
*/
void CG_DrawChar( int x, int y, int width, int height, int ch ) {
int row, col;
float frow, fcol;
float size;
float ax, ay, aw, ah;
ch &= 255;
if ( ch == ' ' ) {
return;
}
ax = x;
ay = y;
aw = width;
ah = height;
CG_AdjustFrom640( &ax, &ay, &aw, &ah );
row = ch>>4;
col = ch&15;
frow = row*0.0625;
fcol = col*0.0625;
size = 0.0625;
trap_R_DrawStretchPic( ax, ay, aw, ah,
fcol, frow,
fcol + size, frow + size,
cgs.media.charsetShader );
}
/*
==================
CG_DrawStringExt
Draws a multi-colored string with a drop shadow, optionally forcing
to a fixed color.
Coordinates are at 640 by 480 virtual resolution
==================
*/
void CG_DrawStringExt( int x, int y, const char *string, const float *setColor,
qboolean forceColor, qboolean shadow, int charWidth, int charHeight, int maxChars ) {
vec4_t color;
const char *s;
int xx;
int cnt;
if (maxChars <= 0)
maxChars = 32767; // do them all!
// draw the drop shadow
if (shadow) {
color[0] = color[1] = color[2] = 0;
color[3] = setColor[3];
trap_R_SetColor( color );
s = string;
xx = x;
cnt = 0;
while ( *s && cnt < maxChars) {
if ( Q_IsColorString( s ) ) {
s += 2;
continue;
}
CG_DrawChar( xx + 2, y + 2, charWidth, charHeight, *s );
cnt++;
xx += charWidth;
s++;
}
}
// draw the colored text
s = string;
xx = x;
cnt = 0;
trap_R_SetColor( setColor );
while ( *s && cnt < maxChars) {
if ( Q_IsColorString( s ) ) {
if ( !forceColor ) {
memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) );
color[3] = setColor[3];
trap_R_SetColor( color );
}
s += 2;
continue;
}
CG_DrawChar( xx, y, charWidth, charHeight, *s );
xx += charWidth;
cnt++;
s++;
}
trap_R_SetColor( NULL );
}
void CG_DrawBigString( int x, int y, const char *s, float alpha ) {
float color[4];
color[0] = color[1] = color[2] = 1.0;
color[3] = alpha;
CG_DrawStringExt( x, y, s, color, qfalse, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 );
}
void CG_DrawBigStringColor( int x, int y, const char *s, vec4_t color ) {
CG_DrawStringExt( x, y, s, color, qtrue, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 );
}
void CG_DrawSmallString( int x, int y, const char *s, float alpha ) {
float color[4];
color[0] = color[1] = color[2] = 1.0;
color[3] = alpha;
CG_DrawStringExt( x, y, s, color, qfalse, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 );
}
void CG_DrawSmallStringColor( int x, int y, const char *s, vec4_t color ) {
CG_DrawStringExt( x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 );
}
/*
=================
CG_DrawStrlen
Returns character count, skiping color escape codes
=================
*/
int CG_DrawStrlen( const char *str ) {
const char *s = str;
int count = 0;
while ( *s ) {
if ( Q_IsColorString( s ) ) {
s += 2;
} else {
count++;
s++;
}
}
return count;
}
/*
=============
CG_TileClearBox
This repeats a 64*64 tile graphic to fill the screen around a sized down
refresh window.
=============
*/
static void CG_TileClearBox( int x, int y, int w, int h, qhandle_t hShader ) {
float s1, t1, s2, t2;
s1 = x/64.0;
t1 = y/64.0;
s2 = (x+w)/64.0;
t2 = (y+h)/64.0;
trap_R_DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader );
}
/*
==============
CG_TileClear
Clear around a sized down screen
==============
*/
void CG_TileClear( void ) {
int top, bottom, left, right;
int w, h;
w = cgs.glconfig.vidWidth;
h = cgs.glconfig.vidHeight;
if ( cg.refdef.x == 0 && cg.refdef.y == 0 &&
cg.refdef.width == w && cg.refdef.height == h ) {
return; // full screen rendering
}
top = cg.refdef.y;
bottom = top + cg.refdef.height-1;
left = cg.refdef.x;
right = left + cg.refdef.width-1;
// clear above view screen
CG_TileClearBox( 0, 0, w, top, cgs.media.backTileShader );
// clear below view screen
CG_TileClearBox( 0, bottom, w, h - bottom, cgs.media.backTileShader );
// clear left of view screen
CG_TileClearBox( 0, top, left, bottom - top + 1, cgs.media.backTileShader );
// clear right of view screen
CG_TileClearBox( right, top, w - right, bottom - top + 1, cgs.media.backTileShader );
}
/*
================
CG_FadeColor
================
*/
float *CG_FadeColor( int startMsec, int totalMsec ) {
static vec4_t color;
int t;
if ( startMsec == 0 ) {
return NULL;
}
t = cg.time - startMsec;
if ( t >= totalMsec ) {
return NULL;
}
// fade out
if ( totalMsec - t < FADE_TIME ) {
color[3] = ( totalMsec - t ) * 1.0/FADE_TIME;
} else {
color[3] = 1.0;
}
color[0] = color[1] = color[2] = 1;
return color;
}
/*
================
CG_TeamColor
================
*/
float *CG_TeamColor( int team ) {
static vec4_t red = {1, 0.2f, 0.2f, 1};
static vec4_t blue = {0.2f, 0.2f, 1, 1};
static vec4_t other = {1, 1, 1, 1};
static vec4_t spectator = {0.7f, 0.7f, 0.7f, 1};
switch ( team ) {
case TEAM_RED:
return red;
case TEAM_BLUE:
return blue;
case TEAM_SPECTATOR:
return spectator;
default:
return other;
}
}
/*
=================
CG_GetColorForHealth
=================
*/
void CG_GetColorForHealth( int health, int armor, vec4_t hcolor ) {
int count;
int max;
// calculate the total points of damage that can
// be sustained at the current health / armor level
if ( health <= 0 ) {
VectorClear( hcolor ); // black
hcolor[3] = 1;
return;
}
count = armor;
max = health * ARMOR_PROTECTION / ( 1.0 - ARMOR_PROTECTION );
if ( max < count ) {
count = max;
}
health += count;
// set the color based on health
hcolor[0] = 1.0;
hcolor[3] = 1.0;
if ( health >= 100 ) {
hcolor[2] = 1.0;
} else if ( health < 66 ) {
hcolor[2] = 0;
} else {
hcolor[2] = ( health - 66 ) / 33.0;
}
if ( health > 60 ) {
hcolor[1] = 1.0;
} else if ( health < 30 ) {
hcolor[1] = 0;
} else {
hcolor[1] = ( health - 30 ) / 30.0;
}
}
/*
=================
CG_ColorForHealth
=================
*/
void CG_ColorForHealth( vec4_t hcolor ) {
CG_GetColorForHealth( cg.snap->ps.stats[STAT_HEALTH],
cg.snap->ps.stats[STAT_ARMOR], hcolor );
}
// bk001205 - code below duplicated in q3_ui/ui-atoms.c
// bk001205 - FIXME: does this belong in ui_shared.c?
/*
=================
UI_DrawProportionalString2
=================
*/
static int propMap[128][3] = {
{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
{0, 0, PROP_SPACE_WIDTH}, // SPACE
{11, 122, 7}, // !
{154, 181, 14}, // "
{55, 122, 17}, // #
{79, 122, 18}, // $
{101, 122, 23}, // %
{153, 122, 18}, // &
{9, 93, 7}, // '
{207, 122, 8}, // (
{230, 122, 9}, // )
{177, 122, 18}, // *
{30, 152, 18}, // +
{85, 181, 7}, // ,
{34, 93, 11}, // -
{110, 181, 6}, // .
{130, 152, 14}, // /
{22, 64, 17}, // 0
{41, 64, 12}, // 1
{58, 64, 17}, // 2
{78, 64, 18}, // 3
{98, 64, 19}, // 4
{120, 64, 18}, // 5
{141, 64, 18}, // 6
{204, 64, 16}, // 7
{162, 64, 17}, // 8
{182, 64, 18}, // 9
{59, 181, 7}, // :
{35,181, 7}, // ;
{203, 152, 14}, // <
{56, 93, 14}, // =
{228, 152, 14}, // >
{177, 181, 18}, // ?
{28, 122, 22}, // @
{5, 4, 18}, // A
{27, 4, 18}, // B
{48, 4, 18}, // C
{69, 4, 17}, // D
{90, 4, 13}, // E
{106, 4, 13}, // F
{121, 4, 18}, // G
{143, 4, 17}, // H
{164, 4, 8}, // I
{175, 4, 16}, // J
{195, 4, 18}, // K
{216, 4, 12}, // L
{230, 4, 23}, // M
{6, 34, 18}, // N
{27, 34, 18}, // O
{48, 34, 18}, // P
{68, 34, 18}, // Q
{90, 34, 17}, // R
{110, 34, 18}, // S
{130, 34, 14}, // T
{146, 34, 18}, // U
{166, 34, 19}, // V
{185, 34, 29}, // W
{215, 34, 18}, // X
{234, 34, 18}, // Y
{5, 64, 14}, // Z
{60, 152, 7}, // [
{106, 151, 13}, // '\'
{83, 152, 7}, // ]
{128, 122, 17}, // ^
{4, 152, 21}, // _
{134, 181, 5}, // '
{5, 4, 18}, // A
{27, 4, 18}, // B
{48, 4, 18}, // C
{69, 4, 17}, // D
{90, 4, 13}, // E
{106, 4, 13}, // F
{121, 4, 18}, // G
{143, 4, 17}, // H
{164, 4, 8}, // I
{175, 4, 16}, // J
{195, 4, 18}, // K
{216, 4, 12}, // L
{230, 4, 23}, // M
{6, 34, 18}, // N
{27, 34, 18}, // O
{48, 34, 18}, // P
{68, 34, 18}, // Q
{90, 34, 17}, // R
{110, 34, 18}, // S
{130, 34, 14}, // T
{146, 34, 18}, // U
{166, 34, 19}, // V
{185, 34, 29}, // W
{215, 34, 18}, // X
{234, 34, 18}, // Y
{5, 64, 14}, // Z
{153, 152, 13}, // {
{11, 181, 5}, // |
{180, 152, 13}, // }
{79, 93, 17}, // ~
{0, 0, -1} // DEL
};
static int propMapB[26][3] = {
{11, 12, 33},
{49, 12, 31},
{85, 12, 31},
{120, 12, 30},
{156, 12, 21},
{183, 12, 21},
{207, 12, 32},
{13, 55, 30},
{49, 55, 13},
{66, 55, 29},
{101, 55, 31},
{135, 55, 21},
{158, 55, 40},
{204, 55, 32},
{12, 97, 31},
{48, 97, 31},
{82, 97, 30},
{118, 97, 30},
{153, 97, 30},
{185, 97, 25},
{213, 97, 30},
{11, 139, 32},
{42, 139, 51},
{93, 139, 32},
{126, 139, 31},
{158, 139, 25},
};
#define PROPB_GAP_WIDTH 4
#define PROPB_SPACE_WIDTH 12
#define PROPB_HEIGHT 36
/*
=================
UI_DrawBannerString
=================
*/
static void UI_DrawBannerString2( int x, int y, const char* str, vec4_t color )
{
const char* s;
unsigned char ch; // bk001204 : array subscript
float ax;
float ay;
float aw;
float ah;
float frow;
float fcol;
float fwidth;
float fheight;
// draw the colored text
trap_R_SetColor( color );
ax = x * cgs.screenXScale + cgs.screenXBias;
ay = y * cgs.screenYScale;
s = str;
while ( *s )
{
ch = *s & 127;
if ( ch == ' ' ) {
ax += ((float)PROPB_SPACE_WIDTH + (float)PROPB_GAP_WIDTH)* cgs.screenXScale;
}
else if ( ch >= 'A' && ch <= 'Z' ) {
ch -= 'A';
fcol = (float)propMapB[ch][0] / 256.0f;
frow = (float)propMapB[ch][1] / 256.0f;
fwidth = (float)propMapB[ch][2] / 256.0f;
fheight = (float)PROPB_HEIGHT / 256.0f;
aw = (float)propMapB[ch][2] * cgs.screenXScale;
ah = (float)PROPB_HEIGHT * cgs.screenXScale;
trap_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol+fwidth, frow+fheight, cgs.media.charsetPropB );
ax += (aw + (float)PROPB_GAP_WIDTH * cgs.screenXScale);
}
s++;
}
trap_R_SetColor( NULL );
}
void UI_DrawBannerString( int x, int y, const char* str, int style, vec4_t color ) {
const char * s;
int ch;
int width;
vec4_t drawcolor;
// find the width of the drawn text
s = str;
width = 0;
while ( *s ) {
ch = *s;
if ( ch == ' ' ) {
width += PROPB_SPACE_WIDTH;
}
else if ( ch >= 'A' && ch <= 'Z' ) {
width += propMapB[ch - 'A'][2] + PROPB_GAP_WIDTH;
}
s++;
}
width -= PROPB_GAP_WIDTH;
switch( style & UI_FORMATMASK ) {
case UI_CENTER:
x -= width / 2;
break;
case UI_RIGHT:
x -= width;
break;
case UI_LEFT:
default:
break;
}
if ( style & UI_DROPSHADOW ) {
drawcolor[0] = drawcolor[1] = drawcolor[2] = 0;
drawcolor[3] = color[3];
UI_DrawBannerString2( x+2, y+2, str, drawcolor );
}
UI_DrawBannerString2( x, y, str, color );
}
int UI_ProportionalStringWidth( const char* str ) {
const char * s;
int ch;
int charWidth;
int width;
s = str;
width = 0;
while ( *s ) {
ch = *s & 127;
charWidth = propMap[ch][2];
if ( charWidth != -1 ) {
width += charWidth;
width += PROP_GAP_WIDTH;
}
s++;
}
width -= PROP_GAP_WIDTH;
return width;
}
static void UI_DrawProportionalString2( int x, int y, const char* str, vec4_t color, float sizeScale, qhandle_t charset )
{
const char* s;
unsigned char ch; // bk001204 - unsigned
float ax;
float ay;
float aw;
float ah;
float frow;
float fcol;
float fwidth;
float fheight;
// draw the colored text
trap_R_SetColor( color );
ax = x * cgs.screenXScale + cgs.screenXBias;
ay = y * cgs.screenXScale;
s = str;
while ( *s )
{
ch = *s & 127;
if ( ch == ' ' ) {
aw = (float)PROP_SPACE_WIDTH * cgs.screenXScale * sizeScale;
} else if ( propMap[ch][2] != -1 ) {
fcol = (float)propMap[ch][0] / 256.0f;
frow = (float)propMap[ch][1] / 256.0f;
fwidth = (float)propMap[ch][2] / 256.0f;
fheight = (float)PROP_HEIGHT / 256.0f;
aw = (float)propMap[ch][2] * cgs.screenXScale * sizeScale;
ah = (float)PROP_HEIGHT * cgs.screenXScale * sizeScale;
trap_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol+fwidth, frow+fheight, charset );
} else {
aw = 0;
}
ax += (aw + (float)PROP_GAP_WIDTH * cgs.screenXScale * sizeScale);
s++;
}
trap_R_SetColor( NULL );
}
/*
=================
UI_ProportionalSizeScale
=================
*/
float UI_ProportionalSizeScale( int style ) {
if( style & UI_SMALLFONT ) {
return 0.75;
}
return 1.00;
}
/*
=================
UI_DrawProportionalString
=================
*/
void UI_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color ) {
vec4_t drawcolor;
int width;
float sizeScale;
sizeScale = UI_ProportionalSizeScale( style );
switch( style & UI_FORMATMASK ) {
case UI_CENTER:
width = UI_ProportionalStringWidth( str ) * sizeScale;
x -= width / 2;
break;
case UI_RIGHT:
width = UI_ProportionalStringWidth( str ) * sizeScale;
x -= width;
break;
case UI_LEFT:
default:
break;
}
if ( style & UI_DROPSHADOW ) {
drawcolor[0] = drawcolor[1] = drawcolor[2] = 0;
drawcolor[3] = color[3];
UI_DrawProportionalString2( x+2, y+2, str, drawcolor, sizeScale, cgs.media.charsetProp );
}
if ( style & UI_INVERSE ) {
drawcolor[0] = color[0] * 0.8;
drawcolor[1] = color[1] * 0.8;
drawcolor[2] = color[2] * 0.8;
drawcolor[3] = color[3];
UI_DrawProportionalString2( x, y, str, drawcolor, sizeScale, cgs.media.charsetProp );
return;
}
if ( style & UI_PULSE ) {
drawcolor[0] = color[0] * 0.8;
drawcolor[1] = color[1] * 0.8;
drawcolor[2] = color[2] * 0.8;
drawcolor[3] = color[3];
UI_DrawProportionalString2( x, y, str, color, sizeScale, cgs.media.charsetProp );
drawcolor[0] = color[0];
drawcolor[1] = color[1];
drawcolor[2] = color[2];
drawcolor[3] = 0.5 + 0.5 * sin( cg.time / PULSE_DIVISOR );
UI_DrawProportionalString2( x, y, str, drawcolor, sizeScale, cgs.media.charsetPropGlow );
return;
}
UI_DrawProportionalString2( x, y, str, color, sizeScale, cgs.media.charsetProp );
}

828
code/cgame/cg_effects.c Normal file
View File

@@ -0,0 +1,828 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_effects.c -- these functions generate localentities, usually as a result
// of event processing
#include "cg_local.h"
/*
==================
CG_BubbleTrail
Bullets shot underwater
==================
*/
void CG_BubbleTrail( vec3_t start, vec3_t end, float spacing ) {
vec3_t move;
vec3_t vec;
float len;
int i;
if ( cg_noProjectileTrail.integer ) {
return;
}
VectorCopy (start, move);
VectorSubtract (end, start, vec);
len = VectorNormalize (vec);
// advance a random amount first
i = rand() % (int)spacing;
VectorMA( move, i, vec, move );
VectorScale (vec, spacing, vec);
for ( ; i < len; i += spacing ) {
localEntity_t *le;
refEntity_t *re;
le = CG_AllocLocalEntity();
le->leFlags = LEF_PUFF_DONT_SCALE;
le->leType = LE_MOVE_SCALE_FADE;
le->startTime = cg.time;
le->endTime = cg.time + 1000 + random() * 250;
le->lifeRate = 1.0 / ( le->endTime - le->startTime );
re = &le->refEntity;
re->shaderTime = cg.time / 1000.0f;
re->reType = RT_SPRITE;
re->rotation = 0;
re->radius = 3;
re->customShader = cgs.media.waterBubbleShader;
re->shaderRGBA[0] = 0xff;
re->shaderRGBA[1] = 0xff;
re->shaderRGBA[2] = 0xff;
re->shaderRGBA[3] = 0xff;
le->color[3] = 1.0;
le->pos.trType = TR_LINEAR;
le->pos.trTime = cg.time;
VectorCopy( move, le->pos.trBase );
le->pos.trDelta[0] = crandom()*5;
le->pos.trDelta[1] = crandom()*5;
le->pos.trDelta[2] = crandom()*5 + 6;
VectorAdd (move, vec, move);
}
}
/*
=====================
CG_SmokePuff
Adds a smoke puff or blood trail localEntity.
=====================
*/
localEntity_t *CG_SmokePuff( const vec3_t p, const vec3_t vel,
float radius,
float r, float g, float b, float a,
float duration,
int startTime,
int fadeInTime,
int leFlags,
qhandle_t hShader ) {
static int seed = 0x92;
localEntity_t *le;
refEntity_t *re;
// int fadeInTime = startTime + duration / 2;
le = CG_AllocLocalEntity();
le->leFlags = leFlags;
le->radius = radius;
re = &le->refEntity;
re->rotation = Q_random( &seed ) * 360;
re->radius = radius;
re->shaderTime = startTime / 1000.0f;
le->leType = LE_MOVE_SCALE_FADE;
le->startTime = startTime;
le->fadeInTime = fadeInTime;
le->endTime = startTime + duration;
if ( fadeInTime > startTime ) {
le->lifeRate = 1.0 / ( le->endTime - le->fadeInTime );
}
else {
le->lifeRate = 1.0 / ( le->endTime - le->startTime );
}
le->color[0] = r;
le->color[1] = g;
le->color[2] = b;
le->color[3] = a;
le->pos.trType = TR_LINEAR_STOP;
le->pos.trTime = startTime;
VectorCopy( vel, le->pos.trDelta );
VectorCopy( p, le->pos.trBase );
VectorCopy( p, re->origin );
re->customShader = hShader;
// rage pro can't alpha fade, so use a different shader
if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO ) {
re->customShader = cgs.media.smokePuffRageProShader;
re->shaderRGBA[0] = 0xff;
re->shaderRGBA[1] = 0xff;
re->shaderRGBA[2] = 0xff;
re->shaderRGBA[3] = 0xff;
} else {
re->shaderRGBA[0] = le->color[0] * 0xff;
re->shaderRGBA[1] = le->color[1] * 0xff;
re->shaderRGBA[2] = le->color[2] * 0xff;
re->shaderRGBA[3] = 0xff;
}
re->reType = RT_SPRITE;
re->radius = le->radius;
return le;
}
// LEILEI same as above, but slows down.......
localEntity_t *CG_SlowPuff( const vec3_t p, const vec3_t vel,
float radius,
float r, float g, float b, float a,
float duration,
int startTime,
int fadeInTime,
int leFlags,
qhandle_t hShader ) {
static int seed = 0x92;
localEntity_t *le;
refEntity_t *re;
le = CG_AllocLocalEntity();
le->leFlags = leFlags;
le->radius = radius;
re = &le->refEntity;
re->rotation = Q_random( &seed ) * 360;
re->radius = radius;
re->shaderTime = startTime / 1000.0f;
le->leType = LE_MOVE_SCALE_FADE;
le->startTime = startTime;
le->fadeInTime = fadeInTime;
le->endTime = startTime + duration;
if ( fadeInTime > startTime ) {
le->lifeRate = 1.0 / ( le->endTime - le->fadeInTime );
}
else {
le->lifeRate = 1.0 / ( le->endTime - le->startTime );
}
le->color[0] = r;
le->color[1] = g;
le->color[2] = b;
le->color[3] = a;
le->pos.trType = TR_LINEAR;
le->pos.trTime = startTime;
VectorCopy( vel, le->pos.trDelta );
VectorCopy( p, le->pos.trBase );
VectorCopy( p, re->origin );
re->customShader = hShader;
// rage pro can't alpha fade, so use a different shader
if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO ) {
re->customShader = cgs.media.smokePuffRageProShader;
re->shaderRGBA[0] = 0xff;
re->shaderRGBA[1] = 0xff;
re->shaderRGBA[2] = 0xff;
re->shaderRGBA[3] = 0xff;
} else {
re->shaderRGBA[0] = le->color[0] * 0xff;
re->shaderRGBA[1] = le->color[1] * 0xff;
re->shaderRGBA[2] = le->color[2] * 0xff;
re->shaderRGBA[3] = 0xff;
}
re->reType = RT_SPRITE;
re->radius = le->radius;
return le;
}
/*
==================
CG_SpawnEffect
Player teleporting in or out
==================
*/
void CG_SpawnEffect( vec3_t org ) {
localEntity_t *le;
refEntity_t *re;
le = CG_AllocLocalEntity();
le->leFlags = 0;
le->leType = LE_FADE_RGB;
le->startTime = cg.time;
le->endTime = cg.time + 500;
le->lifeRate = 1.0 / ( le->endTime - le->startTime );
le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
re = &le->refEntity;
re->reType = RT_MODEL;
re->shaderTime = cg.time / 1000.0f;
#ifndef MISSIONPACK
re->customShader = cgs.media.teleportEffectShader;
#endif
re->hModel = cgs.media.teleportEffectModel;
AxisClear( re->axis );
VectorCopy( org, re->origin );
#ifdef MISSIONPACK
re->origin[2] += 16;
#else
re->origin[2] -= 24;
#endif
}
/*
===============
CG_LightningBoltBeam
===============
*/
void CG_LightningBoltBeam( vec3_t start, vec3_t end ) {
localEntity_t *le;
refEntity_t *beam;
le = CG_AllocLocalEntity();
le->leFlags = 0;
le->leType = LE_SHOWREFENTITY;
le->startTime = cg.time;
le->endTime = cg.time + 50;
beam = &le->refEntity;
VectorCopy( start, beam->origin );
// this is the end point
VectorCopy( end, beam->oldorigin );
beam->reType = RT_LIGHTNING;
beam->customShader = cgs.media.lightningShader;
}
/*
==================
CG_KamikazeEffect
==================
*/
void CG_KamikazeEffect( vec3_t org ) {
localEntity_t *le;
refEntity_t *re;
le = CG_AllocLocalEntity();
le->leFlags = 0;
le->leType = LE_KAMIKAZE;
le->startTime = cg.time;
le->endTime = cg.time + 3000;//2250;
le->lifeRate = 1.0 / ( le->endTime - le->startTime );
le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
VectorClear(le->angles.trBase);
re = &le->refEntity;
re->reType = RT_MODEL;
re->shaderTime = cg.time / 1000.0f;
re->hModel = cgs.media.kamikazeEffectModel;
VectorCopy( org, re->origin );
}
/*
==================
CG_ObeliskExplode
==================
*/
void CG_ObeliskExplode( vec3_t org, int entityNum ) {
localEntity_t *le;
vec3_t origin;
// create an explosion
VectorCopy( org, origin );
origin[2] += 64;
le = CG_MakeExplosion( origin, vec3_origin,
cgs.media.dishFlashModel,
cgs.media.rocketExplosionShader,
600, qtrue );
le->light = 300;
le->lightColor[0] = 1;
le->lightColor[1] = 0.75;
le->lightColor[2] = 0.0;
}
/*
==================
CG_ObeliskPain
==================
*/
void CG_ObeliskPain( vec3_t org ) {
float r;
sfxHandle_t sfx;
// hit sound
r = rand() & 3;
if ( r < 2 ) {
sfx = cgs.media.obeliskHitSound1;
} else if ( r == 2 ) {
sfx = cgs.media.obeliskHitSound2;
} else {
sfx = cgs.media.obeliskHitSound3;
}
trap_S_StartSound ( org, ENTITYNUM_NONE, CHAN_BODY, sfx );
}
/*
==================
CG_InvulnerabilityImpact
==================
*/
void CG_InvulnerabilityImpact( vec3_t org, vec3_t angles ) {
localEntity_t *le;
refEntity_t *re;
int r;
sfxHandle_t sfx;
le = CG_AllocLocalEntity();
le->leFlags = 0;
le->leType = LE_INVULIMPACT;
le->startTime = cg.time;
le->endTime = cg.time + 1000;
le->lifeRate = 1.0 / ( le->endTime - le->startTime );
le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
re = &le->refEntity;
re->reType = RT_MODEL;
re->shaderTime = cg.time / 1000.0f;
re->hModel = cgs.media.invulnerabilityImpactModel;
VectorCopy( org, re->origin );
AnglesToAxis( angles, re->axis );
r = rand() & 3;
if ( r < 2 ) {
sfx = cgs.media.invulnerabilityImpactSound1;
} else if ( r == 2 ) {
sfx = cgs.media.invulnerabilityImpactSound2;
} else {
sfx = cgs.media.invulnerabilityImpactSound3;
}
trap_S_StartSound (org, ENTITYNUM_NONE, CHAN_BODY, sfx );
}
/*
==================
CG_InvulnerabilityJuiced
==================
*/
void CG_InvulnerabilityJuiced( vec3_t org ) {
localEntity_t *le;
refEntity_t *re;
vec3_t angles;
le = CG_AllocLocalEntity();
le->leFlags = 0;
le->leType = LE_INVULJUICED;
le->startTime = cg.time;
le->endTime = cg.time + 10000;
le->lifeRate = 1.0 / ( le->endTime - le->startTime );
le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
re = &le->refEntity;
re->reType = RT_MODEL;
re->shaderTime = cg.time / 1000.0f;
re->hModel = cgs.media.invulnerabilityJuicedModel;
VectorCopy( org, re->origin );
VectorClear(angles);
AnglesToAxis( angles, re->axis );
trap_S_StartSound (org, ENTITYNUM_NONE, CHAN_BODY, cgs.media.invulnerabilityJuicedSound );
}
/*
==================
CG_ScorePlum
==================
*/
void CG_ScorePlum( int client, vec3_t org, int score ) {
localEntity_t *le;
refEntity_t *re;
vec3_t angles;
static vec3_t lastPos;
// only visualize for the client that scored
if (client != cg.predictedPlayerState.clientNum || cg_scorePlum.integer == 0) {
return;
}
le = CG_AllocLocalEntity();
le->leFlags = 0;
le->leType = LE_SCOREPLUM;
le->startTime = cg.time;
le->endTime = cg.time + 4000;
le->lifeRate = 1.0 / ( le->endTime - le->startTime );
le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0;
le->radius = score;
VectorCopy( org, le->pos.trBase );
if (org[2] >= lastPos[2] - 20 && org[2] <= lastPos[2] + 20) {
le->pos.trBase[2] -= 20;
}
//CG_Printf( "Plum origin %i %i %i -- %i\n", (int)org[0], (int)org[1], (int)org[2], (int)Distance(org, lastPos));
VectorCopy(org, lastPos);
re = &le->refEntity;
re->reType = RT_SPRITE;
re->radius = 16;
VectorClear(angles);
AnglesToAxis( angles, re->axis );
}
/*
====================
CG_MakeExplosion
====================
*/
localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir,
qhandle_t hModel, qhandle_t shader,
int msec, qboolean isSprite ) {
float ang;
localEntity_t *ex;
int offset;
vec3_t tmpVec, newOrigin;
if ( msec <= 0 ) {
CG_Error( "CG_MakeExplosion: msec = %i", msec );
}
// skew the time a bit so they aren't all in sync
offset = rand() & 63;
ex = CG_AllocLocalEntity();
if ( isSprite ) {
ex->leType = LE_SPRITE_EXPLOSION;
// randomly rotate sprite orientation
ex->refEntity.rotation = rand() % 360;
VectorScale( dir, 16, tmpVec );
VectorAdd( tmpVec, origin, newOrigin );
} else {
ex->leType = LE_EXPLOSION;
VectorCopy( origin, newOrigin );
// set axis with random rotate
if ( !dir ) {
AxisClear( ex->refEntity.axis );
} else {
ang = rand() % 360;
VectorCopy( dir, ex->refEntity.axis[0] );
RotateAroundDirection( ex->refEntity.axis, ang );
}
}
ex->startTime = cg.time - offset;
ex->endTime = ex->startTime + msec;
// bias the time so all shader effects start correctly
ex->refEntity.shaderTime = ex->startTime / 1000.0f;
ex->refEntity.hModel = hModel;
ex->refEntity.customShader = shader;
// set origin
VectorCopy( newOrigin, ex->refEntity.origin );
VectorCopy( newOrigin, ex->refEntity.oldorigin );
ex->color[0] = ex->color[1] = ex->color[2] = 1.0;
return ex;
}
/*
=================
CG_Bleed
This is the spurt of blood when a character gets hit
=================
*/
void CG_Bleed( vec3_t origin, int entityNum ) {
localEntity_t *ex;
if ( !cg_blood.integer ) {
return;
}
ex = CG_AllocLocalEntity();
ex->leType = LE_EXPLOSION;
ex->startTime = cg.time;
ex->endTime = ex->startTime + 500;
VectorCopy ( origin, ex->refEntity.origin);
ex->refEntity.reType = RT_SPRITE;
ex->refEntity.rotation = rand() % 360;
ex->refEntity.radius = 24;
ex->refEntity.customShader = cgs.media.bloodExplosionShader;
// don't show player's own blood in view
if ( entityNum == cg.snap->ps.clientNum ) {
ex->refEntity.renderfx |= RF_THIRD_PERSON;
}
}
/*
==================
CG_SpurtBlood (LEILEI)
==================
*/
void CG_SpurtBlood( vec3_t origin, vec3_t velocity, int hard ) {
localEntity_t *blood;
// if ( !cg_blood.integer ) { return; }
velocity[0] = velocity[0] * hard * crandom()*460;
velocity[1] = velocity[1] * hard * crandom()*460;
velocity[2] = velocity[2] * hard * crandom()*566 + 65;
blood = CG_SmokePuff( origin, velocity,
21, // radius
1, 1, 1, 1, // color
2450, // trailTime
cg.time, // startTime
0, // fadeInTime
0, // flags
cgs.media.lbldShader1 );
// use the optimized version
blood->leType = LE_FALL_SCALE_FADE;
blood->leType = LE_GORE;
blood->pos.trType = TR_GRAVITY;
VectorCopy( velocity, blood->pos.trDelta );
blood->pos.trDelta[2] = 55;
if (crandom() < 0.5){
blood->leMarkType = LEMT_BURN;
blood->leBounceSoundType = LEBS_BLOOD;
}
// VectorCopy( velocity, blood->pos.trDelta );
}
/*
==================
CG_LaunchGib
==================
*/
void CG_LaunchGib( vec3_t origin, vec3_t velocity, qhandle_t hModel ) {
localEntity_t *le;
refEntity_t *re;
le = CG_AllocLocalEntity();
re = &le->refEntity;
le->leType = LE_FRAGMENT;
le->startTime = cg.time;
le->endTime = le->startTime + 5000 + random() * 3000;
VectorCopy( origin, re->origin );
AxisCopy( axisDefault, re->axis );
re->hModel = hModel;
le->pos.trType = TR_GRAVITY;
VectorCopy( origin, le->pos.trBase );
VectorCopy( velocity, le->pos.trDelta );
le->pos.trTime = cg.time;
le->bounceFactor = 0.6f;
le->leBounceSoundType = LEBS_BLOOD;
le->leMarkType = LEMT_BLOOD;
if ( cg_leiSuperGoreyAwesome.integer ) {
CG_SpurtBlood( origin, velocity, 7); // LEILEI toss some extra juice
CG_SpurtBlood( origin, velocity, 22);
CG_SpurtBlood( origin, velocity, 11);
}
}
/*
===================
CG_GibPlayer
Generated a bunch of gibs launching out from the bodies location
===================
*/
#define GIB_VELOCITY 250
#define GIB_JUMP 250
void CG_GibPlayer( vec3_t playerOrigin ) {
vec3_t origin, velocity;
if ( !cg_blood.integer ) {
return;
}
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
if ( rand() & 1 ) {
CG_LaunchGib( origin, velocity, cgs.media.gibSkull );
} else {
CG_LaunchGib( origin, velocity, cgs.media.gibBrain );
}
// allow gibs to be turned off for speed
if ( !cg_gibs.integer ) {
return;
}
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
CG_LaunchGib( origin, velocity, cgs.media.gibAbdomen );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
CG_LaunchGib( origin, velocity, cgs.media.gibArm );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
CG_LaunchGib( origin, velocity, cgs.media.gibChest );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
CG_LaunchGib( origin, velocity, cgs.media.gibFist );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
CG_LaunchGib( origin, velocity, cgs.media.gibFoot );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
CG_LaunchGib( origin, velocity, cgs.media.gibForearm );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
CG_LaunchGib( origin, velocity, cgs.media.gibIntestine );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
CG_LaunchGib( origin, velocity, cgs.media.gibLeg );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*GIB_VELOCITY;
velocity[1] = crandom()*GIB_VELOCITY;
velocity[2] = GIB_JUMP + crandom()*GIB_VELOCITY;
CG_LaunchGib( origin, velocity, cgs.media.gibLeg );
}
/*
==================
CG_LaunchGib
==================
*/
void CG_LaunchExplode( vec3_t origin, vec3_t velocity, qhandle_t hModel ) {
localEntity_t *le;
refEntity_t *re;
le = CG_AllocLocalEntity();
re = &le->refEntity;
le->leType = LE_FRAGMENT;
le->startTime = cg.time;
le->endTime = le->startTime + 10000 + random() * 6000;
VectorCopy( origin, re->origin );
AxisCopy( axisDefault, re->axis );
re->hModel = hModel;
le->pos.trType = TR_GRAVITY;
VectorCopy( origin, le->pos.trBase );
VectorCopy( velocity, le->pos.trDelta );
le->pos.trTime = cg.time;
le->bounceFactor = 0.1f;
le->leBounceSoundType = LEBS_BRASS;
le->leMarkType = LEMT_NONE;
}
#define EXP_VELOCITY 100
#define EXP_JUMP 150
/*
===================
CG_GibPlayer
Generated a bunch of gibs launching out from the bodies location
===================
*/
void CG_BigExplosion( vec3_t playerOrigin ) {
vec3_t origin, velocity;
if ( !cg_blood.integer ) {
return;
}
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*EXP_VELOCITY;
velocity[1] = crandom()*EXP_VELOCITY;
velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*EXP_VELOCITY;
velocity[1] = crandom()*EXP_VELOCITY;
velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*EXP_VELOCITY*1.5;
velocity[1] = crandom()*EXP_VELOCITY*1.5;
velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*EXP_VELOCITY*2.0;
velocity[1] = crandom()*EXP_VELOCITY*2.0;
velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
VectorCopy( playerOrigin, origin );
velocity[0] = crandom()*EXP_VELOCITY*2.5;
velocity[1] = crandom()*EXP_VELOCITY*2.5;
velocity[2] = EXP_JUMP + crandom()*EXP_VELOCITY;
CG_LaunchExplode( origin, velocity, cgs.media.smoke2 );
}

1112
code/cgame/cg_ents.c Normal file

File diff suppressed because it is too large Load Diff

1374
code/cgame/cg_event.c Normal file

File diff suppressed because it is too large Load Diff

312
code/cgame/cg_info.c Normal file
View File

@@ -0,0 +1,312 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_info.c -- display information while data is being loading
#include "cg_local.h"
#define MAX_LOADING_PLAYER_ICONS 16
#define MAX_LOADING_ITEM_ICONS 26
static int loadingPlayerIconCount;
static int loadingItemIconCount;
static qhandle_t loadingPlayerIcons[MAX_LOADING_PLAYER_ICONS];
static qhandle_t loadingItemIcons[MAX_LOADING_ITEM_ICONS];
/*
===================
CG_DrawLoadingIcons
===================
*/
static void CG_DrawLoadingIcons( void ) {
int n;
int x, y;
for( n = 0; n < loadingPlayerIconCount; n++ ) {
x = 16 + n * 78;
y = 324-40;
CG_DrawPic( x, y, 64, 64, loadingPlayerIcons[n] );
}
for( n = 0; n < loadingItemIconCount; n++ ) {
y = 400-40;
if( n >= 13 ) {
y += 40;
}
x = 16 + n % 13 * 48;
CG_DrawPic( x, y, 32, 32, loadingItemIcons[n] );
}
}
/*
======================
CG_LoadingString
======================
*/
void CG_LoadingString( const char *s ) {
Q_strncpyz( cg.infoScreenText, s, sizeof( cg.infoScreenText ) );
trap_UpdateScreen();
}
/*
===================
CG_LoadingItem
===================
*/
void CG_LoadingItem( int itemNum ) {
gitem_t *item;
item = &bg_itemlist[itemNum];
if ( item->icon && loadingItemIconCount < MAX_LOADING_ITEM_ICONS ) {
loadingItemIcons[loadingItemIconCount++] = trap_R_RegisterShaderNoMip( item->icon );
}
CG_LoadingString( item->pickup_name );
}
/*
===================
CG_LoadingClient
===================
*/
void CG_LoadingClient( int clientNum ) {
const char *info;
char *skin;
char personality[MAX_QPATH];
char model[MAX_QPATH];
char iconName[MAX_QPATH];
info = CG_ConfigString( CS_PLAYERS + clientNum );
if ( loadingPlayerIconCount < MAX_LOADING_PLAYER_ICONS ) {
Q_strncpyz( model, Info_ValueForKey( info, "model" ), sizeof( model ) );
skin = strrchr( model, '/' );
if ( skin ) {
*skin++ = '\0';
} else {
skin = "default";
}
Com_sprintf( iconName, MAX_QPATH, "models/players/%s/icon_%s.tga", model, skin );
loadingPlayerIcons[loadingPlayerIconCount] = trap_R_RegisterShaderNoMip( iconName );
if ( !loadingPlayerIcons[loadingPlayerIconCount] ) {
Com_sprintf( iconName, MAX_QPATH, "models/players/characters/%s/icon_%s.tga", model, skin );
loadingPlayerIcons[loadingPlayerIconCount] = trap_R_RegisterShaderNoMip( iconName );
}
if ( !loadingPlayerIcons[loadingPlayerIconCount] ) {
Com_sprintf( iconName, MAX_QPATH, "models/players/%s/icon_%s.tga", DEFAULT_MODEL, "default" );
loadingPlayerIcons[loadingPlayerIconCount] = trap_R_RegisterShaderNoMip( iconName );
}
if ( loadingPlayerIcons[loadingPlayerIconCount] ) {
loadingPlayerIconCount++;
}
}
Q_strncpyz( personality, Info_ValueForKey( info, "n" ), sizeof(personality) );
Q_CleanStr( personality );
if( cgs.gametype == GT_SINGLE_PLAYER ) {
trap_S_RegisterSound( va( "sound/player/announce/%s.wav", personality ), qtrue );
}
CG_LoadingString( personality );
}
/*
====================
CG_DrawInformation
Draw all the status / pacifier stuff during level loading
====================
*/
void CG_DrawInformation( void ) {
const char *s;
const char *info;
const char *sysInfo;
int y;
int value;
qhandle_t levelshot;
qhandle_t detail;
char buf[1024];
info = CG_ConfigString( CS_SERVERINFO );
sysInfo = CG_ConfigString( CS_SYSTEMINFO );
s = Info_ValueForKey( info, "mapname" );
levelshot = trap_R_RegisterShaderNoMip( va( "levelshots/%s.tga", s ) );
if ( !levelshot ) {
levelshot = trap_R_RegisterShaderNoMip( "menu/art/unknownmap" );
}
trap_R_SetColor( NULL );
CG_DrawPic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, levelshot );
// blend a detail texture over it
detail = trap_R_RegisterShader( "levelShotDetail" );
trap_R_DrawStretchPic( 0, 0, cgs.glconfig.vidWidth, cgs.glconfig.vidHeight, 0, 0, 2.5, 2, detail );
// draw the icons of things as they are loaded
CG_DrawLoadingIcons();
// the first 150 rows are reserved for the client connection
// screen to write into
if ( cg.infoScreenText[0] ) {
UI_DrawProportionalString( 320, 128-32, va("Loading... %s", cg.infoScreenText),
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
} else {
UI_DrawProportionalString( 320, 128-32, "Awaiting snapshot...",
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
}
// draw info string information
y = 180-32;
// don't print server lines if playing a local game
trap_Cvar_VariableStringBuffer( "sv_running", buf, sizeof( buf ) );
if ( !atoi( buf ) ) {
// server hostname
Q_strncpyz(buf, Info_ValueForKey( info, "sv_hostname" ), 1024);
Q_CleanStr(buf);
UI_DrawProportionalString( 320, y, buf,
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
y += PROP_HEIGHT;
// pure server
s = Info_ValueForKey( sysInfo, "sv_pure" );
if ( s[0] == '1' ) {
UI_DrawProportionalString( 320, y, "Pure Server",
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
y += PROP_HEIGHT;
}
// server-specific message of the day
s = CG_ConfigString( CS_MOTD );
if ( s[0] ) {
UI_DrawProportionalString( 320, y, s,
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
y += PROP_HEIGHT;
}
// some extra space after hostname and motd
y += 10;
}
// map-specific message (long map name)
s = CG_ConfigString( CS_MESSAGE );
if ( s[0] ) {
UI_DrawProportionalString( 320, y, s,
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
y += PROP_HEIGHT;
}
// cheats warning
s = Info_ValueForKey( sysInfo, "sv_cheats" );
if ( s[0] == '1' ) {
UI_DrawProportionalString( 320, y, "CHEATS ARE ENABLED",
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
y += PROP_HEIGHT;
}
// game type
switch ( cgs.gametype ) {
case GT_FFA:
s = "Free For All";
break;
case GT_SINGLE_PLAYER:
s = "Single Player";
break;
case GT_TOURNAMENT:
s = "Tournament";
break;
case GT_TEAM:
s = "Team Deathmatch";
break;
case GT_CTF:
s = "Capture The Flag";
break;
//#ifdef MISSIONPACK
case GT_1FCTF:
s = "One Flag CTF";
break;
case GT_OBELISK:
s = "Overload";
break;
case GT_HARVESTER:
s = "Harvester";
break;
//#endif
case GT_ELIMINATION:
s = "Elimination";
break;
case GT_CTF_ELIMINATION:
s = " CTF Elimination";
break;
case GT_LMS:
s = "Last Man Standing";
break;
case GT_DOUBLE_D:
s = "Double Domination";
break;
case GT_DOMINATION:
s = "Domination";
break;
default:
s = "Unknown Gametype";
break;
}
UI_DrawProportionalString( 320, y, s,
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
y += PROP_HEIGHT;
value = atoi( Info_ValueForKey( info, "timelimit" ) );
if ( value ) {
UI_DrawProportionalString( 320, y, va( "timelimit %i", value ),
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
y += PROP_HEIGHT;
}
if (cgs.gametype < GT_CTF || cgs.ffa_gt>0) {
value = atoi( Info_ValueForKey( info, "fraglimit" ) );
if ( value ) {
UI_DrawProportionalString( 320, y, va( "fraglimit %i", value ),
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
y += PROP_HEIGHT;
}
}
if (cgs.gametype >= GT_CTF && cgs.ffa_gt == 0) {
value = atoi( Info_ValueForKey( info, "capturelimit" ) );
if ( value ) {
UI_DrawProportionalString( 320, y, va( "capturelimit %i", value ),
UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, colorWhite );
y += PROP_HEIGHT;
}
}
}

1898
code/cgame/cg_local.h Normal file

File diff suppressed because it is too large Load Diff

1101
code/cgame/cg_localents.c Normal file

File diff suppressed because it is too large Load Diff

2348
code/cgame/cg_main.c Normal file

File diff suppressed because it is too large Load Diff

2563
code/cgame/cg_marks.c Normal file

File diff suppressed because it is too large Load Diff

1867
code/cgame/cg_newdraw.c Normal file

File diff suppressed because it is too large Load Diff

2019
code/cgame/cg_particles.c Normal file

File diff suppressed because it is too large Load Diff

2624
code/cgame/cg_players.c Normal file

File diff suppressed because it is too large Load Diff

536
code/cgame/cg_playerstate.c Normal file
View File

@@ -0,0 +1,536 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_playerstate.c -- this file acts on changes in a new playerState_t
// With normal play, this will be done after local prediction, but when
// following another player or playing back a demo, it will be checked
// when the snapshot transitions like all the other entities
#include "cg_local.h"
/*
==============
CG_CheckAmmo
If the ammo has gone low enough to generate the warning, play a sound
==============
*/
void CG_CheckAmmo( void ) {
int i;
int total;
int previous;
int weapons;
// see about how many seconds of ammo we have remaining
weapons = cg.snap->ps.stats[ STAT_WEAPONS ];
total = 0;
for ( i = WP_MACHINEGUN ; i < WP_NUM_WEAPONS ; i++ ) {
if ( ! ( weapons & ( 1 << i ) ) || i == WP_GRAPPLING_HOOK ) {
continue;
}
switch ( i ) {
case WP_ROCKET_LAUNCHER:
case WP_GRENADE_LAUNCHER:
case WP_RAILGUN:
case WP_SHOTGUN:
//#ifdef MISSIONPACK
case WP_PROX_LAUNCHER:
//#endif
total += cg.snap->ps.ammo[i] * 1000;
break;
default:
total += cg.snap->ps.ammo[i] * 200;
break;
}
if ( total >= 5000 ) {
cg.lowAmmoWarning = 0;
return;
}
}
previous = cg.lowAmmoWarning;
if ( total == 0 ) {
cg.lowAmmoWarning = 2;
} else {
cg.lowAmmoWarning = 1;
}
// play a sound on transitions
if ( cg.lowAmmoWarning != previous ) {
trap_S_StartLocalSound( cgs.media.noAmmoSound, CHAN_LOCAL_SOUND );
}
}
/*
==============
CG_DamageFeedback
==============
*/
void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) {
float left, front, up;
float kick;
int health;
float scale;
vec3_t dir;
vec3_t angles;
float dist;
float yaw, pitch;
// show the attacking player's head and name in corner
cg.attackerTime = cg.time;
// the lower on health you are, the greater the view kick will be
health = cg.snap->ps.stats[STAT_HEALTH];
if ( health < 40 ) {
scale = 1;
} else {
scale = 40.0 / health;
}
kick = damage * scale;
if (kick < 5)
kick = 5;
if (kick > 10)
kick = 10;
// if yaw and pitch are both 255, make the damage always centered (falling, etc)
if ( yawByte == 255 && pitchByte == 255 ) {
cg.damageX = 0;
cg.damageY = 0;
cg.v_dmg_roll = 0;
cg.v_dmg_pitch = -kick;
} else {
// positional
pitch = pitchByte / 255.0 * 360;
yaw = yawByte / 255.0 * 360;
angles[PITCH] = pitch;
angles[YAW] = yaw;
angles[ROLL] = 0;
AngleVectors( angles, dir, NULL, NULL );
VectorSubtract( vec3_origin, dir, dir );
front = DotProduct (dir, cg.refdef.viewaxis[0] );
left = DotProduct (dir, cg.refdef.viewaxis[1] );
up = DotProduct (dir, cg.refdef.viewaxis[2] );
dir[0] = front;
dir[1] = left;
dir[2] = 0;
dist = VectorLength( dir );
if ( dist < 0.1 ) {
dist = 0.1f;
}
cg.v_dmg_roll = kick * left;
cg.v_dmg_pitch = -kick * front;
if ( front <= 0.1 ) {
front = 0.1f;
}
cg.damageX = -left / front;
cg.damageY = up / dist;
}
// clamp the position
if ( cg.damageX > 1.0 ) {
cg.damageX = 1.0;
}
if ( cg.damageX < - 1.0 ) {
cg.damageX = -1.0;
}
if ( cg.damageY > 1.0 ) {
cg.damageY = 1.0;
}
if ( cg.damageY < - 1.0 ) {
cg.damageY = -1.0;
}
// don't let the screen flashes vary as much
if ( kick > 10 ) {
kick = 10;
}
cg.damageValue = kick;
cg.v_dmg_time = cg.time + DAMAGE_TIME;
cg.damageTime = cg.snap->serverTime;
}
/*
================
CG_Respawn
A respawn happened this snapshot
================
*/
void CG_Respawn( void ) {
// no error decay on player movement
cg.thisFrameTeleport = qtrue;
// display weapons available
cg.weaponSelectTime = cg.time;
// select the weapon the server says we are using
cg.weaponSelect = cg.snap->ps.weapon;
}
extern char *eventnames[];
/*
==============
CG_CheckPlayerstateEvents
==============
*/
void CG_CheckPlayerstateEvents( playerState_t *ps, playerState_t *ops ) {
int i;
int event;
centity_t *cent;
if ( ps->externalEvent && ps->externalEvent != ops->externalEvent ) {
cent = &cg_entities[ ps->clientNum ];
cent->currentState.event = ps->externalEvent;
cent->currentState.eventParm = ps->externalEventParm;
CG_EntityEvent( cent, cent->lerpOrigin );
}
cent = &cg.predictedPlayerEntity; // cg_entities[ ps->clientNum ];
// go through the predictable events buffer
for ( i = ps->eventSequence - MAX_PS_EVENTS ; i < ps->eventSequence ; i++ ) {
// if we have a new predictable event
if ( i >= ops->eventSequence
// or the server told us to play another event instead of a predicted event we already issued
// or something the server told us changed our prediction causing a different event
|| (i > ops->eventSequence - MAX_PS_EVENTS && ps->events[i & (MAX_PS_EVENTS-1)] != ops->events[i & (MAX_PS_EVENTS-1)]) ) {
event = ps->events[ i & (MAX_PS_EVENTS-1) ];
cent->currentState.event = event;
cent->currentState.eventParm = ps->eventParms[ i & (MAX_PS_EVENTS-1) ];
CG_EntityEvent( cent, cent->lerpOrigin );
cg.predictableEvents[ i & (MAX_PREDICTED_EVENTS-1) ] = event;
cg.eventSequence++;
}
}
}
/*
==================
CG_CheckChangedPredictableEvents
==================
*/
void CG_CheckChangedPredictableEvents( playerState_t *ps ) {
int i;
int event;
centity_t *cent;
cent = &cg.predictedPlayerEntity;
for ( i = ps->eventSequence - MAX_PS_EVENTS ; i < ps->eventSequence ; i++ ) {
//
if (i >= cg.eventSequence) {
continue;
}
// if this event is not further back in than the maximum predictable events we remember
if (i > cg.eventSequence - MAX_PREDICTED_EVENTS) {
// if the new playerstate event is different from a previously predicted one
if ( ps->events[i & (MAX_PS_EVENTS-1)] != cg.predictableEvents[i & (MAX_PREDICTED_EVENTS-1) ] ) {
event = ps->events[ i & (MAX_PS_EVENTS-1) ];
cent->currentState.event = event;
cent->currentState.eventParm = ps->eventParms[ i & (MAX_PS_EVENTS-1) ];
CG_EntityEvent( cent, cent->lerpOrigin );
cg.predictableEvents[ i & (MAX_PREDICTED_EVENTS-1) ] = event;
if ( cg_showmiss.integer ) {
CG_Printf("WARNING: changed predicted event\n");
}
}
}
}
}
/*
==================
pushReward
==================
*/
static void pushReward(sfxHandle_t sfx, qhandle_t shader, int rewardCount) {
if (cg.rewardStack < (MAX_REWARDSTACK-1)) {
cg.rewardStack++;
cg.rewardSound[cg.rewardStack] = sfx;
cg.rewardShader[cg.rewardStack] = shader;
cg.rewardCount[cg.rewardStack] = rewardCount;
}
}
/*
==================
CG_CheckLocalSounds
==================
*/
void CG_CheckLocalSounds( playerState_t *ps, playerState_t *ops ) {
int highScore, health, armor, reward;
sfxHandle_t sfx;
// don't play the sounds if the player just changed teams
if ( ps->persistant[PERS_TEAM] != ops->persistant[PERS_TEAM] ) {
return;
}
// hit changes
if ( ps->persistant[PERS_HITS] > ops->persistant[PERS_HITS] ) {
armor = ps->persistant[PERS_ATTACKEE_ARMOR] & 0xff;
health = ps->persistant[PERS_ATTACKEE_ARMOR] >> 8;
#ifdef MISSIONPACK
if (armor > 50 ) {
trap_S_StartLocalSound( cgs.media.hitSoundHighArmor, CHAN_LOCAL_SOUND );
} else if (armor || health > 100) {
trap_S_StartLocalSound( cgs.media.hitSoundLowArmor, CHAN_LOCAL_SOUND );
} else {
trap_S_StartLocalSound( cgs.media.hitSound, CHAN_LOCAL_SOUND );
}
#else
trap_S_StartLocalSound( cgs.media.hitSound, CHAN_LOCAL_SOUND );
#endif
} else if ( ps->persistant[PERS_HITS] < ops->persistant[PERS_HITS] ) {
trap_S_StartLocalSound( cgs.media.hitTeamSound, CHAN_LOCAL_SOUND );
}
// health changes of more than -1 should make pain sounds
if ( ps->stats[STAT_HEALTH] < ops->stats[STAT_HEALTH] - 1 ) {
if ( ps->stats[STAT_HEALTH] > 0 ) {
CG_PainEvent( &cg.predictedPlayerEntity, ps->stats[STAT_HEALTH] );
}
}
// if we are going into the intermission, don't start any voices
if ( cg.intermissionStarted ) {
return;
}
// reward sounds
reward = qfalse;
if (ps->persistant[PERS_CAPTURES] != ops->persistant[PERS_CAPTURES]) {
pushReward(cgs.media.captureAwardSound, cgs.media.medalCapture, ps->persistant[PERS_CAPTURES]);
reward = qtrue;
//Com_Printf("capture\n");
}
if (ps->persistant[PERS_IMPRESSIVE_COUNT] != ops->persistant[PERS_IMPRESSIVE_COUNT]) {
#ifdef MISSIONPACK
if (ps->persistant[PERS_IMPRESSIVE_COUNT] == 1) {
sfx = cgs.media.firstImpressiveSound;
} else {
sfx = cgs.media.impressiveSound;
}
#else
sfx = cgs.media.impressiveSound;
#endif
pushReward(sfx, cgs.media.medalImpressive, ps->persistant[PERS_IMPRESSIVE_COUNT]);
reward = qtrue;
//Com_Printf("impressive\n");
}
//KK-OAX We Just Won't Draw The Excellent Stuff if Multikills are Enabled!!!
if( !cgs.altExcellent ) {
if (ps->persistant[PERS_EXCELLENT_COUNT] != ops->persistant[PERS_EXCELLENT_COUNT]) {
#ifdef MISSIONPACK
if (ps->persistant[PERS_EXCELLENT_COUNT] == 1) {
sfx = cgs.media.firstExcellentSound;
} else {
sfx = cgs.media.excellentSound;
}
#else
sfx = cgs.media.excellentSound;
#endif
pushReward(sfx, cgs.media.medalExcellent, ps->persistant[PERS_EXCELLENT_COUNT]);
reward = qtrue;
//Com_Printf("excellent\n");
}
}
if (ps->persistant[PERS_GAUNTLET_FRAG_COUNT] != ops->persistant[PERS_GAUNTLET_FRAG_COUNT]) {
#ifdef MISSIONPACK
if (ops->persistant[PERS_GAUNTLET_FRAG_COUNT] == 1) {
sfx = cgs.media.firstHumiliationSound;
} else {
sfx = cgs.media.humiliationSound;
}
#else
sfx = cgs.media.humiliationSound;
#endif
pushReward(sfx, cgs.media.medalGauntlet, ps->persistant[PERS_GAUNTLET_FRAG_COUNT]);
reward = qtrue;
//Com_Printf("guantlet frag\n");
}
if (ps->persistant[PERS_DEFEND_COUNT] != ops->persistant[PERS_DEFEND_COUNT]) {
pushReward(cgs.media.defendSound, cgs.media.medalDefend, ps->persistant[PERS_DEFEND_COUNT]);
reward = qtrue;
//Com_Printf("defend\n");
}
if (ps->persistant[PERS_ASSIST_COUNT] != ops->persistant[PERS_ASSIST_COUNT]) {
pushReward(cgs.media.assistSound, cgs.media.medalAssist, ps->persistant[PERS_ASSIST_COUNT]);
reward = qtrue;
//Com_Printf("assist\n");
}
// if any of the player event bits changed
if (ps->persistant[PERS_PLAYEREVENTS] != ops->persistant[PERS_PLAYEREVENTS]) {
if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_DENIEDREWARD) !=
(ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_DENIEDREWARD)) {
trap_S_StartLocalSound( cgs.media.deniedSound, CHAN_ANNOUNCER );
}
else if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_GAUNTLETREWARD) !=
(ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_GAUNTLETREWARD)) {
trap_S_StartLocalSound( cgs.media.humiliationSound, CHAN_ANNOUNCER );
}
else if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_HOLYSHIT) !=
(ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_HOLYSHIT)) {
trap_S_StartLocalSound( cgs.media.holyShitSound, CHAN_ANNOUNCER );
}
reward = qtrue;
}
// check for flag pickup
if ( cgs.gametype > GT_TEAM ) {
if ((ps->powerups[PW_REDFLAG] != ops->powerups[PW_REDFLAG] && ps->powerups[PW_REDFLAG]) ||
(ps->powerups[PW_BLUEFLAG] != ops->powerups[PW_BLUEFLAG] && ps->powerups[PW_BLUEFLAG]) ||
(ps->powerups[PW_NEUTRALFLAG] != ops->powerups[PW_NEUTRALFLAG] && ps->powerups[PW_NEUTRALFLAG]) )
{
trap_S_StartLocalSound( cgs.media.youHaveFlagSound, CHAN_ANNOUNCER );
}
}
// lead changes
if (!reward) {
//
if ( !cg.warmup ) {
// never play lead changes during warmup
if ( ps->persistant[PERS_RANK] != ops->persistant[PERS_RANK] ) {
if ( cgs.gametype < GT_TEAM || cgs.ffa_gt==1) {
if ( ps->persistant[PERS_RANK] == 0 ) {
CG_AddBufferedSound(cgs.media.takenLeadSound);
} else if ( ps->persistant[PERS_RANK] == RANK_TIED_FLAG ) {
CG_AddBufferedSound(cgs.media.tiedLeadSound);
} else if ( ( ops->persistant[PERS_RANK] & ~RANK_TIED_FLAG ) == 0 ) {
CG_AddBufferedSound(cgs.media.lostLeadSound);
}
}
}
}
}
// timelimit warnings
if ( cgs.timelimit > 0 && cgs.timelimit <= 1000 ) {
int msec;
msec = cg.time - cgs.levelStartTime;
if ( !( cg.timelimitWarnings & 4 ) && msec > ( cgs.timelimit * 60 + 2 ) * 1000 ) {
cg.timelimitWarnings |= 1 | 2 | 4;
trap_S_StartLocalSound( cgs.media.suddenDeathSound, CHAN_ANNOUNCER );
}
else if ( !( cg.timelimitWarnings & 2 ) && msec > (cgs.timelimit - 1) * 60 * 1000 ) {
cg.timelimitWarnings |= 1 | 2;
trap_S_StartLocalSound( cgs.media.oneMinuteSound, CHAN_ANNOUNCER );
}
else if ( cgs.timelimit > 5 && !( cg.timelimitWarnings & 1 ) && msec > (cgs.timelimit - 5) * 60 * 1000 ) {
cg.timelimitWarnings |= 1;
trap_S_StartLocalSound( cgs.media.fiveMinuteSound, CHAN_ANNOUNCER );
}
}
// fraglimit warnings
if ( cgs.fraglimit > 0 && cgs.gametype < GT_CTF) {
highScore = cgs.scores1;
if (cgs.gametype == GT_TEAM && cgs.scores2 > highScore) {
highScore = cgs.scores2;
}
if ( !( cg.fraglimitWarnings & 4 ) && highScore == (cgs.fraglimit - 1) ) {
cg.fraglimitWarnings |= 1 | 2 | 4;
CG_AddBufferedSound(cgs.media.oneFragSound);
}
else if ( cgs.fraglimit > 2 && !( cg.fraglimitWarnings & 2 ) && highScore == (cgs.fraglimit - 2) ) {
cg.fraglimitWarnings |= 1 | 2;
CG_AddBufferedSound(cgs.media.twoFragSound);
}
else if ( cgs.fraglimit > 3 && !( cg.fraglimitWarnings & 1 ) && highScore == (cgs.fraglimit - 3) ) {
cg.fraglimitWarnings |= 1;
CG_AddBufferedSound(cgs.media.threeFragSound);
}
}
}
/*
===============
CG_TransitionPlayerState
===============
*/
void CG_TransitionPlayerState( playerState_t *ps, playerState_t *ops ) {
// check for changing follow mode
if ( ps->clientNum != ops->clientNum ) {
cg.thisFrameTeleport = qtrue;
// make sure we don't get any unwanted transition effects
*ops = *ps;
}
// damage events (player is getting wounded)
if ( ps->damageEvent != ops->damageEvent && ps->damageCount ) {
CG_DamageFeedback( ps->damageYaw, ps->damagePitch, ps->damageCount );
}
// respawning
if ( ps->persistant[PERS_SPAWN_COUNT] != ops->persistant[PERS_SPAWN_COUNT] ) {
CG_Respawn();
}
if ( cg.mapRestart ) {
CG_Respawn();
cg.mapRestart = qfalse;
}
if ( cg.snap->ps.pm_type != PM_INTERMISSION
&& ps->persistant[PERS_TEAM] != TEAM_SPECTATOR ) {
CG_CheckLocalSounds( ps, ops );
}
// check for going low on ammo
CG_CheckAmmo();
// run events
CG_CheckPlayerstateEvents( ps, ops );
// smooth the ducking viewheight change
if ( ps->viewheight != ops->viewheight ) {
cg.duckChange = ps->viewheight - ops->viewheight;
cg.duckTime = cg.time;
}
}

942
code/cgame/cg_predict.c Normal file
View File

@@ -0,0 +1,942 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_predict.c -- this file generates cg.predictedPlayerState by either
// interpolating between snapshots from the server or locally predicting
// ahead the client's movement.
// It also handles local physics interaction, like fragments bouncing off walls
#include "cg_local.h"
static pmove_t cg_pmove;
static int cg_numSolidEntities;
static centity_t *cg_solidEntities[MAX_ENTITIES_IN_SNAPSHOT];
static int cg_numTriggerEntities;
static centity_t *cg_triggerEntities[MAX_ENTITIES_IN_SNAPSHOT];
/*
====================
CG_BuildSolidList
When a new cg.snap has been set, this function builds a sublist
of the entities that are actually solid, to make for more
efficient collision detection
====================
*/
void CG_BuildSolidList( void ) {
int i;
centity_t *cent;
snapshot_t *snap;
entityState_t *ent;
cg_numSolidEntities = 0;
cg_numTriggerEntities = 0;
if ( cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport ) {
snap = cg.nextSnap;
} else {
snap = cg.snap;
}
for ( i = 0 ; i < snap->numEntities ; i++ ) {
cent = &cg_entities[ snap->entities[ i ].number ];
ent = &cent->currentState;
if ( ent->eType == ET_ITEM || ent->eType == ET_PUSH_TRIGGER || ent->eType == ET_TELEPORT_TRIGGER ) {
cg_triggerEntities[cg_numTriggerEntities] = cent;
cg_numTriggerEntities++;
continue;
}
if ( cent->nextState.solid ) {
cg_solidEntities[cg_numSolidEntities] = cent;
cg_numSolidEntities++;
continue;
}
}
}
/*
====================
CG_ClipMoveToEntities
====================
*/
static void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end,
int skipNumber, int mask, trace_t *tr ) {
int i, x, zd, zu;
trace_t trace;
entityState_t *ent;
clipHandle_t cmodel;
vec3_t bmins, bmaxs;
vec3_t origin, angles;
centity_t *cent;
for ( i = 0 ; i < cg_numSolidEntities ; i++ ) {
cent = cg_solidEntities[ i ];
ent = &cent->currentState;
if ( ent->number == skipNumber ) {
continue;
}
if ( ent->solid == SOLID_BMODEL ) {
// special value for bmodel
cmodel = trap_CM_InlineModel( ent->modelindex );
VectorCopy( cent->lerpAngles, angles );
BG_EvaluateTrajectory( &cent->currentState.pos, cg.physicsTime, origin );
} else {
// encoded bbox
x = (ent->solid & 255);
zd = ((ent->solid>>8) & 255);
zu = ((ent->solid>>16) & 255) - 32;
bmins[0] = bmins[1] = -x;
bmaxs[0] = bmaxs[1] = x;
bmins[2] = -zd;
bmaxs[2] = zu;
cmodel = trap_CM_TempBoxModel( bmins, bmaxs );
VectorCopy( vec3_origin, angles );
VectorCopy( cent->lerpOrigin, origin );
}
trap_CM_TransformedBoxTrace ( &trace, start, end,
mins, maxs, cmodel, mask, origin, angles);
if (trace.allsolid || trace.fraction < tr->fraction) {
trace.entityNum = ent->number;
*tr = trace;
} else if (trace.startsolid) {
tr->startsolid = qtrue;
}
if ( tr->allsolid ) {
return;
}
}
}
/*
================
CG_Trace
================
*/
void CG_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end,
int skipNumber, int mask ) {
trace_t t;
trap_CM_BoxTrace ( &t, start, end, mins, maxs, 0, mask);
t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE;
// check all other solid models
CG_ClipMoveToEntities (start, mins, maxs, end, skipNumber, mask, &t);
*result = t;
}
/*
================
CG_PointContents
================
*/
int CG_PointContents( const vec3_t point, int passEntityNum ) {
int i;
entityState_t *ent;
centity_t *cent;
clipHandle_t cmodel;
int contents;
contents = trap_CM_PointContents (point, 0);
for ( i = 0 ; i < cg_numSolidEntities ; i++ ) {
cent = cg_solidEntities[ i ];
ent = &cent->currentState;
if ( ent->number == passEntityNum ) {
continue;
}
if (ent->solid != SOLID_BMODEL) { // special value for bmodel
continue;
}
cmodel = trap_CM_InlineModel( ent->modelindex );
if ( !cmodel ) {
continue;
}
contents |= trap_CM_TransformedPointContents( point, cmodel, cent->lerpOrigin, cent->lerpAngles );
}
return contents;
}
/*
========================
CG_InterpolatePlayerState
Generates cg.predictedPlayerState by interpolating between
cg.snap->player_state and cg.nextFrame->player_state
========================
*/
static void CG_InterpolatePlayerState( qboolean grabAngles ) {
float f;
int i;
playerState_t *out;
snapshot_t *prev, *next;
out = &cg.predictedPlayerState;
prev = cg.snap;
next = cg.nextSnap;
*out = cg.snap->ps;
// if we are still allowing local input, short circuit the view angles
if ( grabAngles ) {
usercmd_t cmd;
int cmdNum;
cmdNum = trap_GetCurrentCmdNumber();
trap_GetUserCmd( cmdNum, &cmd );
PM_UpdateViewAngles( out, &cmd );
}
// if the next frame is a teleport, we can't lerp to it
if ( cg.nextFrameTeleport ) {
return;
}
if ( !next || next->serverTime <= prev->serverTime ) {
return;
}
f = (float)( cg.time - prev->serverTime ) / ( next->serverTime - prev->serverTime );
i = next->ps.bobCycle;
if ( i < prev->ps.bobCycle ) {
i += 256; // handle wraparound
}
out->bobCycle = prev->ps.bobCycle + f * ( i - prev->ps.bobCycle );
for ( i = 0 ; i < 3 ; i++ ) {
out->origin[i] = prev->ps.origin[i] + f * (next->ps.origin[i] - prev->ps.origin[i] );
if ( !grabAngles ) {
out->viewangles[i] = LerpAngle(
prev->ps.viewangles[i], next->ps.viewangles[i], f );
}
out->velocity[i] = prev->ps.velocity[i] +
f * (next->ps.velocity[i] - prev->ps.velocity[i] );
}
}
/*
===================
CG_TouchItem
===================
*/
static void CG_TouchItem( centity_t *cent ) {
gitem_t *item;
//For instantgib
qboolean canBePicked;
if(cgs.gametype == GT_ELIMINATION || cgs.gametype == GT_LMS)
return; //No weapon pickup in elimination
//normally we can
canBePicked = qtrue;
//But in instantgib, rocket arena, and CTF_ELIMINATION we normally can't:
if(cgs.nopickup || cgs.gametype == GT_CTF_ELIMINATION)
canBePicked = qfalse;
if ( !cg_predictItems.integer ) {
return;
}
if ( !BG_PlayerTouchesItem( &cg.predictedPlayerState, &cent->currentState, cg.time ) ) {
return;
}
// never pick an item up twice in a prediction
if ( cent->miscTime == cg.time ) {
return;
}
if ( !BG_CanItemBeGrabbed( cgs.gametype, &cent->currentState, &cg.predictedPlayerState ) ) {
return; // can't hold it
}
item = &bg_itemlist[ cent->currentState.modelindex ];
// Special case for flags.
// We don't predict touching our own flag
#if 1 //MISSIONPACK
if( cgs.gametype == GT_1FCTF ) {
if( item->giTag != PW_NEUTRALFLAG ) {
return;
}
}
if( cgs.gametype == GT_CTF || cgs.gametype == GT_CTF_ELIMINATION || cgs.gametype == GT_HARVESTER ) {
#else
if( cgs.gametype == GT_CTF || cgs.gametype == GT_CTF_ELIMINATION ) {
#endif
if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_RED &&
item->giTag == PW_REDFLAG)
return;
if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_BLUE &&
item->giTag == PW_BLUEFLAG)
return;
//Even in instantgib, we can predict our enemy flag
if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_RED &&
item->giTag == PW_BLUEFLAG && (!(cgs.elimflags&EF_ONEWAY) || cgs.attackingTeam == TEAM_RED))
canBePicked = qtrue;
if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_BLUE &&
item->giTag == PW_REDFLAG && (!(cgs.elimflags&EF_ONEWAY) || cgs.attackingTeam == TEAM_BLUE))
canBePicked = qtrue;
if (item->giTag == WP_RAILGUN)
canBePicked = qfalse;
if (item->giTag == WP_PLASMAGUN)
canBePicked = qfalse;
}
//Currently we don't predict anything in Double Domination because it looks like we take a flag
if( cgs.gametype == GT_DOUBLE_D ) {
if(cgs.redflag == TEAM_NONE)
return; //Can never pick if just one flag is NONE (because then the other is too)
if(item->giTag == PW_REDFLAG){ //at point A
if(cgs.redflag != cg.predictedPlayerState.persistant[PERS_TEAM]) //not already taken
trap_S_StartLocalSound( cgs.media.hitSound , CHAN_ANNOUNCER );
return;
}
if(item->giTag == PW_BLUEFLAG){ //at point B
if(cgs.blueflag != cg.predictedPlayerState.persistant[PERS_TEAM]) //already taken
trap_S_StartLocalSound( cgs.media.hitSound , CHAN_ANNOUNCER );
return;
}
}
// grab it
if(canBePicked)
{
BG_AddPredictableEventToPlayerstate( EV_ITEM_PICKUP, cent->currentState.modelindex , &cg.predictedPlayerState);
// remove it from the frame so it won't be drawn
cent->currentState.eFlags |= EF_NODRAW;
// don't touch it again this prediction
cent->miscTime = cg.time;
// if its a weapon, give them some predicted ammo so the autoswitch will work
if ( item->giType == IT_WEAPON ) {
cg.predictedPlayerState.stats[ STAT_WEAPONS ] |= 1 << item->giTag;
if ( !cg.predictedPlayerState.ammo[ item->giTag ] ) {
cg.predictedPlayerState.ammo[ item->giTag ] = 1;
}
}
}
}
/*
=========================
CG_TouchTriggerPrediction
Predict push triggers and items
=========================
*/
static void CG_TouchTriggerPrediction( void ) {
int i;
trace_t trace;
entityState_t *ent;
clipHandle_t cmodel;
centity_t *cent;
qboolean spectator;
// dead clients don't activate triggers
if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) {
return;
}
spectator = ( cg.predictedPlayerState.pm_type == PM_SPECTATOR );
if ( cg.predictedPlayerState.pm_type != PM_NORMAL && !spectator ) {
return;
}
for ( i = 0 ; i < cg_numTriggerEntities ; i++ ) {
cent = cg_triggerEntities[ i ];
ent = &cent->currentState;
if ( ent->eType == ET_ITEM && !spectator ) {
CG_TouchItem( cent );
continue;
}
if ( ent->solid != SOLID_BMODEL ) {
continue;
}
cmodel = trap_CM_InlineModel( ent->modelindex );
if ( !cmodel ) {
continue;
}
trap_CM_BoxTrace( &trace, cg.predictedPlayerState.origin, cg.predictedPlayerState.origin,
cg_pmove.mins, cg_pmove.maxs, cmodel, -1 );
if ( !trace.startsolid ) {
continue;
}
if ( ent->eType == ET_TELEPORT_TRIGGER ) {
cg.hyperspace = qtrue;
} else if ( ent->eType == ET_PUSH_TRIGGER ) {
BG_TouchJumpPad( &cg.predictedPlayerState, ent );
}
}
// if we didn't touch a jump pad this pmove frame
if ( cg.predictedPlayerState.jumppad_frame != cg.predictedPlayerState.pmove_framecount ) {
cg.predictedPlayerState.jumppad_frame = 0;
cg.predictedPlayerState.jumppad_ent = 0;
}
}
//unlagged - optimized prediction
#define ABS(x) ((x) < 0 ? (-(x)) : (x))
static int IsUnacceptableError( playerState_t *ps, playerState_t *pps ) {
vec3_t delta;
int i;
if ( pps->pm_type != ps->pm_type ||
pps->pm_flags != ps->pm_flags ||
pps->pm_time != ps->pm_time ) {
return 1;
}
VectorSubtract( pps->origin, ps->origin, delta );
if ( VectorLengthSquared( delta ) > 0.1f * 0.1f ) {
if ( cg_showmiss.integer ) {
CG_Printf("delta: %.2f ", VectorLength(delta) );
}
return 2;
}
VectorSubtract( pps->velocity, ps->velocity, delta );
if ( VectorLengthSquared( delta ) > 0.1f * 0.1f ) {
if ( cg_showmiss.integer ) {
CG_Printf("delta: %.2f ", VectorLength(delta) );
}
return 3;
}
if ( pps->weaponTime != ps->weaponTime ||
pps->gravity != ps->gravity ||
pps->speed != ps->speed ||
pps->delta_angles[0] != ps->delta_angles[0] ||
pps->delta_angles[1] != ps->delta_angles[1] ||
pps->delta_angles[2] != ps->delta_angles[2] ||
pps->groundEntityNum != ps->groundEntityNum ) {
return 4;
}
if ( pps->legsTimer != ps->legsTimer ||
pps->legsAnim != ps->legsAnim ||
pps->torsoTimer != ps->torsoTimer ||
pps->torsoAnim != ps->torsoAnim ||
pps->movementDir != ps->movementDir ) {
return 5;
}
VectorSubtract( pps->grapplePoint, ps->grapplePoint, delta );
if ( VectorLengthSquared( delta ) > 0.1f * 0.1f ) {
return 6;
}
if ( pps->eFlags != ps->eFlags ) {
return 7;
}
if ( pps->eventSequence != ps->eventSequence ) {
return 8;
}
for ( i = 0; i < MAX_PS_EVENTS; i++ ) {
if ( pps->events[i] != ps->events[i] ||
pps->eventParms[i] != ps->eventParms[i] ) {
return 9;
}
}
if ( pps->externalEvent != ps->externalEvent ||
pps->externalEventParm != ps->externalEventParm ||
pps->externalEventTime != ps->externalEventTime ) {
return 10;
}
if ( pps->clientNum != ps->clientNum ||
pps->weapon != ps->weapon ||
pps->weaponstate != ps->weaponstate ) {
return 11;
}
if ( ABS(pps->viewangles[0] - ps->viewangles[0]) > 1.0f ||
ABS(pps->viewangles[1] - ps->viewangles[1]) > 1.0f ||
ABS(pps->viewangles[2] - ps->viewangles[2]) > 1.0f ) {
return 12;
}
if ( pps->viewheight != ps->viewheight ) {
return 13;
}
if ( pps->damageEvent != ps->damageEvent ||
pps->damageYaw != ps->damageYaw ||
pps->damagePitch != ps->damagePitch ||
pps->damageCount != ps->damageCount ) {
return 14;
}
for ( i = 0; i < MAX_STATS; i++ ) {
if ( pps->stats[i] != ps->stats[i] ) {
return 15;
}
}
for ( i = 0; i < MAX_PERSISTANT; i++ ) {
if ( pps->persistant[i] != ps->persistant[i] ) {
return 16;
}
}
for ( i = 0; i < MAX_POWERUPS; i++ ) {
if ( pps->powerups[i] != ps->powerups[i] ) {
return 17;
}
}
for ( i = 0; i < MAX_WEAPONS; i++ ) {
if ( pps->ammo[i] != ps->ammo[i] ) {
return 18;
}
}
if ( pps->generic1 != ps->generic1 ||
pps->loopSound != ps->loopSound ||
pps->jumppad_ent != ps->jumppad_ent ) {
return 19;
}
return 0;
}
//unlagged - optimized prediction
/*
=================
CG_PredictPlayerState
Generates cg.predictedPlayerState for the current cg.time
cg.predictedPlayerState is guaranteed to be valid after exiting.
For demo playback, this will be an interpolation between two valid
playerState_t.
For normal gameplay, it will be the result of predicted usercmd_t on
top of the most recent playerState_t received from the server.
Each new snapshot will usually have one or more new usercmd over the last,
but we simulate all unacknowledged commands each time, not just the new ones.
This means that on an internet connection, quite a few pmoves may be issued
each frame.
OPTIMIZE: don't re-simulate unless the newly arrived snapshot playerState_t
differs from the predicted one. Would require saving all intermediate
playerState_t during prediction.
We detect prediction errors and allow them to be decayed off over several frames
to ease the jerk.
=================
*/
void CG_PredictPlayerState( void ) {
int cmdNum, current;
playerState_t oldPlayerState;
qboolean moved;
usercmd_t oldestCmd;
usercmd_t latestCmd;
//unlagged - optimized prediction
int stateIndex = 0, predictCmd = 0; //Sago: added initializing
int numPredicted = 0, numPlayedBack = 0; // debug code
//unlagged - optimized prediction
cg.hyperspace = qfalse; // will be set if touching a trigger_teleport
// if this is the first frame we must guarantee
// predictedPlayerState is valid even if there is some
// other error condition
if ( !cg.validPPS ) {
cg.validPPS = qtrue;
cg.predictedPlayerState = cg.snap->ps;
}
// demo playback just copies the moves
if ( cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW) ) {
CG_InterpolatePlayerState( qfalse );
return;
}
// non-predicting local movement will grab the latest angles
if ( cg_nopredict.integer || cg_synchronousClients.integer ) {
CG_InterpolatePlayerState( qtrue );
return;
}
// prepare for pmove
cg_pmove.ps = &cg.predictedPlayerState;
cg_pmove.trace = CG_Trace;
cg_pmove.pointcontents = CG_PointContents;
if ( cg_pmove.ps->pm_type == PM_DEAD ) {
cg_pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY;
}
else {
cg_pmove.tracemask = MASK_PLAYERSOLID;
}
if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR ) {
cg_pmove.tracemask &= ~CONTENTS_BODY; // spectators can fly through bodies
}
cg_pmove.noFootsteps = ( cgs.dmflags & DF_NO_FOOTSTEPS ) > 0;
// save the state before the pmove so we can detect transitions
oldPlayerState = cg.predictedPlayerState;
current = trap_GetCurrentCmdNumber();
// if we don't have the commands right after the snapshot, we
// can't accurately predict a current position, so just freeze at
// the last good position we had
cmdNum = current - CMD_BACKUP + 1;
trap_GetUserCmd( cmdNum, &oldestCmd );
if ( oldestCmd.serverTime > cg.snap->ps.commandTime
&& oldestCmd.serverTime < cg.time ) { // special check for map_restart
if ( cg_showmiss.integer ) {
CG_Printf ("exceeded PACKET_BACKUP on commands\n");
}
return;
}
// get the latest command so we can know which commands are from previous map_restarts
trap_GetUserCmd( current, &latestCmd );
// get the most recent information we have, even if
// the server time is beyond our current cg.time,
// because predicted player positions are going to
// be ahead of everything else anyway
if ( cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport ) {
cg.predictedPlayerState = cg.nextSnap->ps;
cg.physicsTime = cg.nextSnap->serverTime;
} else {
cg.predictedPlayerState = cg.snap->ps;
cg.physicsTime = cg.snap->serverTime;
}
if ( pmove_msec.integer < 8 ) {
trap_Cvar_Set("pmove_msec", "8");
}
else if (pmove_msec.integer > 33) {
trap_Cvar_Set("pmove_msec", "33");
}
cg_pmove.pmove_fixed = pmove_fixed.integer;// | cg_pmove_fixed.integer;
cg_pmove.pmove_msec = pmove_msec.integer;
cg_pmove.pmove_float = pmove_float.integer;
cg_pmove.pmove_flags = cgs.dmflags;
//unlagged - optimized prediction
// Like the comments described above, a player's state is entirely
// re-predicted from the last valid snapshot every client frame, which
// can be really, really, really slow. Every old command has to be
// run again. For every client frame that is *not* directly after a
// snapshot, this is unnecessary, since we have no new information.
// For those, we'll play back the predictions from the last frame and
// predict only the newest commands. Essentially, we'll be doing
// an incremental predict instead of a full predict.
//
// If we have a new snapshot, we can compare its player state's command
// time to the command times in the queue to find a match. If we find
// a matching state, and the predicted version has not deviated, we can
// use the predicted state as a base - and also do an incremental predict.
//
// With this method, we get incremental predicts on every client frame
// except a frame following a new snapshot in which there was a prediction
// error. This yeilds anywhere from a 15% to 40% performance increase,
// depending on how much of a bottleneck the CPU is.
if ( cg_optimizePrediction.integer ) {
if ( cg.nextFrameTeleport || cg.thisFrameTeleport ) {
// do a full predict
cg.lastPredictedCommand = 0;
cg.stateTail = cg.stateHead;
predictCmd = current - CMD_BACKUP + 1;
}
// cg.physicsTime is the current snapshot's serverTime
// if it's the same as the last one
else if ( cg.physicsTime == cg.lastServerTime ) {
// we have no new information, so do an incremental predict
predictCmd = cg.lastPredictedCommand + 1;
}
else {
// we have a new snapshot
int i;
qboolean error = qtrue;
// loop through the saved states queue
for ( i = cg.stateHead; i != cg.stateTail; i = (i + 1) % NUM_SAVED_STATES ) {
// if we find a predicted state whose commandTime matches the snapshot player state's commandTime
if ( cg.savedPmoveStates[i].commandTime == cg.predictedPlayerState.commandTime ) {
// make sure the state differences are acceptable
int errorcode = IsUnacceptableError( &cg.predictedPlayerState, &cg.savedPmoveStates[i] );
// too much change?
if ( errorcode ) {
if ( cg_showmiss.integer ) {
CG_Printf("errorcode %d at %d\n", errorcode, cg.time);
}
// yeah, so do a full predict
break;
}
// this one is almost exact, so we'll copy it in as the starting point
*cg_pmove.ps = cg.savedPmoveStates[i];
// advance the head
cg.stateHead = (i + 1) % NUM_SAVED_STATES;
// set the next command to predict
predictCmd = cg.lastPredictedCommand + 1;
// a saved state matched, so flag it
error = qfalse;
break;
}
}
// if no saved states matched
if ( error ) {
// do a full predict
cg.lastPredictedCommand = 0;
cg.stateTail = cg.stateHead;
predictCmd = current - CMD_BACKUP + 1;
}
}
// keep track of the server time of the last snapshot so we
// know when we're starting from a new one in future calls
cg.lastServerTime = cg.physicsTime;
stateIndex = cg.stateHead;
}
//unlagged - optimized prediction
// run cmds
moved = qfalse;
for ( cmdNum = current - CMD_BACKUP + 1 ; cmdNum <= current ; cmdNum++ ) {
// get the command
trap_GetUserCmd( cmdNum, &cg_pmove.cmd );
if ( cg_pmove.pmove_fixed ) {
PM_UpdateViewAngles( cg_pmove.ps, &cg_pmove.cmd );
}
// don't do anything if the time is before the snapshot player time
if ( cg_pmove.cmd.serverTime <= cg.predictedPlayerState.commandTime ) {
continue;
}
// don't do anything if the command was from a previous map_restart
if ( cg_pmove.cmd.serverTime > latestCmd.serverTime ) {
continue;
}
// check for a prediction error from last frame
// on a lan, this will often be the exact value
// from the snapshot, but on a wan we will have
// to predict several commands to get to the point
// we want to compare
if ( cg.predictedPlayerState.commandTime == oldPlayerState.commandTime ) {
vec3_t delta;
float len;
if ( cg.thisFrameTeleport ) {
// a teleport will not cause an error decay
VectorClear( cg.predictedError );
if ( cg_showmiss.integer ) {
CG_Printf( "PredictionTeleport\n" );
}
cg.thisFrameTeleport = qfalse;
} else {
vec3_t adjusted;
CG_AdjustPositionForMover( cg.predictedPlayerState.origin,
cg.predictedPlayerState.groundEntityNum, cg.physicsTime, cg.oldTime, adjusted );
if ( cg_showmiss.integer ) {
if (!VectorCompare( oldPlayerState.origin, adjusted )) {
CG_Printf("prediction error\n");
}
}
VectorSubtract( oldPlayerState.origin, adjusted, delta );
len = VectorLength( delta );
if ( len > 0.1 ) {
if ( cg_showmiss.integer ) {
CG_Printf("Prediction miss: %f\n", len);
}
if ( cg_errorDecay.integer ) {
int t;
float f;
t = cg.time - cg.predictedErrorTime;
f = ( cg_errorDecay.value - t ) / cg_errorDecay.value;
if ( f < 0 ) {
f = 0;
}
if ( f > 0 && cg_showmiss.integer ) {
CG_Printf("Double prediction decay: %f\n", f);
}
VectorScale( cg.predictedError, f, cg.predictedError );
} else {
VectorClear( cg.predictedError );
}
VectorAdd( delta, cg.predictedError, cg.predictedError );
cg.predictedErrorTime = cg.oldTime;
}
}
}
// don't predict gauntlet firing, which is only supposed to happen
// when it actually inflicts damage
cg_pmove.gauntletHit = qfalse;
if ( cg_pmove.pmove_fixed ) {
cg_pmove.cmd.serverTime = ((cg_pmove.cmd.serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer;
}
//unlagged - optimized prediction
if ( cg_optimizePrediction.integer ) {
// if we need to predict this command, or we've run out of space in the saved states queue
if ( cmdNum >= predictCmd || (stateIndex + 1) % NUM_SAVED_STATES == cg.stateHead ) {
// run the Pmove
Pmove (&cg_pmove);
numPredicted++; // debug code
// record the last predicted command
cg.lastPredictedCommand = cmdNum;
// if we haven't run out of space in the saved states queue
if ( (stateIndex + 1) % NUM_SAVED_STATES != cg.stateHead ) {
// save the state for the false case (of cmdNum >= predictCmd)
// in later calls to this function
cg.savedPmoveStates[stateIndex] = *cg_pmove.ps;
stateIndex = (stateIndex + 1) % NUM_SAVED_STATES;
cg.stateTail = stateIndex;
}
}
else {
numPlayedBack++; // debug code
if ( cg_showmiss.integer &&
cg.savedPmoveStates[stateIndex].commandTime != cg_pmove.cmd.serverTime) {
// this should ONLY happen just after changing the value of pmove_fixed
CG_Printf( "saved state miss\n" );
}
// play back the command from the saved states
*cg_pmove.ps = cg.savedPmoveStates[stateIndex];
// go to the next element in the saved states array
stateIndex = (stateIndex + 1) % NUM_SAVED_STATES;
}
}
else {
// run the Pmove
Pmove (&cg_pmove);
numPredicted++; // debug code
}
//unlagged - optimized prediction
moved = qtrue;
// add push trigger movement effects
CG_TouchTriggerPrediction();
// check for predictable events that changed from previous predictions
//CG_CheckChangedPredictableEvents(&cg.predictedPlayerState);
}
//unlagged - optimized prediction
// do a /condump after a few seconds of this
//CG_Printf("cg.time: %d, numPredicted: %d, numPlayedBack: %d\n", cg.time, numPredicted, numPlayedBack); // debug code
// if everything is working right, numPredicted should be 1 more than 98%
// of the time, meaning only ONE predicted move was done in the frame
// you should see other values for numPredicted after IsUnacceptableError
// returns nonzero, and that's it
//unlagged - optimized prediction
if ( cg_showmiss.integer > 1 ) {
CG_Printf( "[%i : %i] ", cg_pmove.cmd.serverTime, cg.time );
}
if ( !moved ) {
if ( cg_showmiss.integer ) {
CG_Printf( "not moved\n" );
}
return;
}
// adjust for the movement of the groundentity
CG_AdjustPositionForMover( cg.predictedPlayerState.origin,
cg.predictedPlayerState.groundEntityNum,
cg.physicsTime, cg.time, cg.predictedPlayerState.origin );
if ( cg_showmiss.integer ) {
if (cg.predictedPlayerState.eventSequence > oldPlayerState.eventSequence + MAX_PS_EVENTS) {
CG_Printf("WARNING: dropped event\n");
}
}
// fire events and other transition triggered things
CG_TransitionPlayerState( &cg.predictedPlayerState, &oldPlayerState );
if ( cg_showmiss.integer ) {
if (cg.eventSequence > cg.predictedPlayerState.eventSequence) {
CG_Printf("WARNING: double event\n");
cg.eventSequence = cg.predictedPlayerState.eventSequence;
}
}
}

238
code/cgame/cg_public.h Normal file
View File

@@ -0,0 +1,238 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
#define CMD_BACKUP 64
#define CMD_MASK (CMD_BACKUP - 1)
// allow a lot of command backups for very fast systems
// multiple commands may be combined into a single packet, so this
// needs to be larger than PACKET_BACKUP
#define MAX_ENTITIES_IN_SNAPSHOT 256
// snapshots are a view of the server at a given time
// Snapshots are generated at regular time intervals by the server,
// but they may not be sent if a client's rate level is exceeded, or
// they may be dropped by the network.
typedef struct {
int snapFlags; // SNAPFLAG_RATE_DELAYED, etc
int ping;
int serverTime; // server time the message is valid for (in msec)
byte areamask[MAX_MAP_AREA_BYTES]; // portalarea visibility bits
playerState_t ps; // complete information about the current player at this time
int numEntities; // all of the entities that need to be presented
entityState_t entities[MAX_ENTITIES_IN_SNAPSHOT]; // at the time of this snapshot
int numServerCommands; // text based server commands to execute when this
int serverCommandSequence; // snapshot becomes current
} snapshot_t;
enum {
CGAME_EVENT_NONE,
CGAME_EVENT_TEAMMENU,
CGAME_EVENT_SCOREBOARD,
CGAME_EVENT_EDITHUD
};
/*
==================================================================
functions imported from the main executable
==================================================================
*/
#define CGAME_IMPORT_API_VERSION 4
typedef enum {
CG_PRINT,
CG_ERROR,
CG_MILLISECONDS,
CG_CVAR_REGISTER,
CG_CVAR_UPDATE,
CG_CVAR_SET,
CG_CVAR_VARIABLESTRINGBUFFER,
CG_ARGC,
CG_ARGV,
CG_ARGS,
CG_FS_FOPENFILE,
CG_FS_READ,
CG_FS_WRITE,
CG_FS_FCLOSEFILE,
CG_SENDCONSOLECOMMAND,
CG_ADDCOMMAND,
CG_SENDCLIENTCOMMAND,
CG_UPDATESCREEN,
CG_CM_LOADMAP,
CG_CM_NUMINLINEMODELS,
CG_CM_INLINEMODEL,
CG_CM_LOADMODEL,
CG_CM_TEMPBOXMODEL,
CG_CM_POINTCONTENTS,
CG_CM_TRANSFORMEDPOINTCONTENTS,
CG_CM_BOXTRACE,
CG_CM_TRANSFORMEDBOXTRACE,
CG_CM_MARKFRAGMENTS,
CG_S_STARTSOUND,
CG_S_STARTLOCALSOUND,
CG_S_CLEARLOOPINGSOUNDS,
CG_S_ADDLOOPINGSOUND,
CG_S_UPDATEENTITYPOSITION,
CG_S_RESPATIALIZE,
CG_S_REGISTERSOUND,
CG_S_STARTBACKGROUNDTRACK,
CG_R_LOADWORLDMAP,
CG_R_REGISTERMODEL,
CG_R_REGISTERSKIN,
CG_R_REGISTERSHADER,
CG_R_CLEARSCENE,
CG_R_ADDREFENTITYTOSCENE,
CG_R_ADDPOLYTOSCENE,
CG_R_ADDLIGHTTOSCENE,
CG_R_RENDERSCENE,
CG_R_SETCOLOR,
CG_R_DRAWSTRETCHPIC,
CG_R_MODELBOUNDS,
CG_R_LERPTAG,
CG_GETGLCONFIG,
CG_GETGAMESTATE,
CG_GETCURRENTSNAPSHOTNUMBER,
CG_GETSNAPSHOT,
CG_GETSERVERCOMMAND,
CG_GETCURRENTCMDNUMBER,
CG_GETUSERCMD,
CG_SETUSERCMDVALUE,
CG_R_REGISTERSHADERNOMIP,
CG_MEMORY_REMAINING,
CG_R_REGISTERFONT,
CG_KEY_ISDOWN,
CG_KEY_GETCATCHER,
CG_KEY_SETCATCHER,
CG_KEY_GETKEY,
CG_PC_ADD_GLOBAL_DEFINE,
CG_PC_LOAD_SOURCE,
CG_PC_FREE_SOURCE,
CG_PC_READ_TOKEN,
CG_PC_SOURCE_FILE_AND_LINE,
CG_S_STOPBACKGROUNDTRACK,
CG_REAL_TIME,
CG_SNAPVECTOR,
CG_REMOVECOMMAND,
CG_R_LIGHTFORPOINT,
CG_CIN_PLAYCINEMATIC,
CG_CIN_STOPCINEMATIC,
CG_CIN_RUNCINEMATIC,
CG_CIN_DRAWCINEMATIC,
CG_CIN_SETEXTENTS,
CG_R_REMAP_SHADER,
CG_S_ADDREALLOOPINGSOUND,
CG_S_STOPLOOPINGSOUND,
CG_CM_TEMPCAPSULEMODEL,
CG_CM_CAPSULETRACE,
CG_CM_TRANSFORMEDCAPSULETRACE,
CG_R_ADDADDITIVELIGHTTOSCENE,
CG_GET_ENTITY_TOKEN,
CG_R_ADDPOLYSTOSCENE,
CG_R_INPVS,
// 1.32
CG_FS_SEEK,
/*
CG_LOADCAMERA,
CG_STARTCAMERA,
CG_GETCAMERAINFO,
*/
CG_MEMSET = 100,
CG_MEMCPY,
CG_STRNCPY,
CG_SIN,
CG_COS,
CG_ATAN2,
CG_SQRT,
CG_FLOOR,
CG_CEIL,
CG_TESTPRINTINT,
CG_TESTPRINTFLOAT,
CG_ACOS
} cgameImport_t;
/*
==================================================================
functions exported to the main executable
==================================================================
*/
typedef enum {
CG_INIT,
// void CG_Init( int serverMessageNum, int serverCommandSequence, int clientNum )
// called when the level loads or when the renderer is restarted
// all media should be registered at this time
// cgame will display loading status by calling SCR_Update, which
// will call CG_DrawInformation during the loading process
// reliableCommandSequence will be 0 on fresh loads, but higher for
// demos, tourney restarts, or vid_restarts
CG_SHUTDOWN,
// void (*CG_Shutdown)( void );
// oportunity to flush and close any open files
CG_CONSOLE_COMMAND,
// qboolean (*CG_ConsoleCommand)( void );
// a console command has been issued locally that is not recognized by the
// main game system.
// use Cmd_Argc() / Cmd_Argv() to read the command, return qfalse if the
// command is not known to the game
CG_DRAW_ACTIVE_FRAME,
// void (*CG_DrawActiveFrame)( int serverTime, stereoFrame_t stereoView, qboolean demoPlayback );
// Generates and draws a game scene and status information at the given time.
// If demoPlayback is set, local movement prediction will not be enabled
CG_CROSSHAIR_PLAYER,
// int (*CG_CrosshairPlayer)( void );
CG_LAST_ATTACKER,
// int (*CG_LastAttacker)( void );
CG_KEY_EVENT,
// void (*CG_KeyEvent)( int key, qboolean down );
CG_MOUSE_EVENT,
// void (*CG_MouseEvent)( int dx, int dy );
CG_EVENT_HANDLING
// void (*CG_EventHandling)(int type);
} cgameExport_t;
//----------------------------------------------

553
code/cgame/cg_scoreboard.c Normal file
View File

@@ -0,0 +1,553 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_scoreboard -- draw the scoreboard on top of the game screen
#include "cg_local.h"
#define SCOREBOARD_X (0)
#define SB_HEADER 86
#define SB_TOP (SB_HEADER+32)
// Where the status bar starts, so we don't overwrite it
#define SB_STATUSBAR 420
#define SB_NORMAL_HEIGHT 40
#define SB_INTER_HEIGHT 16 // interleaved height
#define SB_MAXCLIENTS_NORMAL ((SB_STATUSBAR - SB_TOP) / SB_NORMAL_HEIGHT)
#define SB_MAXCLIENTS_INTER ((SB_STATUSBAR - SB_TOP) / SB_INTER_HEIGHT - 1)
// Used when interleaved
#define SB_LEFT_BOTICON_X (SCOREBOARD_X+0)
#define SB_LEFT_HEAD_X (SCOREBOARD_X+32)
#define SB_RIGHT_BOTICON_X (SCOREBOARD_X+64)
#define SB_RIGHT_HEAD_X (SCOREBOARD_X+96)
// Normal
#define SB_BOTICON_X (SCOREBOARD_X+32)
#define SB_HEAD_X (SCOREBOARD_X+64)
#define SB_SCORELINE_X 112
#define SB_RATING_WIDTH (6 * BIGCHAR_WIDTH) // width 6
#define SB_SCORE_X (SB_SCORELINE_X + BIGCHAR_WIDTH) // width 6
#define SB_RATING_X (SB_SCORELINE_X + 6 * BIGCHAR_WIDTH) // width 6
#define SB_PING_X (SB_SCORELINE_X + 12 * BIGCHAR_WIDTH + 8) // width 5
#define SB_TIME_X (SB_SCORELINE_X + 17 * BIGCHAR_WIDTH + 8) // width 5
#define SB_NAME_X (SB_SCORELINE_X + 22 * BIGCHAR_WIDTH) // width 15
// The new and improved score board
//
// In cases where the number of clients is high, the score board heads are interleaved
// here's the layout
//
// 0 32 80 112 144 240 320 400 <-- pixel position
// bot head bot head score ping time name
//
// wins/losses are drawn on bot icon now
static qboolean localClient; // true if local client has been displayed
/*
=================
CG_DrawScoreboard
=================
*/
static void CG_DrawClientScore( int y, score_t *score, float *color, float fade, qboolean largeFormat ) {
char string[1024];
vec3_t headAngles;
clientInfo_t *ci;
int iconx, headx;
if ( score->client < 0 || score->client >= cgs.maxclients ) {
Com_Printf( "Bad score->client: %i\n", score->client );
return;
}
ci = &cgs.clientinfo[score->client];
iconx = SB_BOTICON_X + (SB_RATING_WIDTH / 2);
headx = SB_HEAD_X + (SB_RATING_WIDTH / 2);
// draw the handicap or bot skill marker (unless player has flag)
if ( ci->powerups & ( 1 << PW_NEUTRALFLAG ) ) {
if( largeFormat ) {
CG_DrawFlagModel( iconx, y - ( 32 - BIGCHAR_HEIGHT ) / 2, 32, 32, TEAM_FREE, qfalse );
}
else {
CG_DrawFlagModel( iconx, y, 16, 16, TEAM_FREE, qfalse );
}
} else if ( ci->powerups & ( 1 << PW_REDFLAG ) ) {
if( largeFormat ) {
CG_DrawFlagModel( iconx, y - ( 32 - BIGCHAR_HEIGHT ) / 2, 32, 32, TEAM_RED, qfalse );
}
else {
CG_DrawFlagModel( iconx, y, 16, 16, TEAM_RED, qfalse );
}
} else if ( ci->powerups & ( 1 << PW_BLUEFLAG ) ) {
if( largeFormat ) {
CG_DrawFlagModel( iconx, y - ( 32 - BIGCHAR_HEIGHT ) / 2, 32, 32, TEAM_BLUE, qfalse );
}
else {
CG_DrawFlagModel( iconx, y, 16, 16, TEAM_BLUE, qfalse );
}
} else {
if ( ci->botSkill > 0 && ci->botSkill <= 5 ) {
if ( cg_drawIcons.integer ) {
if( largeFormat ) {
CG_DrawPic( iconx, y - ( 32 - BIGCHAR_HEIGHT ) / 2, 32, 32, cgs.media.botSkillShaders[ ci->botSkill - 1 ] );
}
else {
CG_DrawPic( iconx, y, 16, 16, cgs.media.botSkillShaders[ ci->botSkill - 1 ] );
}
}
} else if ( ci->handicap < 100 ) {
Com_sprintf( string, sizeof( string ), "%i", ci->handicap );
if ( cgs.gametype == GT_TOURNAMENT )
CG_DrawSmallStringColor( iconx, y - SMALLCHAR_HEIGHT/2, string, color );
else
CG_DrawSmallStringColor( iconx, y, string, color );
}
// draw the wins / losses
if ( cgs.gametype == GT_TOURNAMENT ) {
Com_sprintf( string, sizeof( string ), "%i/%i", ci->wins, ci->losses );
if( ci->handicap < 100 && !ci->botSkill ) {
CG_DrawSmallStringColor( iconx, y + SMALLCHAR_HEIGHT/2, string, color );
}
else {
CG_DrawSmallStringColor( iconx, y, string, color );
}
}
}
// draw the face
VectorClear( headAngles );
headAngles[YAW] = 180;
if( largeFormat ) {
CG_DrawHead( headx, y - ( ICON_SIZE - BIGCHAR_HEIGHT ) / 2, ICON_SIZE, ICON_SIZE,
score->client, headAngles );
}
else {
CG_DrawHead( headx, y, 16, 16, score->client, headAngles );
}
#ifdef MISSIONPACK
// draw the team task
if ( ci->teamTask != TEAMTASK_NONE ) {
if (ci->isDead) {
CG_DrawPic( headx + 48, y, 16, 16, cgs.media.deathShader );
}
else if ( ci->teamTask == TEAMTASK_OFFENSE ) {
CG_DrawPic( headx + 48, y, 16, 16, cgs.media.assaultShader );
}
else if ( ci->teamTask == TEAMTASK_DEFENSE ) {
CG_DrawPic( headx + 48, y, 16, 16, cgs.media.defendShader );
}
}
#endif
// draw the score line
if ( score->ping == -1 ) {
Com_sprintf(string, sizeof(string),
" connecting %s", ci->name);
} else if ( ci->team == TEAM_SPECTATOR ) {
Com_sprintf(string, sizeof(string),
" SPECT %3i %4i %s", score->ping, score->time, ci->name);
} else {
/*if(cgs.gametype == GT_LMS)
Com_sprintf(string, sizeof(string),
"%5i %4i %4i %s *%i*", score->score, score->ping, score->time, ci->name, ci->isDead);
else*/
/*if(ci->isDead)
Com_sprintf(string, sizeof(string),
"%5i %4i %4i %s *DEAD*", score->score, score->ping, score->time, ci->name);
else*/
Com_sprintf(string, sizeof(string),
"%5i %4i %4i %s", score->score, score->ping, score->time, ci->name);
}
// highlight your position
if ( score->client == cg.snap->ps.clientNum ) {
float hcolor[4];
int rank;
localClient = qtrue;
if ( ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR ) ||
( ( cgs.gametype >= GT_TEAM ) &&
( cgs.ffa_gt != 1 ) ) ) {
// Sago: I think this means that it doesn't matter if two players are tied in team game - only team score counts
rank = -1;
} else {
rank = cg.snap->ps.persistant[PERS_RANK] & ~RANK_TIED_FLAG;
}
if ( rank == 0 ) {
hcolor[0] = 0;
hcolor[1] = 0;
hcolor[2] = 0.7f;
} else if ( rank == 1 ) {
hcolor[0] = 0.7f;
hcolor[1] = 0;
hcolor[2] = 0;
} else if ( rank == 2 ) {
hcolor[0] = 0.7f;
hcolor[1] = 0.7f;
hcolor[2] = 0;
} else {
hcolor[0] = 0.7f;
hcolor[1] = 0.7f;
hcolor[2] = 0.7f;
}
hcolor[3] = fade * 0.7;
CG_FillRect( SB_SCORELINE_X + BIGCHAR_WIDTH + (SB_RATING_WIDTH / 2), y,
640 - SB_SCORELINE_X - BIGCHAR_WIDTH, BIGCHAR_HEIGHT+1, hcolor );
}
CG_DrawBigString( SB_SCORELINE_X + (SB_RATING_WIDTH / 2), y, string, fade );
// add the "ready" marker for intermission exiting
if ( cg.snap->ps.stats[ STAT_CLIENTS_READY ] & ( 1 << score->client ) ) {
CG_DrawBigStringColor( iconx, y, "READY", color );
} else
if(cgs.gametype == GT_LMS) {
CG_DrawBigStringColor( iconx-50, y, va("*%i*",ci->isDead), color );
} else
if(ci->isDead) {
CG_DrawBigStringColor( iconx-60, y, "DEAD", color );
}
}
/*
=================
CG_TeamScoreboard
=================
*/
static int CG_TeamScoreboard( int y, team_t team, float fade, int maxClients, int lineHeight ) {
int i;
score_t *score;
float color[4];
int count;
clientInfo_t *ci;
color[0] = color[1] = color[2] = 1.0;
color[3] = fade;
count = 0;
for ( i = 0 ; i < cg.numScores && count < maxClients ; i++ ) {
score = &cg.scores[i];
ci = &cgs.clientinfo[ score->client ];
if ( team != ci->team ) {
continue;
}
CG_DrawClientScore( y + lineHeight * count, score, color, fade, lineHeight == SB_NORMAL_HEIGHT );
count++;
}
return count;
}
/*
=================
CG_DrawScoreboard
Draw the normal in-game scoreboard
=================
*/
qboolean CG_DrawOldScoreboard( void ) {
int x, y, w, i, n1, n2;
float fade;
float *fadeColor;
char *s;
int maxClients;
int lineHeight;
int topBorderSize, bottomBorderSize;
// don't draw amuthing if the menu or console is up
if ( cg_paused.integer ) {
cg.deferredPlayerLoading = 0;
return qfalse;
}
if ( cgs.gametype == GT_SINGLE_PLAYER && cg.predictedPlayerState.pm_type == PM_INTERMISSION ) {
cg.deferredPlayerLoading = 0;
return qfalse;
}
// don't draw scoreboard during death while warmup up
if ( cg.warmup && !cg.showScores ) {
return qfalse;
}
if ( cg.showScores || cg.predictedPlayerState.pm_type == PM_DEAD ||
cg.predictedPlayerState.pm_type == PM_INTERMISSION ) {
fade = 1.0;
fadeColor = colorWhite;
} else {
fadeColor = CG_FadeColor( cg.scoreFadeTime, FADE_TIME );
if ( !fadeColor ) {
// next time scoreboard comes up, don't print killer
cg.deferredPlayerLoading = 0;
cg.killerName[0] = 0;
return qfalse;
}
fade = *fadeColor;
}
// fragged by ... line
if ( cg.killerName[0] ) {
s = va("Fragged by %s", cg.killerName );
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
x = ( SCREEN_WIDTH - w ) / 2;
y = 40;
CG_DrawBigString( x, y, s, fade );
}
// current rank
if ( cgs.gametype < GT_TEAM || cgs.ffa_gt == 1) {
if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR ) {
s = va("%s place with %i",
CG_PlaceString( cg.snap->ps.persistant[PERS_RANK] + 1 ),
cg.snap->ps.persistant[PERS_SCORE] );
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
x = ( SCREEN_WIDTH - w ) / 2;
y = 60;
CG_DrawBigString( x, y, s, fade );
}
} else {
if ( cg.teamScores[0] == cg.teamScores[1] ) {
s = va("Teams are tied at %i", cg.teamScores[0] );
} else if ( cg.teamScores[0] >= cg.teamScores[1] ) {
s = va("Red leads %i to %i",cg.teamScores[0], cg.teamScores[1] );
} else {
s = va("Blue leads %i to %i",cg.teamScores[1], cg.teamScores[0] );
}
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
x = ( SCREEN_WIDTH - w ) / 2;
y = 60;
CG_DrawBigString( x, y, s, fade );
}
// scoreboard
y = SB_HEADER;
CG_DrawPic( SB_SCORE_X + (SB_RATING_WIDTH / 2), y, 64, 32, cgs.media.scoreboardScore );
CG_DrawPic( SB_PING_X - (SB_RATING_WIDTH / 2), y, 64, 32, cgs.media.scoreboardPing );
CG_DrawPic( SB_TIME_X - (SB_RATING_WIDTH / 2), y, 64, 32, cgs.media.scoreboardTime );
CG_DrawPic( SB_NAME_X - (SB_RATING_WIDTH / 2), y, 64, 32, cgs.media.scoreboardName );
y = SB_TOP;
// If there are more than SB_MAXCLIENTS_NORMAL, use the interleaved scores
if ( cg.numScores > SB_MAXCLIENTS_NORMAL ) {
maxClients = SB_MAXCLIENTS_INTER;
lineHeight = SB_INTER_HEIGHT;
topBorderSize = 8;
bottomBorderSize = 16;
} else {
maxClients = SB_MAXCLIENTS_NORMAL;
lineHeight = SB_NORMAL_HEIGHT;
topBorderSize = 16;
bottomBorderSize = 16;
}
localClient = qfalse;
if ( cgs.gametype >= GT_TEAM && cgs.ffa_gt!=1) {
//
// teamplay scoreboard
//
y += lineHeight/2;
if ( cg.teamScores[0] >= cg.teamScores[1] ) {
n1 = CG_TeamScoreboard( y, TEAM_RED, fade, maxClients, lineHeight );
CG_DrawTeamBackground( 0, y - topBorderSize, 640, n1 * lineHeight + bottomBorderSize, 0.33f, TEAM_RED );
y += (n1 * lineHeight) + BIGCHAR_HEIGHT;
maxClients -= n1;
n2 = CG_TeamScoreboard( y, TEAM_BLUE, fade, maxClients, lineHeight );
CG_DrawTeamBackground( 0, y - topBorderSize, 640, n2 * lineHeight + bottomBorderSize, 0.33f, TEAM_BLUE );
y += (n2 * lineHeight) + BIGCHAR_HEIGHT;
maxClients -= n2;
} else {
n1 = CG_TeamScoreboard( y, TEAM_BLUE, fade, maxClients, lineHeight );
CG_DrawTeamBackground( 0, y - topBorderSize, 640, n1 * lineHeight + bottomBorderSize, 0.33f, TEAM_BLUE );
y += (n1 * lineHeight) + BIGCHAR_HEIGHT;
maxClients -= n1;
n2 = CG_TeamScoreboard( y, TEAM_RED, fade, maxClients, lineHeight );
CG_DrawTeamBackground( 0, y - topBorderSize, 640, n2 * lineHeight + bottomBorderSize, 0.33f, TEAM_RED );
y += (n2 * lineHeight) + BIGCHAR_HEIGHT;
maxClients -= n2;
}
n1 = CG_TeamScoreboard( y, TEAM_SPECTATOR, fade, maxClients, lineHeight );
y += (n1 * lineHeight) + BIGCHAR_HEIGHT;
} else {
//
// free for all scoreboard
//
n1 = CG_TeamScoreboard( y, TEAM_FREE, fade, maxClients, lineHeight );
y += (n1 * lineHeight) + BIGCHAR_HEIGHT;
n2 = CG_TeamScoreboard( y, TEAM_SPECTATOR, fade, maxClients - n1, lineHeight );
y += (n2 * lineHeight) + BIGCHAR_HEIGHT;
}
if (!localClient) {
// draw local client at the bottom
for ( i = 0 ; i < cg.numScores ; i++ ) {
if ( cg.scores[i].client == cg.snap->ps.clientNum ) {
CG_DrawClientScore( y, &cg.scores[i], fadeColor, fade, lineHeight == SB_NORMAL_HEIGHT );
break;
}
}
}
// load any models that have been deferred
if ( ++cg.deferredPlayerLoading > 10 ) {
CG_LoadDeferredPlayers();
}
return qtrue;
}
//================================================================================
/*
================
CG_CenterGiantLine
================
*/
static void CG_CenterGiantLine( float y, const char *string ) {
float x;
vec4_t color;
color[0] = 1;
color[1] = 1;
color[2] = 1;
color[3] = 1;
x = 0.5 * ( 640 - GIANT_WIDTH * CG_DrawStrlen( string ) );
CG_DrawStringExt( x, y, string, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
}
/*
=================
CG_DrawTourneyScoreboard
Draw the oversize scoreboard for tournements
=================
*/
void CG_DrawOldTourneyScoreboard( void ) {
const char *s;
vec4_t color;
int min, tens, ones;
clientInfo_t *ci;
int y;
int i;
// request more scores regularly
if ( cg.scoresRequestTime + 2000 < cg.time ) {
cg.scoresRequestTime = cg.time;
trap_SendClientCommand( "score" );
}
// draw the dialog background
color[0] = color[1] = color[2] = 0;
color[3] = 1;
CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, color );
color[0] = 1;
color[1] = 1;
color[2] = 1;
color[3] = 1;
// print the mesage of the day
s = CG_ConfigString( CS_MOTD );
if ( !s[0] ) {
s = "Scoreboard";
}
// print optional title
CG_CenterGiantLine( 8, s );
// print server time
ones = cg.time / 1000;
min = ones / 60;
ones %= 60;
tens = ones / 10;
ones %= 10;
s = va("%i:%i%i", min, tens, ones );
CG_CenterGiantLine( 64, s );
// print the two scores
y = 160;
if ( cgs.gametype >= GT_TEAM && cgs.ffa_gt!=1) {
//
// teamplay scoreboard
//
CG_DrawStringExt( 8, y, "Red Team", color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
s = va("%i", cg.teamScores[0] );
CG_DrawStringExt( 632 - GIANT_WIDTH * strlen(s), y, s, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
y += 64;
CG_DrawStringExt( 8, y, "Blue Team", color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
s = va("%i", cg.teamScores[1] );
CG_DrawStringExt( 632 - GIANT_WIDTH * strlen(s), y, s, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
} else {
//
// free for all scoreboard
//
for ( i = 0 ; i < MAX_CLIENTS ; i++ ) {
ci = &cgs.clientinfo[i];
if ( !ci->infoValid ) {
continue;
}
if ( ci->team != TEAM_FREE ) {
continue;
}
CG_DrawStringExt( 8, y, ci->name, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
s = va("%i", ci->score );
CG_DrawStringExt( 632 - GIANT_WIDTH * strlen(s), y, s, color, qtrue, qtrue, GIANT_WIDTH, GIANT_HEIGHT, 0 );
y += 64;
}
}
}

1402
code/cgame/cg_servercmds.c Normal file

File diff suppressed because it is too large Load Diff

405
code/cgame/cg_snapshot.c Normal file
View File

@@ -0,0 +1,405 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_snapshot.c -- things that happen on snapshot transition,
// not necessarily every single rendered frame
#include "cg_local.h"
/*
==================
CG_ResetEntity
==================
*/
static void CG_ResetEntity( centity_t *cent ) {
// if the previous snapshot this entity was updated in is at least
// an event window back in time then we can reset the previous event
if ( cent->snapShotTime < cg.time - EVENT_VALID_MSEC ) {
cent->previousEvent = 0;
}
cent->trailTime = cg.snap->serverTime;
VectorCopy (cent->currentState.origin, cent->lerpOrigin);
VectorCopy (cent->currentState.angles, cent->lerpAngles);
if ( cent->currentState.eType == ET_PLAYER ) {
CG_ResetPlayerEntity( cent );
}
}
/*
===============
CG_TransitionEntity
cent->nextState is moved to cent->currentState and events are fired
===============
*/
//unlagged - early transitioning
// used to be static, now needed to transition entities from within cg_ents.c
void CG_TransitionEntity( centity_t *cent ) {
cent->currentState = cent->nextState;
cent->currentValid = qtrue;
// reset if the entity wasn't in the last frame or was teleported
if ( !cent->interpolate ) {
CG_ResetEntity( cent );
}
// clear the next state. if will be set by the next CG_SetNextSnap
cent->interpolate = qfalse;
// check for events
CG_CheckEvents( cent );
}
/*
==================
CG_SetInitialSnapshot
This will only happen on the very first snapshot, or
on tourney restarts. All other times will use
CG_TransitionSnapshot instead.
FIXME: Also called by map_restart?
==================
*/
void CG_SetInitialSnapshot( snapshot_t *snap ) {
int i;
centity_t *cent;
entityState_t *state;
cg.snap = snap;
BG_PlayerStateToEntityState( &snap->ps, &cg_entities[ snap->ps.clientNum ].currentState, qfalse );
// sort out solid entities
CG_BuildSolidList();
CG_ExecuteNewServerCommands( snap->serverCommandSequence );
// set our local weapon selection pointer to
// what the server has indicated the current weapon is
CG_Respawn();
for ( i = 0 ; i < cg.snap->numEntities ; i++ ) {
state = &cg.snap->entities[ i ];
cent = &cg_entities[ state->number ];
memcpy(&cent->currentState, state, sizeof(entityState_t));
//cent->currentState = *state;
cent->interpolate = qfalse;
cent->currentValid = qtrue;
CG_ResetEntity( cent );
// check for events
CG_CheckEvents( cent );
}
}
/*
===================
CG_TransitionSnapshot
The transition point from snap to nextSnap has passed
===================
*/
static void CG_TransitionSnapshot( void ) {
centity_t *cent;
snapshot_t *oldFrame;
int i;
if ( !cg.snap ) {
CG_Error( "CG_TransitionSnapshot: NULL cg.snap" );
}
if ( !cg.nextSnap ) {
CG_Error( "CG_TransitionSnapshot: NULL cg.nextSnap" );
}
// execute any server string commands before transitioning entities
CG_ExecuteNewServerCommands( cg.nextSnap->serverCommandSequence );
// if we had a map_restart, set everthing with initial
if ( !cg.snap ) {
}
// clear the currentValid flag for all entities in the existing snapshot
for ( i = 0 ; i < cg.snap->numEntities ; i++ ) {
cent = &cg_entities[ cg.snap->entities[ i ].number ];
cent->currentValid = qfalse;
}
// move nextSnap to snap and do the transitions
oldFrame = cg.snap;
cg.snap = cg.nextSnap;
BG_PlayerStateToEntityState( &cg.snap->ps, &cg_entities[ cg.snap->ps.clientNum ].currentState, qfalse );
cg_entities[ cg.snap->ps.clientNum ].interpolate = qfalse;
for ( i = 0 ; i < cg.snap->numEntities ; i++ ) {
cent = &cg_entities[ cg.snap->entities[ i ].number ];
CG_TransitionEntity( cent );
// remember time of snapshot this entity was last updated in
cent->snapShotTime = cg.snap->serverTime;
}
cg.nextSnap = NULL;
// check for playerstate transition events
if ( oldFrame ) {
playerState_t *ops, *ps;
ops = &oldFrame->ps;
ps = &cg.snap->ps;
// teleporting checks are irrespective of prediction
if ( ( ps->eFlags ^ ops->eFlags ) & EF_TELEPORT_BIT ) {
cg.thisFrameTeleport = qtrue; // will be cleared by prediction code
}
// if we are not doing client side movement prediction for any
// reason, then the client events and view changes will be issued now
if ( cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW)
|| cg_nopredict.integer || cg_synchronousClients.integer ) {
CG_TransitionPlayerState( ps, ops );
}
}
}
/*
===================
CG_SetNextSnap
A new snapshot has just been read in from the client system.
===================
*/
static void CG_SetNextSnap( snapshot_t *snap ) {
int num;
entityState_t *es;
centity_t *cent;
cg.nextSnap = snap;
BG_PlayerStateToEntityState( &snap->ps, &cg_entities[ snap->ps.clientNum ].nextState, qfalse );
cg_entities[ cg.snap->ps.clientNum ].interpolate = qtrue;
// check for extrapolation errors
for ( num = 0 ; num < snap->numEntities ; num++ ) {
es = &snap->entities[num];
cent = &cg_entities[ es->number ];
memcpy(&cent->nextState, es, sizeof(entityState_t));
//cent->nextState = *es;
// if this frame is a teleport, or the entity wasn't in the
// previous frame, don't interpolate
if ( !cent->currentValid || ( ( cent->currentState.eFlags ^ es->eFlags ) & EF_TELEPORT_BIT ) ) {
cent->interpolate = qfalse;
} else {
cent->interpolate = qtrue;
}
}
// if the next frame is a teleport for the playerstate, we
// can't interpolate during demos
if ( cg.snap && ( ( snap->ps.eFlags ^ cg.snap->ps.eFlags ) & EF_TELEPORT_BIT ) ) {
cg.nextFrameTeleport = qtrue;
} else {
cg.nextFrameTeleport = qfalse;
}
// if changing follow mode, don't interpolate
if ( cg.nextSnap->ps.clientNum != cg.snap->ps.clientNum ) {
cg.nextFrameTeleport = qtrue;
}
// if changing server restarts, don't interpolate
if ( ( cg.nextSnap->snapFlags ^ cg.snap->snapFlags ) & SNAPFLAG_SERVERCOUNT ) {
cg.nextFrameTeleport = qtrue;
}
// sort out solid entities
CG_BuildSolidList();
}
/*
========================
CG_ReadNextSnapshot
This is the only place new snapshots are requested
This may increment cgs.processedSnapshotNum multiple
times if the client system fails to return a
valid snapshot.
========================
*/
static snapshot_t *CG_ReadNextSnapshot( void ) {
qboolean r;
snapshot_t *dest;
if ( cg.latestSnapshotNum > cgs.processedSnapshotNum + 1000 ) {
CG_Printf( "WARNING: CG_ReadNextSnapshot: way out of range, %i > %i",
cg.latestSnapshotNum, cgs.processedSnapshotNum );
}
while ( cgs.processedSnapshotNum < cg.latestSnapshotNum ) {
// decide which of the two slots to load it into
if ( cg.snap == &cg.activeSnapshots[0] ) {
dest = &cg.activeSnapshots[1];
} else {
dest = &cg.activeSnapshots[0];
}
// try to read the snapshot from the client system
cgs.processedSnapshotNum++;
r = trap_GetSnapshot( cgs.processedSnapshotNum, dest );
// FIXME: why would trap_GetSnapshot return a snapshot with the same server time
if ( cg.snap && r && dest->serverTime == cg.snap->serverTime ) {
//continue;
}
// if it succeeded, return
if ( r ) {
CG_AddLagometerSnapshotInfo( dest );
return dest;
}
// a GetSnapshot will return failure if the snapshot
// never arrived, or is so old that its entities
// have been shoved off the end of the circular
// buffer in the client system.
// record as a dropped packet
CG_AddLagometerSnapshotInfo( NULL );
// If there are additional snapshots, continue trying to
// read them.
}
// nothing left to read
return NULL;
}
/*
============
CG_ProcessSnapshots
We are trying to set up a renderable view, so determine
what the simulated time is, and try to get snapshots
both before and after that time if available.
If we don't have a valid cg.snap after exiting this function,
then a 3D game view cannot be rendered. This should only happen
right after the initial connection. After cg.snap has been valid
once, it will never turn invalid.
Even if cg.snap is valid, cg.nextSnap may not be, if the snapshot
hasn't arrived yet (it becomes an extrapolating situation instead
of an interpolating one)
============
*/
void CG_ProcessSnapshots( void ) {
snapshot_t *snap;
int n;
// see what the latest snapshot the client system has is
trap_GetCurrentSnapshotNumber( &n, &cg.latestSnapshotTime );
if ( n != cg.latestSnapshotNum ) {
if ( n < cg.latestSnapshotNum ) {
// this should never happen
CG_Error( "CG_ProcessSnapshots: n < cg.latestSnapshotNum" );
}
cg.latestSnapshotNum = n;
}
// If we have yet to receive a snapshot, check for it.
// Once we have gotten the first snapshot, cg.snap will
// always have valid data for the rest of the game
while ( !cg.snap ) {
snap = CG_ReadNextSnapshot();
if ( !snap ) {
// we can't continue until we get a snapshot
return;
}
// set our weapon selection to what
// the playerstate is currently using
if ( !( snap->snapFlags & SNAPFLAG_NOT_ACTIVE ) ) {
CG_SetInitialSnapshot( snap );
}
}
// loop until we either have a valid nextSnap with a serverTime
// greater than cg.time to interpolate towards, or we run
// out of available snapshots
do {
// if we don't have a nextframe, try and read a new one in
if ( !cg.nextSnap ) {
snap = CG_ReadNextSnapshot();
// if we still don't have a nextframe, we will just have to
// extrapolate
if ( !snap ) {
break;
}
CG_SetNextSnap( snap );
// if time went backwards, we have a level restart
if ( cg.nextSnap->serverTime < cg.snap->serverTime ) {
CG_Error( "CG_ProcessSnapshots: Server time went backwards" );
}
}
// if our time is < nextFrame's, we have a nice interpolating state
if ( cg.time >= cg.snap->serverTime && cg.time < cg.nextSnap->serverTime ) {
break;
}
// we have passed the transition from nextFrame to frame
CG_TransitionSnapshot();
} while ( 1 );
// assert our valid conditions upon exiting
if ( cg.snap == NULL ) {
CG_Error( "CG_ProcessSnapshots: cg.snap == NULL" );
}
if ( cg.time < cg.snap->serverTime ) {
// this can happen right after a vid_restart
cg.time = cg.snap->serverTime;
}
if ( cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time ) {
CG_Error( "CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time" );
}
}

106
code/cgame/cg_syscalls.asm Normal file
View File

@@ -0,0 +1,106 @@
code
equ trap_Print -1
equ trap_Error -2
equ trap_Milliseconds -3
equ trap_Cvar_Register -4
equ trap_Cvar_Update -5
equ trap_Cvar_Set -6
equ trap_Cvar_VariableStringBuffer -7
equ trap_Argc -8
equ trap_Argv -9
equ trap_Args -10
equ trap_FS_FOpenFile -11
equ trap_FS_Read -12
equ trap_FS_Write -13
equ trap_FS_FCloseFile -14
equ trap_SendConsoleCommand -15
equ trap_AddCommand -16
equ trap_SendClientCommand -17
equ trap_UpdateScreen -18
equ trap_CM_LoadMap -19
equ trap_CM_NumInlineModels -20
equ trap_CM_InlineModel -21
equ trap_CM_LoadModel -22
equ trap_CM_TempBoxModel -23
equ trap_CM_PointContents -24
equ trap_CM_TransformedPointContents -25
equ trap_CM_BoxTrace -26
equ trap_CM_TransformedBoxTrace -27
equ trap_CM_MarkFragments -28
equ trap_S_StartSound -29
equ trap_S_StartLocalSound -30
equ trap_S_ClearLoopingSounds -31
equ trap_S_AddLoopingSound -32
equ trap_S_UpdateEntityPosition -33
equ trap_S_Respatialize -34
equ trap_S_RegisterSound -35
equ trap_S_StartBackgroundTrack -36
equ trap_R_LoadWorldMap -37
equ trap_R_RegisterModel -38
equ trap_R_RegisterSkin -39
equ trap_R_RegisterShader -40
equ trap_R_ClearScene -41
equ trap_R_AddRefEntityToScene -42
equ trap_R_AddPolyToScene -43
equ trap_R_AddLightToScene -44
equ trap_R_RenderScene -45
equ trap_R_SetColor -46
equ trap_R_DrawStretchPic -47
equ trap_R_ModelBounds -48
equ trap_R_LerpTag -49
equ trap_GetGlconfig -50
equ trap_GetGameState -51
equ trap_GetCurrentSnapshotNumber -52
equ trap_GetSnapshot -53
equ trap_GetServerCommand -54
equ trap_GetCurrentCmdNumber -55
equ trap_GetUserCmd -56
equ trap_SetUserCmdValue -57
equ trap_R_RegisterShaderNoMip -58
equ trap_MemoryRemaining -59
equ trap_R_RegisterFont -60
equ trap_Key_IsDown -61
equ trap_Key_GetCatcher -62
equ trap_Key_SetCatcher -63
equ trap_Key_GetKey -64
equ trap_PC_AddGlobalDefine -65
equ trap_PC_LoadSource -66
equ trap_PC_FreeSource -67
equ trap_PC_ReadToken -68
equ trap_PC_SourceFileAndLine -69
equ trap_S_StopBackgroundTrack -70
equ trap_RealTime -71
equ trap_SnapVector -72
equ trap_RemoveCommand -73
equ trap_R_LightForPoint -74
equ trap_CIN_PlayCinematic -75
equ trap_CIN_StopCinematic -76
equ trap_CIN_RunCinematic -77
equ trap_CIN_DrawCinematic -78
equ trap_CIN_SetExtents -79
equ trap_R_RemapShader -80
equ trap_S_AddRealLoopingSound -81
equ trap_S_StopLoopingSound -82
equ trap_CM_TempCapsuleModel -83
equ trap_CM_CapsuleTrace -84
equ trap_CM_TransformedCapsuleTrace -85
equ trap_R_AddAdditiveLightToScene -86
equ trap_GetEntityToken -87
equ trap_R_AddPolysToScene -88
equ trap_R_inPVS -89
equ trap_FS_Seek -90
equ memset -101
equ memcpy -102
equ strncpy -103
equ sin -104
equ cos -105
equ atan2 -106
equ sqrt -107
equ floor -108
equ ceil -109
equ testPrintInt -110
equ testPrintFloat -111
equ acos -112

446
code/cgame/cg_syscalls.c Normal file
View File

@@ -0,0 +1,446 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_syscalls.c -- this file is only included when building a dll
// cg_syscalls.asm is included instead when building a qvm
#ifdef Q3_VM
#error "Do not use in VM build"
#endif
#include "cg_local.h"
static intptr_t (QDECL *syscall)( intptr_t arg, ... ) = (intptr_t (QDECL *)( intptr_t, ...))-1;
void dllEntry( intptr_t (QDECL *syscallptr)( intptr_t arg,... ) ) {
syscall = syscallptr;
}
int PASSFLOAT( float x ) {
float floatTemp;
floatTemp = x;
return *(int *)&floatTemp;
}
void trap_Print( const char *fmt ) {
syscall( CG_PRINT, fmt );
}
void trap_Error( const char *fmt ) {
syscall( CG_ERROR, fmt );
exit(CG_ERROR); //Will never occour but makes compiler happy
}
int trap_Milliseconds( void ) {
return syscall( CG_MILLISECONDS );
}
void trap_Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags ) {
syscall( CG_CVAR_REGISTER, vmCvar, varName, defaultValue, flags );
}
void trap_Cvar_Update( vmCvar_t *vmCvar ) {
syscall( CG_CVAR_UPDATE, vmCvar );
}
void trap_Cvar_Set( const char *var_name, const char *value ) {
syscall( CG_CVAR_SET, var_name, value );
}
void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) {
syscall( CG_CVAR_VARIABLESTRINGBUFFER, var_name, buffer, bufsize );
}
int trap_Argc( void ) {
return syscall( CG_ARGC );
}
void trap_Argv( int n, char *buffer, int bufferLength ) {
syscall( CG_ARGV, n, buffer, bufferLength );
}
void trap_Args( char *buffer, int bufferLength ) {
syscall( CG_ARGS, buffer, bufferLength );
}
int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
return syscall( CG_FS_FOPENFILE, qpath, f, mode );
}
void trap_FS_Read( void *buffer, int len, fileHandle_t f ) {
syscall( CG_FS_READ, buffer, len, f );
}
void trap_FS_Write( const void *buffer, int len, fileHandle_t f ) {
syscall( CG_FS_WRITE, buffer, len, f );
}
void trap_FS_FCloseFile( fileHandle_t f ) {
syscall( CG_FS_FCLOSEFILE, f );
}
int trap_FS_Seek( fileHandle_t f, long offset, int origin ) {
return syscall( CG_FS_SEEK, f, offset, origin );
}
void trap_SendConsoleCommand( const char *text ) {
syscall( CG_SENDCONSOLECOMMAND, text );
}
void trap_AddCommand( const char *cmdName ) {
syscall( CG_ADDCOMMAND, cmdName );
}
void trap_RemoveCommand( const char *cmdName ) {
syscall( CG_REMOVECOMMAND, cmdName );
}
void trap_SendClientCommand( const char *s ) {
syscall( CG_SENDCLIENTCOMMAND, s );
}
void trap_UpdateScreen( void ) {
syscall( CG_UPDATESCREEN );
}
void trap_CM_LoadMap( const char *mapname ) {
syscall( CG_CM_LOADMAP, mapname );
}
int trap_CM_NumInlineModels( void ) {
return syscall( CG_CM_NUMINLINEMODELS );
}
clipHandle_t trap_CM_InlineModel( int index ) {
return syscall( CG_CM_INLINEMODEL, index );
}
clipHandle_t trap_CM_TempBoxModel( const vec3_t mins, const vec3_t maxs ) {
return syscall( CG_CM_TEMPBOXMODEL, mins, maxs );
}
clipHandle_t trap_CM_TempCapsuleModel( const vec3_t mins, const vec3_t maxs ) {
return syscall( CG_CM_TEMPCAPSULEMODEL, mins, maxs );
}
int trap_CM_PointContents( const vec3_t p, clipHandle_t model ) {
return syscall( CG_CM_POINTCONTENTS, p, model );
}
int trap_CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles ) {
return syscall( CG_CM_TRANSFORMEDPOINTCONTENTS, p, model, origin, angles );
}
void trap_CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
const vec3_t mins, const vec3_t maxs,
clipHandle_t model, int brushmask ) {
syscall( CG_CM_BOXTRACE, results, start, end, mins, maxs, model, brushmask );
}
void trap_CM_CapsuleTrace( trace_t *results, const vec3_t start, const vec3_t end,
const vec3_t mins, const vec3_t maxs,
clipHandle_t model, int brushmask ) {
syscall( CG_CM_CAPSULETRACE, results, start, end, mins, maxs, model, brushmask );
}
void trap_CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end,
const vec3_t mins, const vec3_t maxs,
clipHandle_t model, int brushmask,
const vec3_t origin, const vec3_t angles ) {
syscall( CG_CM_TRANSFORMEDBOXTRACE, results, start, end, mins, maxs, model, brushmask, origin, angles );
}
void trap_CM_TransformedCapsuleTrace( trace_t *results, const vec3_t start, const vec3_t end,
const vec3_t mins, const vec3_t maxs,
clipHandle_t model, int brushmask,
const vec3_t origin, const vec3_t angles ) {
syscall( CG_CM_TRANSFORMEDCAPSULETRACE, results, start, end, mins, maxs, model, brushmask, origin, angles );
}
int trap_CM_MarkFragments( int numPoints, const vec3_t *points,
const vec3_t projection,
int maxPoints, vec3_t pointBuffer,
int maxFragments, markFragment_t *fragmentBuffer ) {
return syscall( CG_CM_MARKFRAGMENTS, numPoints, points, projection, maxPoints, pointBuffer, maxFragments, fragmentBuffer );
}
void trap_S_StartSound( vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ) {
syscall( CG_S_STARTSOUND, origin, entityNum, entchannel, sfx );
}
void trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum ) {
syscall( CG_S_STARTLOCALSOUND, sfx, channelNum );
}
void trap_S_ClearLoopingSounds( qboolean killall ) {
syscall( CG_S_CLEARLOOPINGSOUNDS, killall );
}
void trap_S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx ) {
syscall( CG_S_ADDLOOPINGSOUND, entityNum, origin, velocity, sfx );
}
void trap_S_AddRealLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx ) {
syscall( CG_S_ADDREALLOOPINGSOUND, entityNum, origin, velocity, sfx );
}
void trap_S_StopLoopingSound( int entityNum ) {
syscall( CG_S_STOPLOOPINGSOUND, entityNum );
}
void trap_S_UpdateEntityPosition( int entityNum, const vec3_t origin ) {
syscall( CG_S_UPDATEENTITYPOSITION, entityNum, origin );
}
void trap_S_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater ) {
syscall( CG_S_RESPATIALIZE, entityNum, origin, axis, inwater );
}
sfxHandle_t trap_S_RegisterSound( const char *sample, qboolean compressed ) {
return syscall( CG_S_REGISTERSOUND, sample, compressed );
}
void trap_S_StartBackgroundTrack( const char *intro, const char *loop ) {
syscall( CG_S_STARTBACKGROUNDTRACK, intro, loop );
}
void trap_R_LoadWorldMap( const char *mapname ) {
syscall( CG_R_LOADWORLDMAP, mapname );
}
qhandle_t trap_R_RegisterModel( const char *name ) {
return syscall( CG_R_REGISTERMODEL, name );
}
qhandle_t trap_R_RegisterSkin( const char *name ) {
return syscall( CG_R_REGISTERSKIN, name );
}
qhandle_t trap_R_RegisterShader( const char *name ) {
return syscall( CG_R_REGISTERSHADER, name );
}
qhandle_t trap_R_RegisterShaderNoMip( const char *name ) {
return syscall( CG_R_REGISTERSHADERNOMIP, name );
}
void trap_R_RegisterFont(const char *fontName, int pointSize, fontInfo_t *font) {
syscall(CG_R_REGISTERFONT, fontName, pointSize, font );
}
void trap_R_ClearScene( void ) {
syscall( CG_R_CLEARSCENE );
}
void trap_R_AddRefEntityToScene( const refEntity_t *re ) {
syscall( CG_R_ADDREFENTITYTOSCENE, re );
}
void trap_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts ) {
syscall( CG_R_ADDPOLYTOSCENE, hShader, numVerts, verts );
}
void trap_R_AddPolysToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts, int num ) {
syscall( CG_R_ADDPOLYSTOSCENE, hShader, numVerts, verts, num );
}
int trap_R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ) {
return syscall( CG_R_LIGHTFORPOINT, point, ambientLight, directedLight, lightDir );
}
void trap_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) {
syscall( CG_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) );
}
void trap_R_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ) {
syscall( CG_R_ADDADDITIVELIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) );
}
void trap_R_RenderScene( const refdef_t *fd ) {
syscall( CG_R_RENDERSCENE, fd );
}
void trap_R_SetColor( const float *rgba ) {
syscall( CG_R_SETCOLOR, rgba );
}
void trap_R_DrawStretchPic( float x, float y, float w, float h,
float s1, float t1, float s2, float t2, qhandle_t hShader ) {
syscall( CG_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader );
}
void trap_R_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs ) {
syscall( CG_R_MODELBOUNDS, model, mins, maxs );
}
int trap_R_LerpTag( orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame,
float frac, const char *tagName ) {
return syscall( CG_R_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName );
}
void trap_R_RemapShader( const char *oldShader, const char *newShader, const char *timeOffset ) {
syscall( CG_R_REMAP_SHADER, oldShader, newShader, timeOffset );
}
void trap_GetGlconfig( glconfig_t *glconfig ) {
syscall( CG_GETGLCONFIG, glconfig );
}
void trap_GetGameState( gameState_t *gamestate ) {
syscall( CG_GETGAMESTATE, gamestate );
}
void trap_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) {
syscall( CG_GETCURRENTSNAPSHOTNUMBER, snapshotNumber, serverTime );
}
qboolean trap_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) {
return syscall( CG_GETSNAPSHOT, snapshotNumber, snapshot );
}
qboolean trap_GetServerCommand( int serverCommandNumber ) {
return syscall( CG_GETSERVERCOMMAND, serverCommandNumber );
}
int trap_GetCurrentCmdNumber( void ) {
return syscall( CG_GETCURRENTCMDNUMBER );
}
qboolean trap_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) {
return syscall( CG_GETUSERCMD, cmdNumber, ucmd );
}
void trap_SetUserCmdValue( int stateValue, float sensitivityScale ) {
syscall( CG_SETUSERCMDVALUE, stateValue, PASSFLOAT(sensitivityScale) );
}
void testPrintInt( char *string, int i ) {
syscall( CG_TESTPRINTINT, string, i );
}
void testPrintFloat( char *string, float f ) {
syscall( CG_TESTPRINTFLOAT, string, PASSFLOAT(f) );
}
int trap_MemoryRemaining( void ) {
return syscall( CG_MEMORY_REMAINING );
}
qboolean trap_Key_IsDown( int keynum ) {
return syscall( CG_KEY_ISDOWN, keynum );
}
int trap_Key_GetCatcher( void ) {
return syscall( CG_KEY_GETCATCHER );
}
void trap_Key_SetCatcher( int catcher ) {
syscall( CG_KEY_SETCATCHER, catcher );
}
int trap_Key_GetKey( const char *binding ) {
return syscall( CG_KEY_GETKEY, binding );
}
int trap_PC_AddGlobalDefine( char *define ) {
return syscall( CG_PC_ADD_GLOBAL_DEFINE, define );
}
int trap_PC_LoadSource( const char *filename ) {
return syscall( CG_PC_LOAD_SOURCE, filename );
}
int trap_PC_FreeSource( int handle ) {
return syscall( CG_PC_FREE_SOURCE, handle );
}
int trap_PC_ReadToken( int handle, pc_token_t *pc_token ) {
return syscall( CG_PC_READ_TOKEN, handle, pc_token );
}
int trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) {
return syscall( CG_PC_SOURCE_FILE_AND_LINE, handle, filename, line );
}
void trap_S_StopBackgroundTrack( void ) {
syscall( CG_S_STOPBACKGROUNDTRACK );
}
int trap_RealTime(qtime_t *qtime) {
return syscall( CG_REAL_TIME, qtime );
}
void trap_SnapVector( float *v ) {
syscall( CG_SNAPVECTOR, v );
}
// this returns a handle. arg0 is the name in the format "idlogo.roq", set arg1 to NULL, alteredstates to qfalse (do not alter gamestate)
int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits) {
return syscall(CG_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits);
}
// stops playing the cinematic and ends it. should always return FMV_EOF
// cinematics must be stopped in reverse order of when they are started
e_status trap_CIN_StopCinematic(int handle) {
return syscall(CG_CIN_STOPCINEMATIC, handle);
}
// will run a frame of the cinematic but will not draw it. Will return FMV_EOF if the end of the cinematic has been reached.
e_status trap_CIN_RunCinematic (int handle) {
return syscall(CG_CIN_RUNCINEMATIC, handle);
}
// draws the current frame
void trap_CIN_DrawCinematic (int handle) {
syscall(CG_CIN_DRAWCINEMATIC, handle);
}
// allows you to resize the animation dynamically
void trap_CIN_SetExtents (int handle, int x, int y, int w, int h) {
syscall(CG_CIN_SETEXTENTS, handle, x, y, w, h);
}
/*
qboolean trap_loadCamera( const char *name ) {
return syscall( CG_LOADCAMERA, name );
}
void trap_startCamera(int time) {
syscall(CG_STARTCAMERA, time);
}
qboolean trap_getCameraInfo( int time, vec3_t *origin, vec3_t *angles) {
return syscall( CG_GETCAMERAINFO, time, origin, angles );
}
*/
qboolean trap_GetEntityToken( char *buffer, int bufferSize ) {
return syscall( CG_GET_ENTITY_TOKEN, buffer, bufferSize );
}
qboolean trap_R_inPVS( const vec3_t p1, const vec3_t p2 ) {
return syscall( CG_R_INPVS, p1, p2 );
}

477
code/cgame/cg_unlagged.c Normal file
View File

@@ -0,0 +1,477 @@
/*
===========================================================================
Copyright (C) 2006 Neil Toronto.
This file is part of the Unlagged source code.
Unlagged source code is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
Unlagged source code is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with Unlagged source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//#include "cg_local.h"
#include "cg_local.h"
// we'll need these prototypes
void CG_ShotgunPattern( vec3_t origin, vec3_t origin2, int seed, int otherEntNum );
void CG_Bullet( vec3_t end, int sourceEntityNum, vec3_t normal, qboolean flesh, int fleshEntityNum );
// and this as well
//Must be in sync with g_weapon.c
#define MACHINEGUN_SPREAD 200
#define CHAINGUN_SPREAD 600
/*
=======================
CG_PredictWeaponEffects
Draws predicted effects for the railgun, shotgun, and machinegun. The
lightning gun is done in CG_LightningBolt, since it was just a matter
of setting the right origin and angles.
=======================
*/
void CG_PredictWeaponEffects( centity_t *cent ) {
vec3_t muzzlePoint, forward, right, up;
entityState_t *ent = &cent->currentState;
// if the client isn't us, forget it
if ( cent->currentState.number != cg.predictedPlayerState.clientNum ) {
return;
}
// if it's not switched on server-side, forget it
if ( !cgs.delagHitscan ) {
return;
}
// get the muzzle point
VectorCopy( cg.predictedPlayerState.origin, muzzlePoint );
muzzlePoint[2] += cg.predictedPlayerState.viewheight;
// get forward, right, and up
AngleVectors( cg.predictedPlayerState.viewangles, forward, right, up );
VectorMA( muzzlePoint, 14, forward, muzzlePoint );
// was it a rail attack?
if ( ent->weapon == WP_RAILGUN ) {
// do we have it on for the rail gun?
if ( cg_delag.integer & 1 || cg_delag.integer & 16 ) {
trace_t trace;
vec3_t endPoint;
// trace forward
VectorMA( muzzlePoint, 8192, forward, endPoint );
// THIS IS FOR DEBUGGING!
// you definitely *will* want something like this to test the backward reconciliation
// to make sure it's working *exactly* right
/*if ( cg_debugDelag.integer ) {
* Sago: There are some problems with some unlagged code. People will just have to trust it
// trace forward
CG_Trace( &trace, muzzlePoint, vec3_origin, vec3_origin, endPoint, cent->currentState.number, CONTENTS_BODY|CONTENTS_SOLID );
// did we hit another player?
if ( trace.fraction < 1.0f && (trace.contents & CONTENTS_BODY) ) {
// if we have two snapshots (we're interpolating)
if ( cg.nextSnap ) {
centity_t *c = &cg_entities[trace.entityNum];
vec3_t origin1, origin2;
// figure the two origins used for interpolation
BG_EvaluateTrajectory( &c->currentState.pos, cg.snap->serverTime, origin1 );
BG_EvaluateTrajectory( &c->nextState.pos, cg.nextSnap->serverTime, origin2 );
// print some debugging stuff exactly like what the server does
// it starts with "Int:" to let you know the target was interpolated
CG_Printf("^3Int: time: %d, j: %d, k: %d, origin: %0.2f %0.2f %0.2f\n",
cg.oldTime, cg.snap->serverTime, cg.nextSnap->serverTime,
c->lerpOrigin[0], c->lerpOrigin[1], c->lerpOrigin[2]);
CG_Printf("^5frac: %0.4f, origin1: %0.2f %0.2f %0.2f, origin2: %0.2f %0.2f %0.2f\n",
cg.frameInterpolation, origin1[0], origin1[1], origin1[2], origin2[0], origin2[1], origin2[2]);
}
else {
// we haven't got a next snapshot
// the client clock has either drifted ahead (seems to happen once per server frame
// when you play locally) or the client is using timenudge
// in any case, CG_CalcEntityLerpPositions extrapolated rather than interpolated
centity_t *c = &cg_entities[trace.entityNum];
vec3_t origin1, origin2;
c->currentState.pos.trTime = TR_LINEAR_STOP;
c->currentState.pos.trTime = cg.snap->serverTime;
c->currentState.pos.trDuration = 1000 / sv_fps.integer;
BG_EvaluateTrajectory( &c->currentState.pos, cg.snap->serverTime, origin1 );
BG_EvaluateTrajectory( &c->currentState.pos, cg.snap->serverTime + 1000 / sv_fps.integer, origin2 );
// print some debugging stuff exactly like what the server does
// it starts with "Ext:" to let you know the target was extrapolated
CG_Printf("^3Ext: time: %d, j: %d, k: %d, origin: %0.2f %0.2f %0.2f\n",
cg.oldTime, cg.snap->serverTime, cg.snap->serverTime,
c->lerpOrigin[0], c->lerpOrigin[1], c->lerpOrigin[2]);
CG_Printf("^5frac: %0.4f, origin1: %0.2f %0.2f %0.2f, origin2: %0.2f %0.2f %0.2f\n",
cg.frameInterpolation, origin1[0], origin1[1], origin1[2], origin2[0], origin2[1], origin2[2]);
}
}
}*/
// find the rail's end point
CG_Trace( &trace, muzzlePoint, vec3_origin, vec3_origin, endPoint, cg.predictedPlayerState.clientNum, CONTENTS_SOLID );
// do the magic-number adjustment
VectorMA( muzzlePoint, 4, right, muzzlePoint );
VectorMA( muzzlePoint, -1, up, muzzlePoint );
if(!cg.renderingThirdPerson) {
if(cg_drawGun.integer == 2)
VectorMA(muzzlePoint, 8, cg.refdef.viewaxis[1], muzzlePoint);
else if(cg_drawGun.integer == 3)
VectorMA(muzzlePoint, 4, cg.refdef.viewaxis[1], muzzlePoint);
}
// draw a rail trail
CG_RailTrail( &cgs.clientinfo[cent->currentState.number], muzzlePoint, trace.endpos );
//Com_Printf( "Predicted rail trail\n" );
// explosion at end if not SURF_NOIMPACT
if ( !(trace.surfaceFlags & SURF_NOIMPACT) ) {
// predict an explosion
CG_MissileHitWall( ent->weapon, cg.predictedPlayerState.clientNum, trace.endpos, trace.plane.normal, IMPACTSOUND_DEFAULT );
}
}
}
// was it a shotgun attack?
else if ( ent->weapon == WP_SHOTGUN ) {
// do we have it on for the shotgun?
if ( cg_delag.integer & 1 || cg_delag.integer & 4 ) {
int contents;
vec3_t endPoint, v;
// do everything like the server does
SnapVector( muzzlePoint );
VectorScale( forward, 4096, endPoint );
SnapVector( endPoint );
VectorSubtract( endPoint, muzzlePoint, v );
VectorNormalize( v );
VectorScale( v, 32, v );
VectorAdd( muzzlePoint, v, v );
if ( cgs.glconfig.hardwareType != GLHW_RAGEPRO ) {
// ragepro can't alpha fade, so don't even bother with smoke
vec3_t up;
contents = trap_CM_PointContents( muzzlePoint, 0 );
if ( !( contents & CONTENTS_WATER ) ) {
VectorSet( up, 0, 0, 8 );
CG_SmokePuff( v, up, 32, 1, 1, 1, 0.33f, 900, cg.time, 0, LEF_PUFF_DONT_SCALE, cgs.media.shotgunSmokePuffShader );
}
}
// do the shotgun pellets
CG_ShotgunPattern( muzzlePoint, endPoint, cg.oldTime % 256, cg.predictedPlayerState.clientNum );
//Com_Printf( "Predicted shotgun pattern\n" );
}
}
// was it a machinegun attack?
else if ( ent->weapon == WP_MACHINEGUN ) {
// do we have it on for the machinegun?
if ( cg_delag.integer & 1 || cg_delag.integer & 2 ) {
// the server will use this exact time (it'll be serverTime on that end)
int seed = cg.oldTime % 256;
float r, u;
trace_t tr;
qboolean flesh;
int fleshEntityNum = 0;
vec3_t endPoint;
// do everything exactly like the server does
r = Q_random(&seed) * M_PI * 2.0f;
u = sin(r) * Q_crandom(&seed) * MACHINEGUN_SPREAD * 16;
r = cos(r) * Q_crandom(&seed) * MACHINEGUN_SPREAD * 16;
VectorMA( muzzlePoint, 8192*16, forward, endPoint );
VectorMA( endPoint, r, right, endPoint );
VectorMA( endPoint, u, up, endPoint );
CG_Trace(&tr, muzzlePoint, NULL, NULL, endPoint, cg.predictedPlayerState.clientNum, MASK_SHOT );
if ( tr.surfaceFlags & SURF_NOIMPACT ) {
return;
}
// snap the endpos to integers, but nudged towards the line
SnapVectorTowards( tr.endpos, muzzlePoint );
// do bullet impact
if ( tr.entityNum < MAX_CLIENTS ) {
flesh = qtrue;
fleshEntityNum = tr.entityNum;
} else {
flesh = qfalse;
}
// do the bullet impact
CG_Bullet( tr.endpos, cg.predictedPlayerState.clientNum, tr.plane.normal, flesh, fleshEntityNum );
//Com_Printf( "Predicted bullet\n" );
}
}
// was it a chaingun attack?
else if ( ent->weapon == WP_CHAINGUN ) {
// do we have it on for the machinegun?
if ( cg_delag.integer & 1 || cg_delag.integer & 2 ) {
// the server will use this exact time (it'll be serverTime on that end)
int seed = cg.oldTime % 256;
float r, u;
trace_t tr;
qboolean flesh;
int fleshEntityNum = 0;
vec3_t endPoint;
// do everything exactly like the server does
r = Q_random(&seed) * M_PI * 2.0f;
u = sin(r) * Q_crandom(&seed) * CHAINGUN_SPREAD * 16;
r = cos(r) * Q_crandom(&seed) * CHAINGUN_SPREAD * 16;
VectorMA( muzzlePoint, 8192*16, forward, endPoint );
VectorMA( endPoint, r, right, endPoint );
VectorMA( endPoint, u, up, endPoint );
CG_Trace(&tr, muzzlePoint, NULL, NULL, endPoint, cg.predictedPlayerState.clientNum, MASK_SHOT );
if ( tr.surfaceFlags & SURF_NOIMPACT ) {
return;
}
// snap the endpos to integers, but nudged towards the line
SnapVectorTowards( tr.endpos, muzzlePoint );
// do bullet impact
if ( tr.entityNum < MAX_CLIENTS ) {
flesh = qtrue;
fleshEntityNum = tr.entityNum;
} else {
flesh = qfalse;
}
// do the bullet impact
CG_Bullet( tr.endpos, cg.predictedPlayerState.clientNum, tr.plane.normal, flesh, fleshEntityNum );
//Com_Printf( "Predicted bullet\n" );
}
}
}
/*
=================
CG_AddBoundingBox
Draws a bounding box around a player. Called from CG_Player.
=================
*/
/*void CG_AddBoundingBox( centity_t *cent ) {
polyVert_t verts[4];
clientInfo_t *ci;
int i;
vec3_t mins = {-15, -15, -24};
vec3_t maxs = {15, 15, 32};
float extx, exty, extz;
vec3_t corners[8];
qhandle_t bboxShader, bboxShader_nocull;
if ( !cg_drawBBox.integer ) {
return;
}
// don't draw it if it's us in first-person
if ( cent->currentState.number == cg.predictedPlayerState.clientNum &&
!cg.renderingThirdPerson ) {
return;
}
// don't draw it for dead players
if ( cent->currentState.eFlags & EF_DEAD ) {
return;
}
// get the shader handles
bboxShader = trap_R_RegisterShader( "bbox" );
bboxShader_nocull = trap_R_RegisterShader( "bbox_nocull" );
// if they don't exist, forget it
if ( !bboxShader || !bboxShader_nocull ) {
return;
}
// get the player's client info
ci = &cgs.clientinfo[cent->currentState.clientNum];
// if it's us
if ( cent->currentState.number == cg.predictedPlayerState.clientNum ) {
// use the view height
maxs[2] = cg.predictedPlayerState.viewheight + 6;
}
else {
int x, zd, zu;
// otherwise grab the encoded bounding box
x = (cent->currentState.solid & 255);
zd = ((cent->currentState.solid>>8) & 255);
zu = ((cent->currentState.solid>>16) & 255) - 32;
mins[0] = mins[1] = -x;
maxs[0] = maxs[1] = x;
mins[2] = -zd;
maxs[2] = zu;
}
// get the extents (size)
extx = maxs[0] - mins[0];
exty = maxs[1] - mins[1];
extz = maxs[2] - mins[2];
// set the polygon's texture coordinates
verts[0].st[0] = 0;
verts[0].st[1] = 0;
verts[1].st[0] = 0;
verts[1].st[1] = 1;
verts[2].st[0] = 1;
verts[2].st[1] = 1;
verts[3].st[0] = 1;
verts[3].st[1] = 0;
// set the polygon's vertex colors
if ( ci->team == TEAM_RED ) {
for ( i = 0; i < 4; i++ ) {
verts[i].modulate[0] = 160;
verts[i].modulate[1] = 0;
verts[i].modulate[2] = 0;
verts[i].modulate[3] = 255;
}
}
else if ( ci->team == TEAM_BLUE ) {
for ( i = 0; i < 4; i++ ) {
verts[i].modulate[0] = 0;
verts[i].modulate[1] = 0;
verts[i].modulate[2] = 192;
verts[i].modulate[3] = 255;
}
}
else {
for ( i = 0; i < 4; i++ ) {
verts[i].modulate[0] = 0;
verts[i].modulate[1] = 128;
verts[i].modulate[2] = 0;
verts[i].modulate[3] = 255;
}
}
VectorAdd( cent->lerpOrigin, maxs, corners[3] );
VectorCopy( corners[3], corners[2] );
corners[2][0] -= extx;
VectorCopy( corners[2], corners[1] );
corners[1][1] -= exty;
VectorCopy( corners[1], corners[0] );
corners[0][0] += extx;
for ( i = 0; i < 4; i++ ) {
VectorCopy( corners[i], corners[i + 4] );
corners[i + 4][2] -= extz;
}
// top
VectorCopy( corners[0], verts[0].xyz );
VectorCopy( corners[1], verts[1].xyz );
VectorCopy( corners[2], verts[2].xyz );
VectorCopy( corners[3], verts[3].xyz );
trap_R_AddPolyToScene( bboxShader, 4, verts );
// bottom
VectorCopy( corners[7], verts[0].xyz );
VectorCopy( corners[6], verts[1].xyz );
VectorCopy( corners[5], verts[2].xyz );
VectorCopy( corners[4], verts[3].xyz );
trap_R_AddPolyToScene( bboxShader, 4, verts );
// top side
VectorCopy( corners[3], verts[0].xyz );
VectorCopy( corners[2], verts[1].xyz );
VectorCopy( corners[6], verts[2].xyz );
VectorCopy( corners[7], verts[3].xyz );
trap_R_AddPolyToScene( bboxShader_nocull, 4, verts );
// left side
VectorCopy( corners[2], verts[0].xyz );
VectorCopy( corners[1], verts[1].xyz );
VectorCopy( corners[5], verts[2].xyz );
VectorCopy( corners[6], verts[3].xyz );
trap_R_AddPolyToScene( bboxShader_nocull, 4, verts );
// right side
VectorCopy( corners[0], verts[0].xyz );
VectorCopy( corners[3], verts[1].xyz );
VectorCopy( corners[7], verts[2].xyz );
VectorCopy( corners[4], verts[3].xyz );
trap_R_AddPolyToScene( bboxShader_nocull, 4, verts );
// bottom side
VectorCopy( corners[1], verts[0].xyz );
VectorCopy( corners[0], verts[1].xyz );
VectorCopy( corners[4], verts[2].xyz );
VectorCopy( corners[5], verts[3].xyz );
trap_R_AddPolyToScene( bboxShader_nocull, 4, verts );
}*/
/*
================
CG_Cvar_ClampInt
Clamps a cvar between two integer values, returns qtrue if it had to.
================
*/
qboolean CG_Cvar_ClampInt( const char *name, vmCvar_t *vmCvar, int min, int max ) {
if ( vmCvar->integer > max ) {
CG_Printf( "Allowed values are %d to %d.\n", min, max );
Com_sprintf( vmCvar->string, MAX_CVAR_VALUE_STRING, "%d", max );
vmCvar->value = max;
vmCvar->integer = max;
trap_Cvar_Set( name, vmCvar->string );
return qtrue;
}
if ( vmCvar->integer < min ) {
CG_Printf( "Allowed values are %d to %d.\n", min, max );
Com_sprintf( vmCvar->string, MAX_CVAR_VALUE_STRING, "%d", min );
vmCvar->value = min;
vmCvar->integer = min;
trap_Cvar_Set( name, vmCvar->string );
return qtrue;
}
return qfalse;
}

889
code/cgame/cg_view.c Normal file
View File

@@ -0,0 +1,889 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// cg_view.c -- setup all the parameters (position, angle, etc)
// for a 3D rendering
#include "cg_local.h"
/*
=============================================================================
MODEL TESTING
The viewthing and gun positioning tools from Q2 have been integrated and
enhanced into a single model testing facility.
Model viewing can begin with either "testmodel <modelname>" or "testgun <modelname>".
The names must be the full pathname after the basedir, like
"models/weapons/v_launch/tris.md3" or "players/male/tris.md3"
Testmodel will create a fake entity 100 units in front of the current view
position, directly facing the viewer. It will remain immobile, so you can
move around it to view it from different angles.
Testgun will cause the model to follow the player around and supress the real
view weapon model. The default frame 0 of most guns is completely off screen,
so you will probably have to cycle a couple frames to see it.
"nextframe", "prevframe", "nextskin", and "prevskin" commands will change the
frame or skin of the testmodel. These are bound to F5, F6, F7, and F8 in
q3default.cfg.
If a gun is being tested, the "gun_x", "gun_y", and "gun_z" variables will let
you adjust the positioning.
Note that none of the model testing features update while the game is paused, so
it may be convenient to test with deathmatch set to 1 so that bringing down the
console doesn't pause the game.
=============================================================================
*/
/*
=================
CG_TestModel_f
Creates an entity in front of the current position, which
can then be moved around
=================
*/
void CG_TestModel_f (void) {
vec3_t angles;
memset( &cg.testModelEntity, 0, sizeof(cg.testModelEntity) );
if ( trap_Argc() < 2 ) {
return;
}
Q_strncpyz (cg.testModelName, CG_Argv( 1 ), MAX_QPATH );
cg.testModelEntity.hModel = trap_R_RegisterModel( cg.testModelName );
if ( trap_Argc() == 3 ) {
cg.testModelEntity.backlerp = atof( CG_Argv( 2 ) );
cg.testModelEntity.frame = 1;
cg.testModelEntity.oldframe = 0;
}
if (! cg.testModelEntity.hModel ) {
CG_Printf( "Can't register model\n" );
return;
}
VectorMA( cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin );
angles[PITCH] = 0;
angles[YAW] = 180 + cg.refdefViewAngles[1];
angles[ROLL] = 0;
AnglesToAxis( angles, cg.testModelEntity.axis );
cg.testGun = qfalse;
}
/*
=================
CG_TestGun_f
Replaces the current view weapon with the given model
=================
*/
void CG_TestGun_f (void) {
CG_TestModel_f();
cg.testGun = qtrue;
cg.testModelEntity.renderfx = RF_MINLIGHT | RF_DEPTHHACK | RF_FIRST_PERSON;
}
void CG_TestModelNextFrame_f (void) {
cg.testModelEntity.frame++;
CG_Printf( "frame %i\n", cg.testModelEntity.frame );
}
void CG_TestModelPrevFrame_f (void) {
cg.testModelEntity.frame--;
if ( cg.testModelEntity.frame < 0 ) {
cg.testModelEntity.frame = 0;
}
CG_Printf( "frame %i\n", cg.testModelEntity.frame );
}
void CG_TestModelNextSkin_f (void) {
cg.testModelEntity.skinNum++;
CG_Printf( "skin %i\n", cg.testModelEntity.skinNum );
}
void CG_TestModelPrevSkin_f (void) {
cg.testModelEntity.skinNum--;
if ( cg.testModelEntity.skinNum < 0 ) {
cg.testModelEntity.skinNum = 0;
}
CG_Printf( "skin %i\n", cg.testModelEntity.skinNum );
}
static void CG_AddTestModel (void) {
int i;
// re-register the model, because the level may have changed
cg.testModelEntity.hModel = trap_R_RegisterModel( cg.testModelName );
if (! cg.testModelEntity.hModel ) {
CG_Printf ("Can't register model\n");
return;
}
// if testing a gun, set the origin reletive to the view origin
if ( cg.testGun ) {
VectorCopy( cg.refdef.vieworg, cg.testModelEntity.origin );
VectorCopy( cg.refdef.viewaxis[0], cg.testModelEntity.axis[0] );
VectorCopy( cg.refdef.viewaxis[1], cg.testModelEntity.axis[1] );
VectorCopy( cg.refdef.viewaxis[2], cg.testModelEntity.axis[2] );
// allow the position to be adjusted
for (i=0 ; i<3 ; i++) {
cg.testModelEntity.origin[i] += cg.refdef.viewaxis[0][i] * cg_gun_x.value;
cg.testModelEntity.origin[i] += cg.refdef.viewaxis[1][i] * cg_gun_y.value;
cg.testModelEntity.origin[i] += cg.refdef.viewaxis[2][i] * cg_gun_z.value;
}
}
trap_R_AddRefEntityToScene( &cg.testModelEntity );
}
//============================================================================
/*
=================
CG_CalcVrect
Sets the coordinates of the rendered window
=================
*/
static void CG_CalcVrect (void) {
int size;
// the intermission should allways be full screen
if ( cg.snap->ps.pm_type == PM_INTERMISSION ) {
size = 100;
} else {
// bound normal viewsize
if (cg_viewsize.integer < 30) {
trap_Cvar_Set ("cg_viewsize","30");
size = 30;
} else if (cg_viewsize.integer > 100) {
trap_Cvar_Set ("cg_viewsize","100");
size = 100;
} else {
size = cg_viewsize.integer;
}
}
cg.refdef.width = cgs.glconfig.vidWidth*size/100;
cg.refdef.width &= ~1;
cg.refdef.height = cgs.glconfig.vidHeight*size/100;
cg.refdef.height &= ~1;
cg.refdef.x = (cgs.glconfig.vidWidth - cg.refdef.width)/2;
cg.refdef.y = (cgs.glconfig.vidHeight - cg.refdef.height)/2;
}
//==============================================================================
/*
===============
CG_OffsetThirdPersonView
===============
*/
#define FOCUS_DISTANCE 512
static void CG_OffsetThirdPersonView( void ) {
vec3_t forward, right, up;
vec3_t view;
vec3_t focusAngles;
trace_t trace;
static vec3_t mins = { -4, -4, -4 };
static vec3_t maxs = { 4, 4, 4 };
vec3_t focusPoint;
float focusDist;
float forwardScale, sideScale;
cg.refdef.vieworg[2] += cg.predictedPlayerState.viewheight;
VectorCopy( cg.refdefViewAngles, focusAngles );
// if dead, look at killer
if ( (cg.predictedPlayerState.stats[STAT_HEALTH] <= 0) &&
(cgs.gametype !=GT_ELIMINATION && cgs.gametype !=GT_CTF_ELIMINATION && cgs.gametype !=GT_LMS) ) {
focusAngles[YAW] = cg.predictedPlayerState.stats[STAT_DEAD_YAW];
cg.refdefViewAngles[YAW] = cg.predictedPlayerState.stats[STAT_DEAD_YAW];
}
if ( focusAngles[PITCH] > 45 ) {
focusAngles[PITCH] = 45; // don't go too far overhead
}
AngleVectors( focusAngles, forward, NULL, NULL );
VectorMA( cg.refdef.vieworg, FOCUS_DISTANCE, forward, focusPoint );
VectorCopy( cg.refdef.vieworg, view );
view[2] += 8;
cg.refdefViewAngles[PITCH] *= 0.5;
AngleVectors( cg.refdefViewAngles, forward, right, up );
forwardScale = cos( cg_thirdPersonAngle.value / 180 * M_PI );
sideScale = sin( cg_thirdPersonAngle.value / 180 * M_PI );
VectorMA( view, -cg_thirdPersonRange.value * forwardScale, forward, view );
VectorMA( view, -cg_thirdPersonRange.value * sideScale, right, view );
// trace a ray from the origin to the viewpoint to make sure the view isn't
// in a solid block. Use an 8 by 8 block to prevent the view from near clipping anything
if (!cg_cameraMode.integer) {
CG_Trace( &trace, cg.refdef.vieworg, mins, maxs, view, cg.predictedPlayerState.clientNum, MASK_SOLID );
if ( trace.fraction != 1.0 ) {
VectorCopy( trace.endpos, view );
view[2] += (1.0 - trace.fraction) * 32;
// try another trace to this position, because a tunnel may have the ceiling
// close enogh that this is poking out
CG_Trace( &trace, cg.refdef.vieworg, mins, maxs, view, cg.predictedPlayerState.clientNum, MASK_SOLID );
VectorCopy( trace.endpos, view );
}
}
VectorCopy( view, cg.refdef.vieworg );
// select pitch to look at focus point from vieword
VectorSubtract( focusPoint, cg.refdef.vieworg, focusPoint );
focusDist = sqrt( focusPoint[0] * focusPoint[0] + focusPoint[1] * focusPoint[1] );
if ( focusDist < 1 ) {
focusDist = 1; // should never happen
}
cg.refdefViewAngles[PITCH] = -180 / M_PI * atan2( focusPoint[2], focusDist );
cg.refdefViewAngles[YAW] -= cg_thirdPersonAngle.value;
}
// this causes a compiler bug on mac MrC compiler
static void CG_StepOffset( void ) {
int timeDelta;
// smooth out stair climbing
timeDelta = cg.time - cg.stepTime;
if ( timeDelta < STEP_TIME ) {
cg.refdef.vieworg[2] -= cg.stepChange
* (STEP_TIME - timeDelta) / STEP_TIME;
}
}
/*
===============
CG_OffsetFirstPersonView
===============
*/
static void CG_OffsetFirstPersonView( void ) {
float *origin;
float *angles;
float bob;
float ratio;
float delta;
float speed;
float f;
vec3_t predictedVelocity;
int timeDelta;
if ( cg.snap->ps.pm_type == PM_INTERMISSION ) {
return;
}
origin = cg.refdef.vieworg;
angles = cg.refdefViewAngles;
// if dead, fix the angle and don't add any kick
if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) {
angles[ROLL] = 40;
angles[PITCH] = -15;
angles[YAW] = cg.snap->ps.stats[STAT_DEAD_YAW];
origin[2] += cg.predictedPlayerState.viewheight;
return;
}
// add angles based on weapon kick
VectorAdd (angles, cg.kick_angles, angles);
// add angles based on damage kick
if ( cg.damageTime && cgs.gametype!=GT_ELIMINATION && cgs.gametype!=GT_CTF_ELIMINATION && cgs.gametype!=GT_LMS) {
ratio = cg.time - cg.damageTime;
if ( ratio < DAMAGE_DEFLECT_TIME ) {
ratio /= DAMAGE_DEFLECT_TIME;
angles[PITCH] += ratio * cg.v_dmg_pitch;
angles[ROLL] += ratio * cg.v_dmg_roll;
} else {
ratio = 1.0 - ( ratio - DAMAGE_DEFLECT_TIME ) / DAMAGE_RETURN_TIME;
if ( ratio > 0 ) {
angles[PITCH] += ratio * cg.v_dmg_pitch;
angles[ROLL] += ratio * cg.v_dmg_roll;
}
}
}
// add pitch based on fall kick
#if 0
ratio = ( cg.time - cg.landTime) / FALL_TIME;
if (ratio < 0)
ratio = 0;
angles[PITCH] += ratio * cg.fall_value;
#endif
// add angles based on velocity
VectorCopy( cg.predictedPlayerState.velocity, predictedVelocity );
delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[0]);
angles[PITCH] += delta * cg_runpitch.value;
delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[1]);
angles[ROLL] -= delta * cg_runroll.value;
// add angles based on bob
// make sure the bob is visible even at low speeds
speed = cg.xyspeed > 200 ? cg.xyspeed : 200;
delta = cg.bobfracsin * cg_bobpitch.value * speed;
if (cg.predictedPlayerState.pm_flags & PMF_DUCKED)
delta *= 3; // crouching
angles[PITCH] += delta;
delta = cg.bobfracsin * cg_bobroll.value * speed;
if (cg.predictedPlayerState.pm_flags & PMF_DUCKED)
delta *= 3; // crouching accentuates roll
if (cg.bobcycle & 1)
delta = -delta;
angles[ROLL] += delta;
//===================================
// add view height
origin[2] += cg.predictedPlayerState.viewheight;
// smooth out duck height changes
timeDelta = cg.time - cg.duckTime;
if ( timeDelta < DUCK_TIME) {
cg.refdef.vieworg[2] -= cg.duckChange
* (DUCK_TIME - timeDelta) / DUCK_TIME;
}
// add bob height
bob = cg.bobfracsin * cg.xyspeed * cg_bobup.value;
if (bob > 6) {
bob = 6;
}
origin[2] += bob;
// add fall height
delta = cg.time - cg.landTime;
if ( delta < LAND_DEFLECT_TIME ) {
f = delta / LAND_DEFLECT_TIME;
cg.refdef.vieworg[2] += cg.landChange * f;
} else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) {
delta -= LAND_DEFLECT_TIME;
f = 1.0 - ( delta / LAND_RETURN_TIME );
cg.refdef.vieworg[2] += cg.landChange * f;
}
// add step offset
CG_StepOffset();
// add kick offset
VectorAdd (origin, cg.kick_origin, origin);
// pivot the eye based on a neck length
#if 0
{
#define NECK_LENGTH 8
vec3_t forward, up;
cg.refdef.vieworg[2] -= NECK_LENGTH;
AngleVectors( cg.refdefViewAngles, forward, NULL, up );
VectorMA( cg.refdef.vieworg, 3, forward, cg.refdef.vieworg );
VectorMA( cg.refdef.vieworg, NECK_LENGTH, up, cg.refdef.vieworg );
}
#endif
}
//======================================================================
void CG_ZoomDown_f( void ) {
if ( cg.zoomed ) {
return;
}
cg.zoomed = qtrue;
cg.zoomTime = cg.time;
}
void CG_ZoomUp_f( void ) {
if ( !cg.zoomed ) {
return;
}
cg.zoomed = qfalse;
cg.zoomTime = cg.time;
}
/*
====================
CG_CalcFov
Fixed fov at intermissions, otherwise account for fov variable and zooms.
====================
*/
#define WAVE_AMPLITUDE 1
#define WAVE_FREQUENCY 0.4
static int CG_CalcFov( void ) {
float x;
float phase;
float v;
int contents;
float fov_x, fov_y;
float zoomFov;
float f;
int inwater;
if ( cg.predictedPlayerState.pm_type == PM_INTERMISSION ) {
// if in intermission, use a fixed value
fov_x = 90;
} else {
// user selectable
if ( cgs.dmflags & DF_FIXED_FOV ) {
// dmflag to prevent wide fov for all clients
fov_x = 90;
} else {
fov_x = cg_fov.value;
if ( fov_x < 1 ) {
fov_x = 1;
} else if ( fov_x > 160 ) {
fov_x = 160;
}
if( (cgs.videoflags & VF_LOCK_CVARS_BASIC) && fov_x>140 )
fov_x = 140;
}
if ( cgs.dmflags & DF_FIXED_FOV ) {
// dmflag to prevent wide fov for all clients
zoomFov = 22.5;
} else {
// account for zooms
zoomFov = cg_zoomFov.value;
if ( zoomFov < 1 ) {
zoomFov = 1;
} else if ( zoomFov > 160 ) {
zoomFov = 160;
}
if( (cgs.videoflags & VF_LOCK_CVARS_BASIC) && zoomFov>140 )
zoomFov = 140;
}
if ( cg.zoomed ) {
f = ( cg.time - cg.zoomTime ) / (float)ZOOM_TIME;
if ( f > 1.0 ) {
fov_x = zoomFov;
} else {
fov_x = fov_x + f * ( zoomFov - fov_x );
}
} else {
f = ( cg.time - cg.zoomTime ) / (float)ZOOM_TIME;
if ( f > 1.0 ) {
fov_x = fov_x;
} else {
fov_x = zoomFov + f * ( fov_x - zoomFov );
}
}
}
x = cg.refdef.width / tan( fov_x / 360 * M_PI );
fov_y = atan2( cg.refdef.height, x );
fov_y = fov_y * 360 / M_PI;
// warp if underwater
contents = CG_PointContents( cg.refdef.vieworg, -1 );
if ( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ){
phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2;
v = WAVE_AMPLITUDE * sin( phase );
fov_x += v;
fov_y -= v;
inwater = qtrue;
}
else {
inwater = qfalse;
}
// set it
cg.refdef.fov_x = fov_x;
cg.refdef.fov_y = fov_y;
if ( !cg.zoomed ) {
cg.zoomSensitivity = 1;
} else {
cg.zoomSensitivity = cg.refdef.fov_y / 75.0;
}
return inwater;
}
/*
===============
CG_DamageBlendBlob
===============
*/
static void CG_DamageBlendBlob( void ) {
int t;
int maxTime;
refEntity_t ent;
if ( !cg.damageValue ) {
return;
}
//if (cg.cameraMode) {
// return;
//}
// ragePro systems can't fade blends, so don't obscure the screen
if ( cgs.glconfig.hardwareType == GLHW_RAGEPRO ) {
return;
}
maxTime = DAMAGE_TIME;
t = cg.time - cg.damageTime;
if ( t <= 0 || t >= maxTime ) {
return;
}
memset( &ent, 0, sizeof( ent ) );
ent.reType = RT_SPRITE;
ent.renderfx = RF_FIRST_PERSON;
VectorMA( cg.refdef.vieworg, 8, cg.refdef.viewaxis[0], ent.origin );
VectorMA( ent.origin, cg.damageX * -8, cg.refdef.viewaxis[1], ent.origin );
VectorMA( ent.origin, cg.damageY * 8, cg.refdef.viewaxis[2], ent.origin );
ent.radius = cg.damageValue * 3;
ent.customShader = cgs.media.viewBloodShader;
ent.shaderRGBA[0] = 255;
ent.shaderRGBA[1] = 255;
ent.shaderRGBA[2] = 255;
ent.shaderRGBA[3] = 200 * ( 1.0 - ((float)t / maxTime) );
trap_R_AddRefEntityToScene( &ent );
}
/*
===============
CG_CalcViewValues
Sets cg.refdef view values
===============
*/
static int CG_CalcViewValues( void ) {
playerState_t *ps;
memset( &cg.refdef, 0, sizeof( cg.refdef ) );
// strings for in game rendering
// Q_strncpyz( cg.refdef.text[0], "Park Ranger", sizeof(cg.refdef.text[0]) );
// Q_strncpyz( cg.refdef.text[1], "19", sizeof(cg.refdef.text[1]) );
// calculate size of 3D view
CG_CalcVrect();
ps = &cg.predictedPlayerState;
/*
if (cg.cameraMode) {
vec3_t origin, angles;
if (trap_getCameraInfo(cg.time, &origin, &angles)) {
VectorCopy(origin, cg.refdef.vieworg);
angles[ROLL] = 0;
VectorCopy(angles, cg.refdefViewAngles);
AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis );
return CG_CalcFov();
} else {
cg.cameraMode = qfalse;
}
}
*/
// intermission view
if ( ps->pm_type == PM_INTERMISSION ) {
VectorCopy( ps->origin, cg.refdef.vieworg );
VectorCopy( ps->viewangles, cg.refdefViewAngles );
AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis );
return CG_CalcFov();
}
cg.bobcycle = ( ps->bobCycle & 128 ) >> 7;
cg.bobfracsin = fabs( sin( ( ps->bobCycle & 127 ) / 127.0 * M_PI ) );
cg.xyspeed = sqrt( ps->velocity[0] * ps->velocity[0] +
ps->velocity[1] * ps->velocity[1] );
VectorCopy( ps->origin, cg.refdef.vieworg );
VectorCopy( ps->viewangles, cg.refdefViewAngles );
if (cg_cameraOrbit.integer) {
if (cg.time > cg.nextOrbitTime) {
cg.nextOrbitTime = cg.time + cg_cameraOrbitDelay.integer;
cg_thirdPersonAngle.value += cg_cameraOrbit.value;
}
}
// add error decay
if ( cg_errorDecay.value > 0 ) {
int t;
float f;
t = cg.time - cg.predictedErrorTime;
f = ( cg_errorDecay.value - t ) / cg_errorDecay.value;
if ( f > 0 && f < 1 ) {
VectorMA( cg.refdef.vieworg, f, cg.predictedError, cg.refdef.vieworg );
} else {
cg.predictedErrorTime = 0;
}
}
if ( cg.renderingThirdPerson ) {
// back away from character
CG_OffsetThirdPersonView();
} else {
// offset for local bobbing and kicks
CG_OffsetFirstPersonView();
}
// position eye reletive to origin
AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis );
if ( cg.hyperspace ) {
cg.refdef.rdflags |= RDF_NOWORLDMODEL | RDF_HYPERSPACE;
}
// field of view
return CG_CalcFov();
}
/*
=====================
CG_PowerupTimerSounds
=====================
*/
static void CG_PowerupTimerSounds( void ) {
int i;
int t;
// powerup timers going away
for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
t = cg.snap->ps.powerups[i];
if ( t <= cg.time ) {
continue;
}
if ( t - cg.time >= POWERUP_BLINKS * POWERUP_BLINK_TIME ) {
continue;
}
if ( ( t - cg.time ) / POWERUP_BLINK_TIME != ( t - cg.oldTime ) / POWERUP_BLINK_TIME ) {
trap_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_ITEM, cgs.media.wearOffSound );
}
}
}
/*
=====================
CG_AddBufferedSound
=====================
*/
void CG_AddBufferedSound( sfxHandle_t sfx ) {
if ( !sfx )
return;
cg.soundBuffer[cg.soundBufferIn] = sfx;
cg.soundBufferIn = (cg.soundBufferIn + 1) % MAX_SOUNDBUFFER;
if (cg.soundBufferIn == cg.soundBufferOut) {
cg.soundBufferOut++;
}
}
/*
=====================
CG_PlayBufferedSounds
=====================
*/
static void CG_PlayBufferedSounds( void ) {
if ( cg.soundTime < cg.time ) {
if (cg.soundBufferOut != cg.soundBufferIn && cg.soundBuffer[cg.soundBufferOut]) {
trap_S_StartLocalSound(cg.soundBuffer[cg.soundBufferOut], CHAN_ANNOUNCER);
cg.soundBuffer[cg.soundBufferOut] = 0;
cg.soundBufferOut = (cg.soundBufferOut + 1) % MAX_SOUNDBUFFER;
cg.soundTime = cg.time + 750;
}
}
}
//=========================================================================
/*
=================
CG_DrawActiveFrame
Generates and draws a game scene and status information at the given time.
=================
*/
void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demoPlayback ) {
int inwater;
cg.time = serverTime;
cg.demoPlayback = demoPlayback;
// update cvars
CG_UpdateCvars();
// if we are only updating the screen as a loading
// pacifier, don't even try to read snapshots
if ( cg.infoScreenText[0] != 0 ) {
CG_DrawInformation();
return;
}
// any looped sounds will be respecified as entities
// are added to the render list
trap_S_ClearLoopingSounds(qfalse);
// clear all the render lists
trap_R_ClearScene();
// set up cg.snap and possibly cg.nextSnap
CG_ProcessSnapshots();
// if we haven't received any snapshots yet, all
// we can draw is the information screen
if ( !cg.snap || ( cg.snap->snapFlags & SNAPFLAG_NOT_ACTIVE ) ) {
CG_DrawInformation();
return;
}
// let the client system know what our weapon and zoom settings are
trap_SetUserCmdValue( cg.weaponSelect, cg.zoomSensitivity );
// this counter will be bumped for every valid scene we generate
cg.clientFrame++;
// update cg.predictedPlayerState
CG_PredictPlayerState();
// decide on third person view
cg.renderingThirdPerson = cg_thirdPerson.integer || (cg.snap->ps.stats[STAT_HEALTH] <= 0);
// build cg.refdef
inwater = CG_CalcViewValues();
// first person blend blobs, done after AnglesToAxis
if ( !cg.renderingThirdPerson ) {
CG_DamageBlendBlob();
}
// build the render lists
if ( !cg.hyperspace ) {
CG_AddPacketEntities(); // adter calcViewValues, so predicted player state is correct
CG_AddMarks();
CG_AddParticles ();
CG_AddLocalEntities();
}
CG_AddViewWeapon( &cg.predictedPlayerState );
// add buffered sounds
CG_PlayBufferedSounds();
// play buffered voice chats
CG_PlayBufferedVoiceChats();
// finish up the rest of the refdef
if ( cg.testModelEntity.hModel ) {
CG_AddTestModel();
}
cg.refdef.time = cg.time;
memcpy( cg.refdef.areamask, cg.snap->areamask, sizeof( cg.refdef.areamask ) );
// warning sounds when powerup is wearing off
CG_PowerupTimerSounds();
// update audio positions
trap_S_Respatialize( cg.snap->ps.clientNum, cg.refdef.vieworg, cg.refdef.viewaxis, inwater );
// make sure the lagometerSample and frame timing isn't done twice when in stereo
if ( stereoView != STEREO_RIGHT ) {
cg.frametime = cg.time - cg.oldTime;
if ( cg.frametime < 0 ) {
cg.frametime = 0;
}
cg.oldTime = cg.time;
CG_AddLagometerFrameInfo();
}
if (cg_timescale.value != cg_timescaleFadeEnd.value) {
if (cg_timescale.value < cg_timescaleFadeEnd.value) {
cg_timescale.value += cg_timescaleFadeSpeed.value * ((float)cg.frametime) / 1000;
if (cg_timescale.value > cg_timescaleFadeEnd.value)
cg_timescale.value = cg_timescaleFadeEnd.value;
}
else {
cg_timescale.value -= cg_timescaleFadeSpeed.value * ((float)cg.frametime) / 1000;
if (cg_timescale.value < cg_timescaleFadeEnd.value)
cg_timescale.value = cg_timescaleFadeEnd.value;
}
if (cg_timescaleFadeSpeed.value) {
trap_Cvar_Set("timescale", va("%f", cg_timescale.value));
}
}
// actually issue the rendering calls
CG_DrawActive( stereoView );
if ( cg_stats.integer ) {
CG_Printf( "cg.clientFrame:%i\n", cg.clientFrame );
}
}

3654
code/cgame/cg_weapons.c Normal file

File diff suppressed because it is too large Load Diff

276
code/client/keycodes.h Normal file
View File

@@ -0,0 +1,276 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
#ifndef __KEYCODES_H__
#define __KEYCODES_H__
//
// these are the key numbers that should be passed to KeyEvent
//
// normal keys should be passed as lowercased ascii
typedef enum {
K_TAB = 9,
K_ENTER = 13,
K_ESCAPE = 27,
K_SPACE = 32,
K_BACKSPACE = 127,
K_COMMAND = 128,
K_CAPSLOCK,
K_POWER,
K_PAUSE,
K_UPARROW,
K_DOWNARROW,
K_LEFTARROW,
K_RIGHTARROW,
K_ALT,
K_CTRL,
K_SHIFT,
K_INS,
K_DEL,
K_PGDN,
K_PGUP,
K_HOME,
K_END,
K_F1,
K_F2,
K_F3,
K_F4,
K_F5,
K_F6,
K_F7,
K_F8,
K_F9,
K_F10,
K_F11,
K_F12,
K_F13,
K_F14,
K_F15,
K_KP_HOME,
K_KP_UPARROW,
K_KP_PGUP,
K_KP_LEFTARROW,
K_KP_5,
K_KP_RIGHTARROW,
K_KP_END,
K_KP_DOWNARROW,
K_KP_PGDN,
K_KP_ENTER,
K_KP_INS,
K_KP_DEL,
K_KP_SLASH,
K_KP_MINUS,
K_KP_PLUS,
K_KP_NUMLOCK,
K_KP_STAR,
K_KP_EQUALS,
K_MOUSE1,
K_MOUSE2,
K_MOUSE3,
K_MOUSE4,
K_MOUSE5,
K_MWHEELDOWN,
K_MWHEELUP,
K_JOY1,
K_JOY2,
K_JOY3,
K_JOY4,
K_JOY5,
K_JOY6,
K_JOY7,
K_JOY8,
K_JOY9,
K_JOY10,
K_JOY11,
K_JOY12,
K_JOY13,
K_JOY14,
K_JOY15,
K_JOY16,
K_JOY17,
K_JOY18,
K_JOY19,
K_JOY20,
K_JOY21,
K_JOY22,
K_JOY23,
K_JOY24,
K_JOY25,
K_JOY26,
K_JOY27,
K_JOY28,
K_JOY29,
K_JOY30,
K_JOY31,
K_JOY32,
K_AUX1,
K_AUX2,
K_AUX3,
K_AUX4,
K_AUX5,
K_AUX6,
K_AUX7,
K_AUX8,
K_AUX9,
K_AUX10,
K_AUX11,
K_AUX12,
K_AUX13,
K_AUX14,
K_AUX15,
K_AUX16,
K_WORLD_0,
K_WORLD_1,
K_WORLD_2,
K_WORLD_3,
K_WORLD_4,
K_WORLD_5,
K_WORLD_6,
K_WORLD_7,
K_WORLD_8,
K_WORLD_9,
K_WORLD_10,
K_WORLD_11,
K_WORLD_12,
K_WORLD_13,
K_WORLD_14,
K_WORLD_15,
K_WORLD_16,
K_WORLD_17,
K_WORLD_18,
K_WORLD_19,
K_WORLD_20,
K_WORLD_21,
K_WORLD_22,
K_WORLD_23,
K_WORLD_24,
K_WORLD_25,
K_WORLD_26,
K_WORLD_27,
K_WORLD_28,
K_WORLD_29,
K_WORLD_30,
K_WORLD_31,
K_WORLD_32,
K_WORLD_33,
K_WORLD_34,
K_WORLD_35,
K_WORLD_36,
K_WORLD_37,
K_WORLD_38,
K_WORLD_39,
K_WORLD_40,
K_WORLD_41,
K_WORLD_42,
K_WORLD_43,
K_WORLD_44,
K_WORLD_45,
K_WORLD_46,
K_WORLD_47,
K_WORLD_48,
K_WORLD_49,
K_WORLD_50,
K_WORLD_51,
K_WORLD_52,
K_WORLD_53,
K_WORLD_54,
K_WORLD_55,
K_WORLD_56,
K_WORLD_57,
K_WORLD_58,
K_WORLD_59,
K_WORLD_60,
K_WORLD_61,
K_WORLD_62,
K_WORLD_63,
K_WORLD_64,
K_WORLD_65,
K_WORLD_66,
K_WORLD_67,
K_WORLD_68,
K_WORLD_69,
K_WORLD_70,
K_WORLD_71,
K_WORLD_72,
K_WORLD_73,
K_WORLD_74,
K_WORLD_75,
K_WORLD_76,
K_WORLD_77,
K_WORLD_78,
K_WORLD_79,
K_WORLD_80,
K_WORLD_81,
K_WORLD_82,
K_WORLD_83,
K_WORLD_84,
K_WORLD_85,
K_WORLD_86,
K_WORLD_87,
K_WORLD_88,
K_WORLD_89,
K_WORLD_90,
K_WORLD_91,
K_WORLD_92,
K_WORLD_93,
K_WORLD_94,
K_WORLD_95,
K_SUPER,
K_COMPOSE,
K_MODE,
K_HELP,
K_PRINT,
K_SYSREQ,
K_SCROLLOCK,
K_BREAK,
K_MENU,
K_EURO,
K_UNDO,
MAX_KEYS
} keyNum_t;
// MAX_KEYS replaces K_LAST_KEY, however some mods may have used K_LAST_KEY
// in detecting binds, so we leave it defined to the old hardcoded value
// of maxiumum keys to prevent mods from crashing older versions of the engine
#define K_LAST_KEY 256
// The menu code needs to get both key and char events, but
// to avoid duplicating the paths, the char events are just
// distinguished by or'ing in K_CHAR_FLAG (ugly)
#define K_CHAR_FLAG 1024
#endif

1218
code/game/ai_chat.c Normal file

File diff suppressed because it is too large Load Diff

61
code/game/ai_chat.h Normal file
View File

@@ -0,0 +1,61 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: ai_chat.h
*
* desc: Quake3 bot AI
*
* $Archive: /source/code/botai/ai_chat.c $
*
*****************************************************************************/
//
int BotChat_EnterGame(bot_state_t *bs);
//
int BotChat_ExitGame(bot_state_t *bs);
//
int BotChat_StartLevel(bot_state_t *bs);
//
int BotChat_EndLevel(bot_state_t *bs);
//
int BotChat_HitTalking(bot_state_t *bs);
//
int BotChat_HitNoDeath(bot_state_t *bs);
//
int BotChat_HitNoKill(bot_state_t *bs);
//
int BotChat_Death(bot_state_t *bs);
//
int BotChat_Kill(bot_state_t *bs);
//
int BotChat_EnemySuicide(bot_state_t *bs);
//
int BotChat_Random(bot_state_t *bs);
// time the selected chat takes to type in
float BotChatTime(bot_state_t *bs);
// returns true if the bot can chat at the current position
int BotValidChatPosition(bot_state_t *bs);
// test the initial bot chats
void BotChatTest(bot_state_t *bs);

2097
code/game/ai_cmd.c Normal file

File diff suppressed because it is too large Load Diff

37
code/game/ai_cmd.h Normal file
View File

@@ -0,0 +1,37 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: ai_cmd.h
*
* desc: Quake3 bot AI
*
* $Archive: /source/code/botai/ai_chat.c $
*
*****************************************************************************/
extern int notleader[MAX_CLIENTS];
int BotMatchMessage(bot_state_t *bs, char *message);
void BotPrintTeamGoal(bot_state_t *bs);

2698
code/game/ai_dmnet.c Normal file

File diff suppressed because it is too large Load Diff

61
code/game/ai_dmnet.h Normal file
View File

@@ -0,0 +1,61 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: ai_dmnet.h
*
* desc: Quake3 bot AI
*
* $Archive: /source/code/botai/ai_chat.c $
*
*****************************************************************************/
#define MAX_NODESWITCHES 50
void AIEnter_Intermission(bot_state_t *bs, char *s);
void AIEnter_Observer(bot_state_t *bs, char *s);
void AIEnter_Respawn(bot_state_t *bs, char *s);
void AIEnter_Stand(bot_state_t *bs, char *s);
void AIEnter_Seek_ActivateEntity(bot_state_t *bs, char *s);
void AIEnter_Seek_NBG(bot_state_t *bs, char *s);
void AIEnter_Seek_LTG(bot_state_t *bs, char *s);
void AIEnter_Seek_Camp(bot_state_t *bs, char *s);
void AIEnter_Battle_Fight(bot_state_t *bs, char *s);
void AIEnter_Battle_Chase(bot_state_t *bs, char *s);
void AIEnter_Battle_Retreat(bot_state_t *bs, char *s);
void AIEnter_Battle_NBG(bot_state_t *bs, char *s);
int AINode_Intermission(bot_state_t *bs);
int AINode_Observer(bot_state_t *bs);
int AINode_Respawn(bot_state_t *bs);
int AINode_Stand(bot_state_t *bs);
int AINode_Seek_ActivateEntity(bot_state_t *bs);
int AINode_Seek_NBG(bot_state_t *bs);
int AINode_Seek_LTG(bot_state_t *bs);
int AINode_Battle_Fight(bot_state_t *bs);
int AINode_Battle_Chase(bot_state_t *bs);
int AINode_Battle_Retreat(bot_state_t *bs);
int AINode_Battle_NBG(bot_state_t *bs);
void BotResetNodeSwitches(void);
void BotDumpNodeSwitches(bot_state_t *bs);

5580
code/game/ai_dmq3.c Normal file

File diff suppressed because it is too large Load Diff

200
code/game/ai_dmq3.h Normal file
View File

@@ -0,0 +1,200 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: ai_dmq3.h
*
* desc: Quake3 bot AI
*
* $Archive: /source/code/botai/ai_chat.c $
*
*****************************************************************************/
//setup the deathmatch AI
void BotSetupDeathmatchAI(void);
//shutdown the deathmatch AI
void BotShutdownDeathmatchAI(void);
//let the bot live within it's deathmatch AI net
void BotDeathmatchAI(bot_state_t *bs, float thinktime);
//free waypoints
void BotFreeWaypoints(bot_waypoint_t *wp);
//choose a weapon
void BotChooseWeapon(bot_state_t *bs);
//setup movement stuff
void BotSetupForMovement(bot_state_t *bs);
//update the inventory
void BotUpdateInventory(bot_state_t *bs);
//update the inventory during battle
void BotUpdateBattleInventory(bot_state_t *bs, int enemy);
//use holdable items during battle
void BotBattleUseItems(bot_state_t *bs);
//return true if the bot is dead
qboolean BotIsDead(bot_state_t *bs);
//returns true if the bot is in observer mode
qboolean BotIsObserver(bot_state_t *bs);
//returns true if the bot is in the intermission
qboolean BotIntermission(bot_state_t *bs);
//returns true if the bot is in lava or slime
qboolean BotInLavaOrSlime(bot_state_t *bs);
//returns true if the entity is dead
qboolean EntityIsDead(aas_entityinfo_t *entinfo);
//returns true if the entity is invisible
qboolean EntityIsInvisible(aas_entityinfo_t *entinfo);
//returns true if the entity is shooting
qboolean EntityIsShooting(aas_entityinfo_t *entinfo);
//returns true if this entity has the kamikaze
qboolean EntityHasKamikaze(aas_entityinfo_t *entinfo);
// set a user info key/value pair
void BotSetUserInfo(bot_state_t *bs, char *key, char *value);
// set the team status (offense, defense etc.)
void BotSetTeamStatus(bot_state_t *bs);
//returns the name of the client
char *ClientName(int client, char *name, int size);
//returns an simplyfied client name
char *EasyClientName(int client, char *name, int size);
//returns the skin used by the client
char *ClientSkin(int client, char *skin, int size);
// returns the appropriate synonym context for the current game type and situation
int BotSynonymContext(bot_state_t *bs);
// set last ordered task
int BotSetLastOrderedTask(bot_state_t *bs);
// selection of goals for teamplay
void BotTeamGoals(bot_state_t *bs, int retreat);
//returns the aggression of the bot in the range [0, 100]
float BotAggression(bot_state_t *bs);
//returns how bad the bot feels
float BotFeelingBad(bot_state_t *bs);
//returns true if the bot wants to retreat
int BotWantsToRetreat(bot_state_t *bs);
//returns true if the bot wants to chase
int BotWantsToChase(bot_state_t *bs);
//returns true if the bot wants to help
int BotWantsToHelp(bot_state_t *bs);
//returns true if the bot can and wants to rocketjump
int BotCanAndWantsToRocketJump(bot_state_t *bs);
// returns true if the bot has a persistant powerup and a weapon
int BotHasPersistantPowerupAndWeapon(bot_state_t *bs);
//returns true if the bot wants to and goes camping
int BotWantsToCamp(bot_state_t *bs);
//the bot will perform attack movements
bot_moveresult_t BotAttackMove(bot_state_t *bs, int tfl);
//returns true if the bot and the entity are in the same team
int BotSameTeam(bot_state_t *bs, int entnum);
//returns true if teamplay is on
int TeamPlayIsOn(void);
// returns the client number of the team mate flag carrier (-1 if none)
int BotTeamFlagCarrier(bot_state_t *bs);
//returns visible team mate flag carrier if available
int BotTeamFlagCarrierVisible(bot_state_t *bs);
//returns visible enemy flag carrier if available
int BotEnemyFlagCarrierVisible(bot_state_t *bs);
//get the number of visible teammates and enemies
void BotVisibleTeamMatesAndEnemies(bot_state_t *bs, int *teammates, int *enemies, float range);
//returns true if within the field of vision for the given angles
qboolean InFieldOfVision(vec3_t viewangles, float fov, vec3_t angles);
//returns true and sets the .enemy field when an enemy is found
int BotFindEnemy(bot_state_t *bs, int curenemy);
//returns a roam goal
void BotRoamGoal(bot_state_t *bs, vec3_t goal);
//returns entity visibility in the range [0, 1]
float BotEntityVisible(int viewer, vec3_t eye, vec3_t viewangles, float fov, int ent);
//the bot will aim at the current enemy
void BotAimAtEnemy(bot_state_t *bs);
//check if the bot should attack
void BotCheckAttack(bot_state_t *bs);
//AI when the bot is blocked
void BotAIBlocked(bot_state_t *bs, bot_moveresult_t *moveresult, int activate);
//AI to predict obstacles
int BotAIPredictObstacles(bot_state_t *bs, bot_goal_t *goal);
//enable or disable the areas the blocking entity is in
void BotEnableActivateGoalAreas(bot_activategoal_t *activategoal, int enable);
//pop an activate goal from the stack
int BotPopFromActivateGoalStack(bot_state_t *bs);
//clear the activate goal stack
void BotClearActivateGoalStack(bot_state_t *bs);
//returns the team the bot is in
int BotTeam(bot_state_t *bs);
//retuns the opposite team of the bot
int BotOppositeTeam(bot_state_t *bs);
//returns the flag the bot is carrying (CTFFLAG_?)
int BotCTFCarryingFlag(bot_state_t *bs);
//remember the last ordered task
void BotRememberLastOrderedTask(bot_state_t *bs);
//set ctf goals (defend base, get enemy flag) during seek
void BotCTFSeekGoals(bot_state_t *bs);
//set ctf goals (defend base, get enemy flag) during retreat
void BotCTFRetreatGoals(bot_state_t *bs);
//
int Bot1FCTFCarryingFlag(bot_state_t *bs);
int BotHarvesterCarryingCubes(bot_state_t *bs);
void Bot1FCTFSeekGoals(bot_state_t *bs);
void Bot1FCTFRetreatGoals(bot_state_t *bs);
void BotObeliskSeekGoals(bot_state_t *bs);
void BotObeliskRetreatGoals(bot_state_t *bs);
void BotGoHarvest(bot_state_t *bs);
void BotHarvesterSeekGoals(bot_state_t *bs);
void BotHarvesterRetreatGoals(bot_state_t *bs);
int BotTeamCubeCarrierVisible(bot_state_t *bs);
int BotEnemyCubeCarrierVisible(bot_state_t *bs);
//get a random alternate route goal towards the given base
int BotGetAlternateRouteGoal(bot_state_t *bs, int base);
//returns either the alternate route goal or the given goal
bot_goal_t *BotAlternateRoute(bot_state_t *bs, bot_goal_t *goal);
//create a new waypoint
bot_waypoint_t *BotCreateWayPoint(char *name, vec3_t origin, int areanum);
//find a waypoint with the given name
bot_waypoint_t *BotFindWayPoint(bot_waypoint_t *waypoints, char *name);
//strstr but case insensitive
char *stristr(char *str, char *charset);
//returns the number of the client with the given name
int ClientFromName(char *name);
int ClientOnSameTeamFromName(bot_state_t *bs, char *name);
//
int BotPointAreaNum(vec3_t origin);
//
void BotMapScripts(bot_state_t *bs);
//ctf flags
#define CTF_FLAG_NONE 0
#define CTF_FLAG_RED 1
#define CTF_FLAG_BLUE 2
//CTF skins
#define CTF_SKIN_REDTEAM "red"
#define CTF_SKIN_BLUETEAM "blue"
extern int gametype; //game type
extern int maxclients; //maximum number of clients
extern vmCvar_t bot_grapple;
extern vmCvar_t bot_rocketjump;
extern vmCvar_t bot_fastchat;
extern vmCvar_t bot_nochat;
extern vmCvar_t bot_testrchat;
extern vmCvar_t bot_challenge;
extern bot_goal_t ctf_redflag;
extern bot_goal_t ctf_blueflag;
extern bot_goal_t ctf_neutralflag;
extern bot_goal_t redobelisk;
extern bot_goal_t blueobelisk;
extern bot_goal_t neutralobelisk;

1738
code/game/ai_main.c Normal file

File diff suppressed because it is too large Load Diff

308
code/game/ai_main.h Normal file
View File

@@ -0,0 +1,308 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: ai_main.h
*
* desc: Quake3 bot AI
*
* $Archive: /source/code/botai/ai_chat.c $
*
*****************************************************************************/
//#define DEBUG
#define CTF
#define MAX_ITEMS 256
//bot flags
#define BFL_STRAFERIGHT 1 //strafe to the right
#define BFL_ATTACKED 2 //bot has attacked last ai frame
#define BFL_ATTACKJUMPED 4 //bot jumped during attack last frame
#define BFL_AIMATENEMY 8 //bot aimed at the enemy this frame
#define BFL_AVOIDRIGHT 16 //avoid obstacles by going to the right
#define BFL_IDEALVIEWSET 32 //bot has ideal view angles set
#define BFL_FIGHTSUICIDAL 64 //bot is in a suicidal fight
//long term goal types
#define LTG_TEAMHELP 1 //help a team mate
#define LTG_TEAMACCOMPANY 2 //accompany a team mate
#define LTG_DEFENDKEYAREA 3 //defend a key area
#define LTG_GETFLAG 4 //get the enemy flag
#define LTG_RUSHBASE 5 //rush to the base
#define LTG_RETURNFLAG 6 //return the flag
#define LTG_CAMP 7 //camp somewhere
#define LTG_CAMPORDER 8 //ordered to camp somewhere
#define LTG_PATROL 9 //patrol
#define LTG_GETITEM 10 //get an item
#define LTG_KILL 11 //kill someone
#define LTG_HARVEST 12 //harvest skulls
#define LTG_ATTACKENEMYBASE 13 //attack the enemy base
#define LTG_MAKELOVE_UNDER 14
#define LTG_MAKELOVE_ONTOP 15
//Long term DD goals
#define LTG_POINTA 16 //Take/Defend point A
#define LTG_POINTB 17 //Take/Defend point B
//Long term DD goals
#define LTG_DOMROAM 18 //Go for a non taken point.
#define LTG_DOMHOLD 19 //Pick a point and hold it.
//some goal dedication times
#define TEAM_HELP_TIME 60 //1 minute teamplay help time
#define TEAM_ACCOMPANY_TIME 600 //10 minutes teamplay accompany time
#define TEAM_DEFENDKEYAREA_TIME 600 //10 minutes ctf defend base time
#define TEAM_CAMP_TIME 600 //10 minutes camping time
#define TEAM_PATROL_TIME 600 //10 minutes patrolling time
#define TEAM_LEAD_TIME 600 //10 minutes taking the lead
#define TEAM_GETITEM_TIME 60 //1 minute
#define TEAM_KILL_SOMEONE 180 //3 minute to kill someone
#define TEAM_ATTACKENEMYBASE_TIME 600 //10 minutes
#define TEAM_HARVEST_TIME 120 //2 minutes
#define CTF_GETFLAG_TIME 600 //10 minutes ctf get flag time
#define CTF_RUSHBASE_TIME 120 //2 minutes ctf rush base time
#define CTF_RETURNFLAG_TIME 180 //3 minutes to return the flag
#define CTF_ROAM_TIME 60 //1 minute ctf roam time
//Time for Double Domination tasks
#define DD_POINTA 600
#define DD_POINTB 600
//patrol flags
#define PATROL_LOOP 1
#define PATROL_REVERSE 2
#define PATROL_BACK 4
//teamplay task preference
#define TEAMTP_DEFENDER 1
#define TEAMTP_ATTACKER 2
//CTF strategy
#define CTFS_AGRESSIVE 1
//copied from the aas file header
#define PRESENCE_NONE 1
#define PRESENCE_NORMAL 2
#define PRESENCE_CROUCH 4
//
#define MAX_PROXMINES 64
//check points
typedef struct bot_waypoint_s
{
int inuse;
char name[32];
bot_goal_t goal;
struct bot_waypoint_s *next, *prev;
} bot_waypoint_t;
#define MAX_ACTIVATESTACK 8
#define MAX_ACTIVATEAREAS 32
typedef struct bot_activategoal_s
{
int inuse;
bot_goal_t goal; //goal to activate (buttons etc.)
float time; //time to activate something
float start_time; //time starting to activate something
float justused_time; //time the goal was used
int shoot; //true if bot has to shoot to activate
int weapon; //weapon to be used for activation
vec3_t target; //target to shoot at to activate something
vec3_t origin; //origin of the blocking entity to activate
int areas[MAX_ACTIVATEAREAS]; //routing areas disabled by blocking entity
int numareas; //number of disabled routing areas
int areasdisabled; //true if the areas are disabled for the routing
struct bot_activategoal_s *next; //next activate goal on stack
} bot_activategoal_t;
//bot state
typedef struct bot_state_s
{
int inuse; //true if this state is used by a bot client
int botthink_residual; //residual for the bot thinks
int client; //client number of the bot
int entitynum; //entity number of the bot
playerState_t cur_ps; //current player state
int last_eFlags; //last ps flags
usercmd_t lastucmd; //usercmd from last frame
int entityeventTime[1024]; //last entity event time
//
bot_settings_t settings; //several bot settings
int (*ainode)(struct bot_state_s *bs); //current AI node
float thinktime; //time the bot thinks this frame
vec3_t origin; //origin of the bot
vec3_t velocity; //velocity of the bot
int presencetype; //presence type of the bot
vec3_t eye; //eye coordinates of the bot
int areanum; //the number of the area the bot is in
int inventory[MAX_ITEMS]; //string with items amounts the bot has
int tfl; //the travel flags the bot uses
int flags; //several flags
int respawn_wait; //wait until respawned
int lasthealth; //health value previous frame
int lastkilledplayer; //last killed player
int lastkilledby; //player that last killed this bot
int botdeathtype; //the death type of the bot
int enemydeathtype; //the death type of the enemy
int botsuicide; //true when the bot suicides
int enemysuicide; //true when the enemy of the bot suicides
int setupcount; //true when the bot has just been setup
int map_restart; //true when the map is being restarted
int entergamechat; //true when the bot used an enter game chat
int num_deaths; //number of time this bot died
int num_kills; //number of kills of this bot
int revenge_enemy; //the revenge enemy
int revenge_kills; //number of kills the enemy made
int lastframe_health; //health value the last frame
int lasthitcount; //number of hits last frame
int chatto; //chat to all or team
float walker; //walker charactertic
float ltime; //local bot time
float entergame_time; //time the bot entered the game
float ltg_time; //long term goal time
float nbg_time; //nearby goal time
float respawn_time; //time the bot takes to respawn
float respawnchat_time; //time the bot started a chat during respawn
float chase_time; //time the bot will chase the enemy
float enemyvisible_time; //time the enemy was last visible
float check_time; //time to check for nearby items
float stand_time; //time the bot is standing still
float lastchat_time; //time the bot last selected a chat
float kamikaze_time; //time to check for kamikaze usage
float invulnerability_time; //time to check for invulnerability usage
float standfindenemy_time; //time to find enemy while standing
float attackstrafe_time; //time the bot is strafing in one dir
float attackcrouch_time; //time the bot will stop crouching
float attackchase_time; //time the bot chases during actual attack
float attackjump_time; //time the bot jumped during attack
float enemysight_time; //time before reacting to enemy
float enemydeath_time; //time the enemy died
float enemyposition_time; //time the position and velocity of the enemy were stored
float defendaway_time; //time away while defending
float defendaway_range; //max travel time away from defend area
float rushbaseaway_time; //time away from rushing to the base
float attackaway_time; //time away from attacking the enemy base
float harvestaway_time; //time away from harvesting
float ctfroam_time; //time the bot is roaming in ctf
float killedenemy_time; //time the bot killed the enemy
float arrive_time; //time arrived (at companion)
float lastair_time; //last time the bot had air
float teleport_time; //last time the bot teleported
float camp_time; //last time camped
float camp_range; //camp range
float weaponchange_time; //time the bot started changing weapons
float firethrottlewait_time; //amount of time to wait
float firethrottleshoot_time; //amount of time to shoot
float notblocked_time; //last time the bot was not blocked
float blockedbyavoidspot_time; //time blocked by an avoid spot
float predictobstacles_time; //last time the bot predicted obstacles
int predictobstacles_goalareanum; //last goal areanum the bot predicted obstacles for
vec3_t aimtarget;
vec3_t enemyvelocity; //enemy velocity 0.5 secs ago during battle
vec3_t enemyorigin; //enemy origin 0.5 secs ago during battle
//
int kamikazebody; //kamikaze body
int proxmines[MAX_PROXMINES];
int numproxmines;
//
int character; //the bot character
int ms; //move state of the bot
int gs; //goal state of the bot
int cs; //chat state of the bot
int ws; //weapon state of the bot
//
int enemy; //enemy entity number
int lastenemyareanum; //last reachability area the enemy was in
vec3_t lastenemyorigin; //last origin of the enemy in the reachability area
int weaponnum; //current weapon number
vec3_t viewangles; //current view angles
vec3_t ideal_viewangles; //ideal view angles
vec3_t viewanglespeed;
//
int ltgtype; //long term goal type
// team goals
int teammate; //team mate involved in this team goal
int decisionmaker; //player who decided to go for this goal
int ordered; //true if ordered to do something
float order_time; //time ordered to do something
int owndecision_time; //time the bot made it's own decision
bot_goal_t teamgoal; //the team goal
bot_goal_t altroutegoal; //alternative route goal
float reachedaltroutegoal_time; //time the bot reached the alt route goal
float teammessage_time; //time to message team mates what the bot is doing
float teamgoal_time; //time to stop helping team mate
float teammatevisible_time; //last time the team mate was NOT visible
int teamtaskpreference; //team task preference
// last ordered team goal
int lastgoal_decisionmaker;
int lastgoal_ltgtype;
int lastgoal_teammate;
bot_goal_t lastgoal_teamgoal;
// for leading team mates
int lead_teammate; //team mate the bot is leading
bot_goal_t lead_teamgoal; //team goal while leading
float lead_time; //time leading someone
float leadvisible_time; //last time the team mate was visible
float leadmessage_time; //last time a messaged was sent to the team mate
float leadbackup_time; //time backing up towards team mate
//
char teamleader[32]; //netname of the team leader
float askteamleader_time; //time asked for team leader
float becometeamleader_time; //time the bot will become the team leader
float teamgiveorders_time; //time to give team orders
float lastflagcapture_time; //last time a flag was captured
int numteammates; //number of team mates
int redflagstatus; //0 = at base, 1 = not at base
int blueflagstatus; //0 = at base, 1 = not at base
int neutralflagstatus; //0 = at base, 1 = our team has flag, 2 = enemy team has flag, 3 = enemy team dropped the flag
int flagstatuschanged; //flag status changed
int forceorders; //true if forced to give orders
int flagcarrier; //team mate carrying the enemy flag
int ctfstrategy; //ctf strategy
char subteam[32]; //sub team name
float formation_dist; //formation team mate intervening space
char formation_teammate[16]; //netname of the team mate the bot uses for relative positioning
float formation_angle; //angle relative to the formation team mate
vec3_t formation_dir; //the direction the formation is moving in
vec3_t formation_origin; //origin the bot uses for relative positioning
bot_goal_t formation_goal; //formation goal
bot_activategoal_t *activatestack; //first activate goal on the stack
bot_activategoal_t activategoalheap[MAX_ACTIVATESTACK]; //activate goal heap
bot_waypoint_t *checkpoints; //check points
bot_waypoint_t *patrolpoints; //patrol points
bot_waypoint_t *curpatrolpoint; //current patrol point the bot is going for
int patrolflags; //patrol flags
} bot_state_t;
//resets the whole bot state
void BotResetState(bot_state_t *bs);
//returns the number of bots in the game
int NumBots(void);
//returns info about the entity
void BotEntityInfo(int entnum, aas_entityinfo_t *info);
extern float floattime;
#define FloatTime() floattime
// from the game source
void QDECL BotAI_Print(int type, char *fmt, ...);
void QDECL QDECL BotAI_BotInitialChat( bot_state_t *bs, char *type, ... );
void BotAI_Trace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask);
int BotAI_GetClientState( int clientNum, playerState_t *state );
int BotAI_GetEntityState( int entityNum, entityState_t *state );
int BotAI_GetSnapshotEntity( int clientNum, int sequence, entityState_t *state );
int BotTeamLeader(bot_state_t *bs);

2277
code/game/ai_team.c Normal file

File diff suppressed because it is too large Load Diff

39
code/game/ai_team.h Normal file
View File

@@ -0,0 +1,39 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: ai_team.h
*
* desc: Quake3 bot AI
*
* $Archive: /source/code/botai/ai_chat.c $
*
*****************************************************************************/
void BotTeamAI(bot_state_t *bs);
int BotGetTeamMateTaskPreference(bot_state_t *bs, int teammate);
void BotSetTeamMateTaskPreference(bot_state_t *bs, int teammate, int preference);
void BotVoiceChat(bot_state_t *bs, int toclient, char *voicechat);
void BotVoiceChatOnly(bot_state_t *bs, int toclient, char *voicechat);

531
code/game/ai_vcmd.c Normal file
View File

@@ -0,0 +1,531 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: ai_vcmd.c
*
* desc: Quake3 bot AI
*
* $Archive: /MissionPack/code/game/ai_vcmd.c $
*
*****************************************************************************/
#include "g_local.h"
#include "../botlib/botlib.h"
#include "../botlib/be_aas.h"
#include "../botlib/be_ea.h"
#include "../botlib/be_ai_char.h"
#include "../botlib/be_ai_chat.h"
#include "../botlib/be_ai_gen.h"
#include "../botlib/be_ai_goal.h"
#include "../botlib/be_ai_move.h"
#include "../botlib/be_ai_weap.h"
//
#include "ai_main.h"
#include "ai_dmq3.h"
#include "ai_chat.h"
#include "ai_cmd.h"
#include "ai_dmnet.h"
#include "ai_team.h"
#include "ai_vcmd.h"
//
#include "chars.h" //characteristics
#include "inv.h" //indexes into the inventory
#include "syn.h" //synonyms
#include "match.h" //string matching types and vars
// for the voice chats
#include "../../ui/menudef.h"
typedef struct voiceCommand_s
{
char *cmd;
void (*func)(bot_state_t *bs, int client, int mode);
} voiceCommand_t;
/*
==================
BotVoiceChat_GetFlag
==================
*/
void BotVoiceChat_GetFlag(bot_state_t *bs, int client, int mode) {
//
if (gametype == GT_CTF || gametype == GT_CTF_ELIMINATION) {
if (!ctf_redflag.areanum || !ctf_blueflag.areanum)
return;
}
else if (gametype == GT_1FCTF) {
if (!ctf_neutralflag.areanum || !ctf_redflag.areanum || !ctf_blueflag.areanum)
return;
}
else {
return;
}
//
bs->decisionmaker = client;
bs->ordered = qtrue;
bs->order_time = FloatTime();
//set the time to send a message to the team mates
bs->teammessage_time = FloatTime() + 2 * random();
//set the ltg type
bs->ltgtype = LTG_GETFLAG;
//set the team goal time
bs->teamgoal_time = FloatTime() + CTF_GETFLAG_TIME;
// get an alternate route in ctf
if (gametype == GT_CTF || gametype == GT_CTF_ELIMINATION) {
//get an alternative route goal towards the enemy base
BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs));
}
//
BotSetTeamStatus(bs);
// remember last ordered task
BotRememberLastOrderedTask(bs);
#ifdef DEBUG
BotPrintTeamGoal(bs);
#endif //DEBUG
}
/*
==================
BotVoiceChat_Offense
==================
*/
void BotVoiceChat_Offense(bot_state_t *bs, int client, int mode) {
if ( gametype == GT_CTF || gametype == GT_CTF_ELIMINATION || gametype == GT_1FCTF ) {
BotVoiceChat_GetFlag(bs, client, mode);
return;
}
if (gametype == GT_HARVESTER) {
//
bs->decisionmaker = client;
bs->ordered = qtrue;
bs->order_time = FloatTime();
//set the time to send a message to the team mates
bs->teammessage_time = FloatTime() + 2 * random();
//set the ltg type
bs->ltgtype = LTG_HARVEST;
//set the team goal time
bs->teamgoal_time = FloatTime() + TEAM_HARVEST_TIME;
bs->harvestaway_time = 0;
//
BotSetTeamStatus(bs);
// remember last ordered task
BotRememberLastOrderedTask(bs);
}
else
{
//
bs->decisionmaker = client;
bs->ordered = qtrue;
bs->order_time = FloatTime();
//set the time to send a message to the team mates
bs->teammessage_time = FloatTime() + 2 * random();
//set the ltg type
bs->ltgtype = LTG_ATTACKENEMYBASE;
//set the team goal time
bs->teamgoal_time = FloatTime() + TEAM_ATTACKENEMYBASE_TIME;
bs->attackaway_time = 0;
//
BotSetTeamStatus(bs);
// remember last ordered task
BotRememberLastOrderedTask(bs);
}
#ifdef DEBUG
BotPrintTeamGoal(bs);
#endif //DEBUG
}
/*
==================
BotVoiceChat_Defend
==================
*/
void BotVoiceChat_Defend(bot_state_t *bs, int client, int mode) {
if ( gametype == GT_OBELISK || gametype == GT_HARVESTER) {
//
switch(BotTeam(bs)) {
case TEAM_RED: memcpy(&bs->teamgoal, &redobelisk, sizeof(bot_goal_t)); break;
case TEAM_BLUE: memcpy(&bs->teamgoal, &blueobelisk, sizeof(bot_goal_t)); break;
default: return;
}
}
else
if (gametype == GT_CTF || gametype == GT_CTF_ELIMINATION || gametype == GT_1FCTF ) {
//
switch(BotTeam(bs)) {
case TEAM_RED: memcpy(&bs->teamgoal, &ctf_redflag, sizeof(bot_goal_t)); break;
case TEAM_BLUE: memcpy(&bs->teamgoal, &ctf_blueflag, sizeof(bot_goal_t)); break;
default: return;
}
}
else {
return;
}
//
bs->decisionmaker = client;
bs->ordered = qtrue;
bs->order_time = FloatTime();
//set the time to send a message to the team mates
bs->teammessage_time = FloatTime() + 2 * random();
//set the ltg type
bs->ltgtype = LTG_DEFENDKEYAREA;
//get the team goal time
bs->teamgoal_time = FloatTime() + TEAM_DEFENDKEYAREA_TIME;
//away from defending
bs->defendaway_time = 0;
//
BotSetTeamStatus(bs);
// remember last ordered task
BotRememberLastOrderedTask(bs);
#ifdef DEBUG
BotPrintTeamGoal(bs);
#endif //DEBUG
}
/*
==================
BotVoiceChat_DefendFlag
==================
*/
void BotVoiceChat_DefendFlag(bot_state_t *bs, int client, int mode) {
BotVoiceChat_Defend(bs, client, mode);
}
/*
==================
BotVoiceChat_Patrol
==================
*/
void BotVoiceChat_Patrol(bot_state_t *bs, int client, int mode) {
//
bs->decisionmaker = client;
//
bs->ltgtype = 0;
bs->lead_time = 0;
bs->lastgoal_ltgtype = 0;
//
BotAI_BotInitialChat(bs, "dismissed", NULL);
trap_BotEnterChat(bs->cs, client, CHAT_TELL);
BotVoiceChatOnly(bs, -1, VOICECHAT_ONPATROL);
//
BotSetTeamStatus(bs);
#ifdef DEBUG
BotPrintTeamGoal(bs);
#endif //DEBUG
}
/*
==================
BotVoiceChat_Camp
==================
*/
void BotVoiceChat_Camp(bot_state_t *bs, int client, int mode) {
int areanum;
aas_entityinfo_t entinfo;
char netname[MAX_NETNAME];
//
bs->teamgoal.entitynum = -1;
BotEntityInfo(client, &entinfo);
//if info is valid (in PVS)
if (entinfo.valid) {
areanum = BotPointAreaNum(entinfo.origin);
if (areanum) { // && trap_AAS_AreaReachability(areanum)) {
//NOTE: just assume the bot knows where the person is
//if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, client)) {
bs->teamgoal.entitynum = client;
bs->teamgoal.areanum = areanum;
VectorCopy(entinfo.origin, bs->teamgoal.origin);
VectorSet(bs->teamgoal.mins, -8, -8, -8);
VectorSet(bs->teamgoal.maxs, 8, 8, 8);
//}
}
}
//if the other is not visible
if (bs->teamgoal.entitynum < 0) {
BotAI_BotInitialChat(bs, "whereareyou", EasyClientName(client, netname, sizeof(netname)), NULL);
trap_BotEnterChat(bs->cs, client, CHAT_TELL);
return;
}
//
bs->decisionmaker = client;
bs->ordered = qtrue;
bs->order_time = FloatTime();
//set the time to send a message to the team mates
bs->teammessage_time = FloatTime() + 2 * random();
//set the ltg type
bs->ltgtype = LTG_CAMPORDER;
//get the team goal time
bs->teamgoal_time = FloatTime() + TEAM_CAMP_TIME;
//the teammate that requested the camping
bs->teammate = client;
//not arrived yet
bs->arrive_time = 0;
//
BotSetTeamStatus(bs);
// remember last ordered task
BotRememberLastOrderedTask(bs);
#ifdef DEBUG
BotPrintTeamGoal(bs);
#endif //DEBUG
}
/*
==================
BotVoiceChat_FollowMe
==================
*/
void BotVoiceChat_FollowMe(bot_state_t *bs, int client, int mode) {
int areanum;
aas_entityinfo_t entinfo;
char netname[MAX_NETNAME];
bs->teamgoal.entitynum = -1;
BotEntityInfo(client, &entinfo);
//if info is valid (in PVS)
if (entinfo.valid) {
areanum = BotPointAreaNum(entinfo.origin);
if (areanum) { // && trap_AAS_AreaReachability(areanum)) {
bs->teamgoal.entitynum = client;
bs->teamgoal.areanum = areanum;
VectorCopy(entinfo.origin, bs->teamgoal.origin);
VectorSet(bs->teamgoal.mins, -8, -8, -8);
VectorSet(bs->teamgoal.maxs, 8, 8, 8);
}
}
//if the other is not visible
if (bs->teamgoal.entitynum < 0) {
BotAI_BotInitialChat(bs, "whereareyou", EasyClientName(client, netname, sizeof(netname)), NULL);
trap_BotEnterChat(bs->cs, client, CHAT_TELL);
return;
}
//
bs->decisionmaker = client;
bs->ordered = qtrue;
bs->order_time = FloatTime();
//the team mate
bs->teammate = client;
//last time the team mate was assumed visible
bs->teammatevisible_time = FloatTime();
//set the time to send a message to the team mates
bs->teammessage_time = FloatTime() + 2 * random();
//get the team goal time
bs->teamgoal_time = FloatTime() + TEAM_ACCOMPANY_TIME;
//set the ltg type
bs->ltgtype = LTG_TEAMACCOMPANY;
bs->formation_dist = 3.5 * 32; //3.5 meter
bs->arrive_time = 0;
//
BotSetTeamStatus(bs);
// remember last ordered task
BotRememberLastOrderedTask(bs);
#ifdef DEBUG
BotPrintTeamGoal(bs);
#endif //DEBUG
}
/*
==================
BotVoiceChat_FollowFlagCarrier
==================
*/
void BotVoiceChat_FollowFlagCarrier(bot_state_t *bs, int client, int mode) {
int carrier;
carrier = BotTeamFlagCarrier(bs);
if (carrier >= 0)
BotVoiceChat_FollowMe(bs, carrier, mode);
#ifdef DEBUG
BotPrintTeamGoal(bs);
#endif //DEBUG
}
/*
==================
BotVoiceChat_ReturnFlag
==================
*/
void BotVoiceChat_ReturnFlag(bot_state_t *bs, int client, int mode) {
//if not in CTF mode
if ( gametype != GT_CTF && gametype != GT_CTF_ELIMINATION && gametype != GT_1FCTF ) {
return;
}
//
bs->decisionmaker = client;
bs->ordered = qtrue;
bs->order_time = FloatTime();
//set the time to send a message to the team mates
bs->teammessage_time = FloatTime() + 2 * random();
//set the ltg type
bs->ltgtype = LTG_RETURNFLAG;
//set the team goal time
bs->teamgoal_time = FloatTime() + CTF_RETURNFLAG_TIME;
bs->rushbaseaway_time = 0;
BotSetTeamStatus(bs);
#ifdef DEBUG
BotPrintTeamGoal(bs);
#endif //DEBUG
}
/*
==================
BotVoiceChat_StartLeader
==================
*/
void BotVoiceChat_StartLeader(bot_state_t *bs, int client, int mode) {
ClientName(client, bs->teamleader, sizeof(bs->teamleader));
}
/*
==================
BotVoiceChat_StopLeader
==================
*/
void BotVoiceChat_StopLeader(bot_state_t *bs, int client, int mode) {
char netname[MAX_MESSAGE_SIZE];
if (!Q_stricmp(bs->teamleader, ClientName(client, netname, sizeof(netname)))) {
bs->teamleader[0] = '\0';
notleader[client] = qtrue;
}
}
/*
==================
BotVoiceChat_WhoIsLeader
==================
*/
void BotVoiceChat_WhoIsLeader(bot_state_t *bs, int client, int mode) {
char netname[MAX_MESSAGE_SIZE];
if (!TeamPlayIsOn()) return;
ClientName(bs->client, netname, sizeof(netname));
//if this bot IS the team leader
if (!Q_stricmp(netname, bs->teamleader)) {
BotAI_BotInitialChat(bs, "iamteamleader", NULL);
trap_BotEnterChat(bs->cs, 0, CHAT_TEAM);
BotVoiceChatOnly(bs, -1, VOICECHAT_STARTLEADER);
}
}
/*
==================
BotVoiceChat_WantOnDefense
==================
*/
void BotVoiceChat_WantOnDefense(bot_state_t *bs, int client, int mode) {
char netname[MAX_NETNAME];
int preference;
preference = BotGetTeamMateTaskPreference(bs, client);
preference &= ~TEAMTP_ATTACKER;
preference |= TEAMTP_DEFENDER;
BotSetTeamMateTaskPreference(bs, client, preference);
//
EasyClientName(client, netname, sizeof(netname));
BotAI_BotInitialChat(bs, "keepinmind", netname, NULL);
trap_BotEnterChat(bs->cs, client, CHAT_TELL);
BotVoiceChatOnly(bs, client, VOICECHAT_YES);
trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
}
/*
==================
BotVoiceChat_WantOnOffense
==================
*/
void BotVoiceChat_WantOnOffense(bot_state_t *bs, int client, int mode) {
char netname[MAX_NETNAME];
int preference;
preference = BotGetTeamMateTaskPreference(bs, client);
preference &= ~TEAMTP_DEFENDER;
preference |= TEAMTP_ATTACKER;
BotSetTeamMateTaskPreference(bs, client, preference);
//
EasyClientName(client, netname, sizeof(netname));
BotAI_BotInitialChat(bs, "keepinmind", netname, NULL);
trap_BotEnterChat(bs->cs, client, CHAT_TELL);
BotVoiceChatOnly(bs, client, VOICECHAT_YES);
trap_EA_Action(bs->client, ACTION_AFFIRMATIVE);
}
void BotVoiceChat_Dummy(bot_state_t *bs, int client, int mode) {
}
voiceCommand_t voiceCommands[] = {
{VOICECHAT_GETFLAG, BotVoiceChat_GetFlag},
{VOICECHAT_OFFENSE, BotVoiceChat_Offense },
{VOICECHAT_DEFEND, BotVoiceChat_Defend },
{VOICECHAT_DEFENDFLAG, BotVoiceChat_DefendFlag },
{VOICECHAT_PATROL, BotVoiceChat_Patrol },
{VOICECHAT_CAMP, BotVoiceChat_Camp },
{VOICECHAT_FOLLOWME, BotVoiceChat_FollowMe },
{VOICECHAT_FOLLOWFLAGCARRIER, BotVoiceChat_FollowFlagCarrier },
{VOICECHAT_RETURNFLAG, BotVoiceChat_ReturnFlag },
{VOICECHAT_STARTLEADER, BotVoiceChat_StartLeader },
{VOICECHAT_STOPLEADER, BotVoiceChat_StopLeader },
{VOICECHAT_WHOISLEADER, BotVoiceChat_WhoIsLeader },
{VOICECHAT_WANTONDEFENSE, BotVoiceChat_WantOnDefense },
{VOICECHAT_WANTONOFFENSE, BotVoiceChat_WantOnOffense },
{NULL, BotVoiceChat_Dummy}
};
int BotVoiceChatCommand(bot_state_t *bs, int mode, char *voiceChat) {
int i, voiceOnly, clientNum, color;
char *ptr, buf[MAX_MESSAGE_SIZE], *cmd;
if (!TeamPlayIsOn()) {
return qfalse;
}
if ( mode == SAY_ALL ) {
return qfalse; // don't do anything with voice chats to everyone
}
Q_strncpyz(buf, voiceChat, sizeof(buf));
cmd = buf;
for (ptr = cmd; *cmd && *cmd > ' '; cmd++);
while (*cmd && *cmd <= ' ') *cmd++ = '\0';
voiceOnly = atoi(ptr);
for (ptr = cmd; *cmd && *cmd > ' '; cmd++);
while (*cmd && *cmd <= ' ') *cmd++ = '\0';
clientNum = atoi(ptr);
for (ptr = cmd; *cmd && *cmd > ' '; cmd++);
while (*cmd && *cmd <= ' ') *cmd++ = '\0';
color = atoi(ptr);
if (!BotSameTeam(bs, clientNum)) {
return qfalse;
}
for (i = 0; voiceCommands[i].cmd; i++) {
if (!Q_stricmp(cmd, voiceCommands[i].cmd)) {
voiceCommands[i].func(bs, clientNum, mode);
return qtrue;
}
}
return qfalse;
}

36
code/game/ai_vcmd.h Normal file
View File

@@ -0,0 +1,36 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
/*****************************************************************************
* name: ai_vcmd.h
*
* desc: Quake3 bot AI
*
* $Archive: /source/code/botai/ai_vcmd.c $
*
*****************************************************************************/
int BotVoiceChatCommand(bot_state_t *bs, int mode, char *voicechat);
void BotVoiceChat_Defend(bot_state_t *bs, int client, int mode);

217
code/game/bg_alloc.c Normal file
View File

@@ -0,0 +1,217 @@
//KK-OAX
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
Copyright (C) 2000-2006 Tim Angus
This file is part of the Open Arena source code.
Copied from Tremulous under GPL version 2 including any later version.
Open Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Open Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Open Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "../qcommon/q_shared.h"
#include "bg_public.h"
#include "g_local.h"
#ifdef GAME
# define POOLSIZE ( 1024 * 1024 )
#else
# define POOLSIZE ( 256 * 1024 )
#endif
#define FREEMEMCOOKIE ((int)0xDEADBE3F) // Any unlikely to be used value
#define ROUNDBITS (unsigned int)31 // Round to 32 bytes
typedef struct freeMemNode_s
{
// Size of ROUNDBITS
int cookie, size; // Size includes node (obviously)
struct freeMemNode_s *prev, *next;
} freeMemNode_t;
static char memoryPool[POOLSIZE];
static freeMemNode_t *freeHead;
static int freeMem;
/*
* Returns qtrue if BG_Alloc will succeed, qfalse otherwise
*/
qboolean BG_CanAlloc( unsigned int size) {
freeMemNode_t *fmn;
int allocsize = ( size + sizeof(int) + ROUNDBITS ) & ~ROUNDBITS; // Round to 32-byte boundary
for( fmn = freeHead; fmn; fmn = fmn->next ) {
if( fmn->cookie != FREEMEMCOOKIE ) {
//Memory curroption
return qfalse;
}
if( fmn->size >= allocsize ) {
//At least one useable block
return qtrue;
}
}
return qfalse;
}
void *BG_Alloc( unsigned int size ) {
// Find a free block and allocate.
// Does two passes, attempts to fill same-sized free slot first.
freeMemNode_t *fmn, *prev, *next, *smallest;
int allocsize, smallestsize;
char *endptr;
int *ptr;
allocsize = ( size + sizeof(int) + ROUNDBITS ) & ~ROUNDBITS; // Round to 32-byte boundary
ptr = NULL;
smallest = NULL;
smallestsize = POOLSIZE + 1; // Guaranteed not to miss any slots :)
for( fmn = freeHead; fmn; fmn = fmn->next ) {
if( fmn->cookie != FREEMEMCOOKIE )
Com_Error( ERR_DROP, "BG_Alloc: Memory corruption detected!\n" );
if( fmn->size >= allocsize ) {
// We've got a block
if( fmn->size == allocsize ) {
// Same size, just remove
prev = fmn->prev;
next = fmn->next;
if( prev )
prev->next = next; // Point previous node to next
if( next )
next->prev = prev; // Point next node to previous
if( fmn == freeHead )
freeHead = next; // Set head pointer to next
ptr = (int *) fmn;
break; // Stop the loop, this is fine
} else {
// Keep track of the smallest free slot
if( fmn->size < smallestsize ) {
smallest = fmn;
smallestsize = fmn->size;
}
}
}
}
if( !ptr && smallest ) {
// We found a slot big enough
smallest->size -= allocsize;
endptr = (char *) smallest + smallest->size;
ptr = (int *) endptr;
}
if( ptr ) {
freeMem -= allocsize;
memset( ptr, 0, allocsize );
*ptr++ = allocsize; // Store a copy of size for deallocation
return( (void *) ptr );
}
Com_Error( ERR_DROP, "BG_Alloc: failed on allocation of %i bytes\n", size );
return( NULL );
}
void BG_Free( void *ptr ) {
// Release allocated memory, add it to the free list.
freeMemNode_t *fmn;
char *freeend;
int *freeptr;
freeptr = ptr;
freeptr--;
freeMem += *freeptr;
for( fmn = freeHead; fmn; fmn = fmn->next ) {
freeend = ((char *) fmn) + fmn->size;
if( freeend == (char *) freeptr ) {
// Released block can be merged to an existing node
fmn->size += *freeptr; // Add size of node.
return;
}
}
// No merging, add to head of list
fmn = (freeMemNode_t *) freeptr;
fmn->size = *freeptr; // Set this first to avoid corrupting *freeptr
fmn->cookie = FREEMEMCOOKIE;
fmn->prev = NULL;
fmn->next = freeHead;
freeHead->prev = fmn;
freeHead = fmn;
}
void BG_InitMemory( void ) {
// Set up the initial node
freeHead = (freeMemNode_t *)memoryPool;
freeHead->cookie = FREEMEMCOOKIE;
freeHead->size = POOLSIZE;
freeHead->next = NULL;
freeHead->prev = NULL;
freeMem = sizeof( memoryPool );
}
void BG_DefragmentMemory( void ) {
// If there's a frenzy of deallocation and we want to
// allocate something big, this is useful. Otherwise...
// not much use.
freeMemNode_t *startfmn, *endfmn, *fmn;
for( startfmn = freeHead; startfmn; ) {
endfmn = (freeMemNode_t *)(((char *) startfmn) + startfmn->size);
for( fmn = freeHead; fmn; ) {
if( fmn->cookie != FREEMEMCOOKIE )
Com_Error( ERR_DROP, "BG_DefragmentMemory: Memory corruption detected!\n" );
if( fmn == endfmn ) {
// We can add fmn onto startfmn.
if( fmn->prev )
fmn->prev->next = fmn->next;
if( fmn->next ) {
if( !(fmn->next->prev = fmn->prev) )
freeHead = fmn->next; // We're removing the head node
}
startfmn->size += fmn->size;
memset( fmn, 0, sizeof(freeMemNode_t) ); // A redundant call, really.
startfmn = freeHead;
endfmn = fmn = NULL; // Break out of current loop
}
else
fmn = fmn->next;
}
if( endfmn )
startfmn = startfmn->next; // endfmn acts as a 'restart' flag here
}
}
//KK-OAX This was moved from g_mem.c to keep functionality from being broken.
void Svcmd_GameMem_f( void ) {
int usedMem;
usedMem = POOLSIZE - freeMem;
G_Printf( "Game memory status: %i out of %i bytes allocated\n", usedMem, POOLSIZE );
}

2154
code/game/bg_lib.c Normal file

File diff suppressed because it is too large Load Diff

126
code/game/bg_lib.h Normal file
View File

@@ -0,0 +1,126 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// bg_lib.h -- standard C library replacement routines used by code
// compiled for the virtual machine
// This file is NOT included on native builds
#if !defined( BG_LIB_H ) && defined( Q3_VM )
#define BG_LIB_H
//Ignore __attribute__ on non-gcc platforms
#ifndef __GNUC__
#ifndef __attribute__
#define __attribute__(x)
#endif
#endif
#ifndef NULL
#define NULL ((void *)0)
#endif
typedef int size_t;
typedef char * va_list;
#define _INTSIZEOF(n) ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) )
#define va_start(ap,v) ( ap = (va_list)&v + _INTSIZEOF(v) )
#define va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) )
#define va_end(ap) ( ap = (va_list)0 )
#define CHAR_BIT 8 /* number of bits in a char */
#define SCHAR_MAX 0x7f /* maximum signed char value */
#define SCHAR_MIN (-SCHAR_MAX - 1) /* minimum signed char value */
#define UCHAR_MAX 0xff /* maximum unsigned char value */
#define SHRT_MAX 0x7fff /* maximum (signed) short value */
#define SHRT_MIN (-SHRT_MAX - 1) /* minimum (signed) short value */
#define USHRT_MAX 0xffff /* maximum unsigned short value */
#define INT_MAX 0x7fffffff /* maximum (signed) int value */
#define INT_MIN (-INT_MAX - 1) /* minimum (signed) int value */
#define UINT_MAX 0xffffffff /* maximum unsigned int value */
#define LONG_MAX 0x7fffffffL /* maximum (signed) long value */
#define LONG_MIN (-LONG_MAX - 1) /* minimum (signed) long value */
#define ULONG_MAX 0xffffffffUL /* maximum unsigned long value */
#define isalnum(c) (isalpha(c) || isdigit(c))
#define isalpha(c) (isupper(c) || islower(c))
#define isascii(c) ((c) > 0 && (c) <= 0x7f)
#define iscntrl(c) (((c) >= 0) && (((c) <= 0x1f) || ((c) == 0x7f)))
#define isdigit(c) ((c) >= '0' && (c) <= '9')
#define isgraph(c) ((c) != ' ' && isprint(c))
#define islower(c) ((c) >= 'a' && (c) <= 'z')
#define isprint(c) ((c) >= ' ' && (c) <= '~')
#define ispunct(c) (((c) > ' ' && (c) <= '~') && !isalnum(c))
#define isspace(c) ((c) == ' ' || (c) == '\f' || (c) == '\n' || (c) == '\r' || \
(c) == '\t' || (c) == '\v')
#define isupper(c) ((c) >= 'A' && (c) <= 'Z')
#define isxdigit(c) (isxupper(c) || isxlower(c))
#define isxlower(c) (isdigit(c) || (c >= 'a' && c <= 'f'))
#define isxupper(c) (isdigit(c) || (c >= 'A' && c <= 'F'))
// Misc functions
typedef int cmp_t(const void *, const void *);
void qsort(void *a, size_t n, size_t es, cmp_t *cmp);
void srand( unsigned seed );
int rand( void );
// String functions
size_t strlen( const char *string );
char *strcat( char *strDestination, const char *strSource );
char *strcpy( char *strDestination, const char *strSource );
int strcmp( const char *string1, const char *string2 );
char *strchr( const char *string, int c );
char *strrchr(const char *string, int c);
char *strstr( const char *string, const char *strCharSet );
char *strncpy( char *strDest, const char *strSource, size_t count );
int tolower( int c );
int toupper( int c );
double atof( const char *string );
double _atof( const char **stringPtr );
double strtod( const char *nptr, const char **endptr );
int atoi( const char *string );
int _atoi( const char **stringPtr );
long strtol( const char *nptr, const char **endptr, int base );
int Q_vsnprintf( char *buffer, size_t length, const char *fmt, va_list argptr );
int Q_snprintf( char *buffer, size_t length, const char *fmt, ... ) __attribute__ ((format (printf, 3, 4)));
int sscanf( const char *buffer, const char *fmt, ... ) __attribute__ ((format (scanf, 2, 3)));
// Memory functions
void *memmove( void *dest, const void *src, size_t count );
void *memset( void *dest, int c, size_t count );
void *memcpy( void *dest, const void *src, size_t count );
// Math functions
double ceil( double x );
double floor( double x );
double sqrt( double x );
double sin( double x );
double cos( double x );
double atan2( double y, double x );
double tan( double x );
int abs( int n );
double fabs( double x );
double acos( double x );
#endif // BG_LIB_H

83
code/game/bg_local.h Normal file
View File

@@ -0,0 +1,83 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// bg_local.h -- local definitions for the bg (both games) files
#define MIN_WALK_NORMAL 0.7f // can't walk on very steep slopes
#define STEPSIZE 18
#define JUMP_VELOCITY 270
#define TIMER_LAND 130
#define TIMER_GESTURE (34*66+50)
#define OVERCLIP 1.001f
// all of the locals will be zeroed before each
// pmove, just to make damn sure we don't have
// any differences when running on client or server
typedef struct {
vec3_t forward, right, up;
float frametime;
int msec;
qboolean walking;
qboolean groundPlane;
trace_t groundTrace;
float impactSpeed;
vec3_t previous_origin;
vec3_t previous_velocity;
int previous_waterlevel;
} pml_t;
extern pmove_t *pm;
extern pml_t pml;
// movement parameters
extern float pm_stopspeed;
extern float pm_duckScale;
extern float pm_swimScale;
extern float pm_wadeScale;
extern float pm_accelerate;
extern float pm_airaccelerate;
extern float pm_wateraccelerate;
extern float pm_flyaccelerate;
extern float pm_friction;
extern float pm_waterfriction;
extern float pm_flightfriction;
extern int c_pmove;
void PM_ClipVelocity( vec3_t in, vec3_t normal, vec3_t out, float overbounce );
void PM_AddTouchEnt( int entityNum );
void PM_AddEvent( int newEvent );
qboolean PM_SlideMove( qboolean gravity );
void PM_StepSlideMove( qboolean gravity );

1787
code/game/bg_misc.c Normal file

File diff suppressed because it is too large Load Diff

2085
code/game/bg_pmove.c Normal file

File diff suppressed because it is too large Load Diff

825
code/game/bg_public.h Normal file
View File

@@ -0,0 +1,825 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// bg_public.h -- definitions shared by both the server game and client game modules
// because games can change separately from the main system version, we need a
// second version that must match between game and cgame
#if defined(BG_PUBLIC_H)
#else
#define BG_PUBLIC_H 1
#define GAME_VERSION BASEGAME "-1"
#define DEFAULT_GRAVITY 800
#define GIB_HEALTH -40
#define ARMOR_PROTECTION 0.66
#define MAX_ITEMS 256
#define RANK_TIED_FLAG 0x4000
#define DEFAULT_SHOTGUN_SPREAD 700
#define DEFAULT_SHOTGUN_COUNT 11
#define ITEM_RADIUS 15 // item sizes are needed for client side pickup detection
#define LIGHTNING_RANGE 768
#define SCORE_NOT_PRESENT -9999 // for the CS_SCORES[12] when only one player is present
#define VOTE_TIME 30000 // 30 seconds before vote times out
#define MINS_Z -24
#define DEFAULT_VIEWHEIGHT 26
#define CROUCH_VIEWHEIGHT 12
#define DEAD_VIEWHEIGHT -16
//Domination points
#define MAX_DOMINATION_POINTS 6
#define MAX_DOMINATION_POINTS_NAMES 20
//
// config strings are a general means of communicating variable length strings
// from the server to all connected clients.
//
// CS_SERVERINFO and CS_SYSTEMINFO are defined in q_shared.h
#define CS_MUSIC 2
#define CS_MESSAGE 3 // from the map worldspawn's message field
#define CS_MOTD 4 // g_motd string for server message of the day
#define CS_WARMUP 5 // server time when the match will be restarted
#define CS_SCORES1 6
#define CS_SCORES2 7
#define CS_VOTE_TIME 8
#define CS_VOTE_STRING 9
#define CS_VOTE_YES 10
#define CS_VOTE_NO 11
#define CS_TEAMVOTE_TIME 12
#define CS_TEAMVOTE_STRING 14
#define CS_TEAMVOTE_YES 16
#define CS_TEAMVOTE_NO 18
#define CS_GAME_VERSION 20
#define CS_LEVEL_START_TIME 21 // so the timer only shows the current level
#define CS_INTERMISSION 22 // when 1, fraglimit/timelimit has been hit and intermission will start in a second or two
#define CS_FLAGSTATUS 23 // string indicating flag status in CTF
#define CS_SHADERSTATE 24
#define CS_BOTINFO 25
#define CS_ITEMS 27 // string of 0's and 1's that tell which items are present
#define CS_MODELS 32
#define CS_SOUNDS (CS_MODELS+MAX_MODELS)
#define CS_PLAYERS (CS_SOUNDS+MAX_SOUNDS)
#define CS_LOCATIONS (CS_PLAYERS+MAX_CLIENTS)
#define CS_PARTICLES (CS_LOCATIONS+MAX_LOCATIONS)
#define CS_MAX (CS_PARTICLES+MAX_LOCATIONS)
#if (CS_MAX) > MAX_CONFIGSTRINGS
#error overflow: (CS_MAX) > MAX_CONFIGSTRINGS
#endif
typedef enum {
GT_FFA, // free for all
GT_TOURNAMENT, // one on one tournament
GT_SINGLE_PLAYER, // single player ffa
//-- team games go after this --
GT_TEAM, // team deathmatch
//-- team games that uses bases go after this
GT_CTF, // capture the flag
GT_1FCTF,
GT_OBELISK,
GT_HARVESTER,
//-- custom game types, there will be a variable in
GT_ELIMINATION, // team elimination (custom)
GT_CTF_ELIMINATION, // ctf elimination
GT_LMS, // Last man standing
GT_DOUBLE_D, // Double Domination
GT_DOMINATION, // Standard domination 12
GT_MAX_GAME_TYPE
} gametype_t;
typedef enum { GENDER_MALE, GENDER_FEMALE, GENDER_NEUTER } gender_t;
/*
===================================================================================
PMOVE MODULE
The pmove code takes a player_state_t and a usercmd_t and generates a new player_state_t
and some other output data. Used for local prediction on the client game and true
movement on the server game.
===================================================================================
*/
typedef enum {
PM_NORMAL, // can accelerate and turn
PM_NOCLIP, // noclip movement
PM_SPECTATOR, // still run into walls
PM_DEAD, // no acceleration or turning, but free falling
PM_FREEZE, // stuck in place with no control
PM_INTERMISSION, // no movement or status bar
PM_SPINTERMISSION // no movement or status bar
} pmtype_t;
typedef enum {
WEAPON_READY,
WEAPON_RAISING,
WEAPON_DROPPING,
WEAPON_FIRING
} weaponstate_t;
// pmove->pm_flags
#define PMF_DUCKED 1
#define PMF_JUMP_HELD 2
#define PMF_BACKWARDS_JUMP 8 // go into backwards land
#define PMF_BACKWARDS_RUN 16 // coast down to backwards run
#define PMF_TIME_LAND 32 // pm_time is time before rejump
#define PMF_TIME_KNOCKBACK 64 // pm_time is an air-accelerate only time
#define PMF_TIME_WATERJUMP 256 // pm_time is waterjump
#define PMF_RESPAWNED 512 // clear after attack and jump buttons come up
#define PMF_USE_ITEM_HELD 1024
#define PMF_GRAPPLE_PULL 2048 // pull towards grapple location
#define PMF_FOLLOW 4096 // spectate following another player
#define PMF_SCOREBOARD 8192 // spectate as a scoreboard
#define PMF_INVULEXPAND 16384 // invulnerability sphere set to full size
//Elimination players cannot fire in warmup
#define PMF_ELIMWARMUP 32768 //I hope this is more than 16 signed bits! (it's not but it just works anyway...)
//Don't add anymore, I have already set the sign bit :-(
#define PMF_ALL_TIMES (PMF_TIME_WATERJUMP|PMF_TIME_LAND|PMF_TIME_KNOCKBACK)
#define MAXTOUCH 32
typedef struct {
// state (in / out)
playerState_t *ps;
// command (in)
usercmd_t cmd;
int tracemask; // collide against these types of surfaces
int debugLevel; // if set, diagnostic output will be printed
qboolean noFootsteps; // if the game is setup for no footsteps by the server
qboolean gauntletHit; // true if a gauntlet attack would actually hit something
int framecount;
// results (out)
int numtouch;
int touchents[MAXTOUCH];
vec3_t mins, maxs; // bounding box size
int watertype;
int waterlevel;
float xyspeed;
// for fixed msec Pmove
int pmove_fixed;
int pmove_msec;
//Sago's pmove
int pmove_float;
//Flags effecting movement (see dmflags)
int pmove_flags;
// callbacks to test the world
// these will be different functions during game and cgame
void (*trace)( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentMask );
int (*pointcontents)( const vec3_t point, int passEntityNum );
} pmove_t;
// if a full pmove isn't done on the client, you can just update the angles
void PM_UpdateViewAngles( playerState_t *ps, const usercmd_t *cmd );
void Pmove (pmove_t *pmove);
//===================================================================================
// player_state->stats[] indexes
// NOTE: may not have more than 16
typedef enum {
STAT_HEALTH,
STAT_HOLDABLE_ITEM,
STAT_PERSISTANT_POWERUP,
STAT_WEAPONS, // 16 bit fields
STAT_ARMOR,
STAT_DEAD_YAW, // look this direction when dead (FIXME: get rid of?)
STAT_CLIENTS_READY, // bit mask of clients wishing to exit the intermission (FIXME: configstring?)
STAT_MAX_HEALTH // health / armor limit, changable by handicap
} statIndex_t;
// player_state->persistant[] indexes
// these fields are the only part of player_state that isn't
// cleared on respawn
// NOTE: may not have more than 16
typedef enum {
PERS_SCORE, // !!! MUST NOT CHANGE, SERVER AND GAME BOTH REFERENCE !!!
PERS_HITS, // total points damage inflicted so damage beeps can sound on change
PERS_RANK, // player rank or team rank
PERS_TEAM, // player team
PERS_SPAWN_COUNT, // incremented every respawn
PERS_PLAYEREVENTS, // 16 bits that can be flipped for events
PERS_ATTACKER, // clientnum of last damage inflicter
PERS_ATTACKEE_ARMOR, // health/armor of last person we attacked
PERS_KILLED, // count of the number of times you died
// player awards tracking
PERS_IMPRESSIVE_COUNT, // two railgun hits in a row
PERS_EXCELLENT_COUNT, // two successive kills in a short amount of time
PERS_DEFEND_COUNT, // defend awards
PERS_ASSIST_COUNT, // assist awards
PERS_GAUNTLET_FRAG_COUNT, // kills with the guantlet
PERS_CAPTURES // captures
} persEnum_t;
// entityState_t->eFlags
#define EF_DEAD 0x00000001 // don't draw a foe marker over players with EF_DEAD
#define EF_TICKING 0x00000002 // used to make players play the prox mine ticking sound
#define EF_TELEPORT_BIT 0x00000004 // toggled every time the origin abruptly changes
#define EF_AWARD_EXCELLENT 0x00000008 // draw an excellent sprite
#define EF_PLAYER_EVENT 0x00000010
#define EF_BOUNCE 0x00000010 // for missiles
#define EF_BOUNCE_HALF 0x00000020 // for missiles
#define EF_AWARD_GAUNTLET 0x00000040 // draw a gauntlet sprite
#define EF_NODRAW 0x00000080 // may have an event, but no model (unspawned items)
#define EF_FIRING 0x00000100 // for lightning gun
#define EF_KAMIKAZE 0x00000200
#define EF_MOVER_STOP 0x00000400 // will push otherwise
#define EF_AWARD_CAP 0x00000800 // draw the capture sprite
#define EF_TALK 0x00001000 // draw a talk balloon
#define EF_CONNECTION 0x00002000 // draw a connection trouble sprite
#define EF_VOTED 0x00004000 // already cast a vote
#define EF_AWARD_IMPRESSIVE 0x00008000 // draw an impressive sprite
#define EF_AWARD_DEFEND 0x00010000 // draw a defend sprite
#define EF_AWARD_ASSIST 0x00020000 // draw a assist sprite
#define EF_AWARD_DENIED 0x00040000 // denied
#define EF_TEAMVOTED 0x00080000 // already cast a team vote
// NOTE: may not have more than 16
typedef enum {
PW_NONE,
PW_QUAD,
PW_BATTLESUIT,
PW_HASTE,
PW_INVIS,
PW_REGEN,
PW_FLIGHT,
PW_REDFLAG,
PW_BLUEFLAG,
PW_NEUTRALFLAG,
PW_SCOUT,
PW_GUARD,
PW_DOUBLER,
PW_AMMOREGEN,
PW_INVULNERABILITY,
PW_NUM_POWERUPS
} powerup_t;
typedef enum {
HI_NONE,
HI_TELEPORTER,
HI_MEDKIT,
HI_KAMIKAZE,
HI_PORTAL,
HI_INVULNERABILITY,
HI_NUM_HOLDABLE
} holdable_t;
typedef enum {
DD_NONE,
DD_POINTARED,
DD_POINTABLUE,
DD_POINTAWHITE,
DD_POINTBRED,
DD_POINTBBLUE,
DD_POINTBWHITE
} doubled_t;
typedef enum {
DOM_NONE,
DOM_POINTRED,
DOM_POINTBLUE,
DOM_POINTWHITE,
} domination_t;
typedef enum {
WP_NONE,
WP_GAUNTLET,
WP_MACHINEGUN,
WP_SHOTGUN,
WP_GRENADE_LAUNCHER,
WP_ROCKET_LAUNCHER,
WP_LIGHTNING,
WP_RAILGUN,
WP_PLASMAGUN,
WP_BFG,
WP_GRAPPLING_HOOK,
WP_NAILGUN,
WP_PROX_LAUNCHER,
WP_CHAINGUN,
WP_NUM_WEAPONS
} weapon_t;
// reward sounds (stored in ps->persistant[PERS_PLAYEREVENTS])
#define PLAYEREVENT_DENIEDREWARD 0x0001
#define PLAYEREVENT_GAUNTLETREWARD 0x0002
#define PLAYEREVENT_HOLYSHIT 0x0004
// entityState_t->event values
// entity events are for effects that take place reletive
// to an existing entities origin. Very network efficient.
// two bits at the top of the entityState->event field
// will be incremented with each change in the event so
// that an identical event started twice in a row can
// be distinguished. And off the value with ~EV_EVENT_BITS
// to retrieve the actual event number
#define EV_EVENT_BIT1 0x00000100
#define EV_EVENT_BIT2 0x00000200
#define EV_EVENT_BITS (EV_EVENT_BIT1|EV_EVENT_BIT2)
#define EVENT_VALID_MSEC 300
typedef enum {
EV_NONE,
EV_FOOTSTEP,
EV_FOOTSTEP_METAL,
EV_FOOTSPLASH,
EV_FOOTWADE,
EV_SWIM,
EV_STEP_4,
EV_STEP_8,
EV_STEP_12,
EV_STEP_16,
EV_FALL_SHORT,
EV_FALL_MEDIUM,
EV_FALL_FAR,
EV_JUMP_PAD, // boing sound at origin, jump sound on player
EV_JUMP, //Event 14
EV_WATER_TOUCH, // foot touches
EV_WATER_LEAVE, // foot leaves
EV_WATER_UNDER, // head touches
EV_WATER_CLEAR, // head leaves
EV_ITEM_PICKUP, // normal item pickups are predictable
EV_GLOBAL_ITEM_PICKUP, // powerup / team sounds are broadcast to everyone
EV_NOAMMO,
EV_CHANGE_WEAPON,
EV_FIRE_WEAPON,
EV_USE_ITEM0, //Event 24
EV_USE_ITEM1,
EV_USE_ITEM2,
EV_USE_ITEM3,
EV_USE_ITEM4,
EV_USE_ITEM5,
EV_USE_ITEM6,
EV_USE_ITEM7,
EV_USE_ITEM8,
EV_USE_ITEM9,
EV_USE_ITEM10,
EV_USE_ITEM11,
EV_USE_ITEM12,
EV_USE_ITEM13,
EV_USE_ITEM14,
EV_USE_ITEM15,
EV_ITEM_RESPAWN, //Event 40
EV_ITEM_POP,
EV_PLAYER_TELEPORT_IN,
EV_PLAYER_TELEPORT_OUT,
EV_GRENADE_BOUNCE, // eventParm will be the soundindex
EV_GENERAL_SOUND,
EV_GLOBAL_SOUND, // no attenuation
EV_GLOBAL_TEAM_SOUND,
EV_BULLET_HIT_FLESH,
EV_BULLET_HIT_WALL,
EV_MISSILE_HIT, //Event 50
EV_MISSILE_MISS,
EV_MISSILE_MISS_METAL,
EV_RAILTRAIL,
EV_SHOTGUN,
EV_BULLET, // otherEntity is the shooter
EV_PAIN,
EV_DEATH1,
EV_DEATH2,
EV_DEATH3,
EV_OBITUARY, //Event 60
EV_POWERUP_QUAD,
EV_POWERUP_BATTLESUIT,
EV_POWERUP_REGEN,
EV_GIB_PLAYER, // gib a previously living player
EV_SCOREPLUM, // score plum
EV_PROXIMITY_MINE_STICK,
EV_PROXIMITY_MINE_TRIGGER,
EV_KAMIKAZE, // kamikaze explodes
EV_OBELISKEXPLODE, // obelisk explodes
EV_OBELISKPAIN, // obelisk is in pain
EV_INVUL_IMPACT, // invulnerability sphere impact
EV_JUICED, // invulnerability juiced effect
EV_LIGHTNINGBOLT, // lightning bolt bounced of invulnerability sphere
EV_DEBUG_LINE,
EV_STOPLOOPINGSOUND,
EV_TAUNT,
EV_TAUNT_YES,
EV_TAUNT_NO,
EV_TAUNT_FOLLOWME,
EV_TAUNT_GETFLAG,
EV_TAUNT_GUARDBASE,
EV_TAUNT_PATROL
} entity_event_t;
typedef enum {
GTS_RED_CAPTURE,
GTS_BLUE_CAPTURE,
GTS_RED_RETURN,
GTS_BLUE_RETURN,
GTS_RED_TAKEN,
GTS_BLUE_TAKEN,
GTS_REDOBELISK_ATTACKED,
GTS_BLUEOBELISK_ATTACKED,
GTS_REDTEAM_SCORED,
GTS_BLUETEAM_SCORED,
GTS_REDTEAM_TOOK_LEAD,
GTS_BLUETEAM_TOOK_LEAD,
GTS_TEAMS_ARE_TIED,
GTS_KAMIKAZE
} global_team_sound_t;
// animations
typedef enum {
BOTH_DEATH1,
BOTH_DEAD1,
BOTH_DEATH2,
BOTH_DEAD2,
BOTH_DEATH3,
BOTH_DEAD3,
TORSO_GESTURE,
TORSO_ATTACK,
TORSO_ATTACK2,
TORSO_DROP,
TORSO_RAISE,
TORSO_STAND,
TORSO_STAND2,
LEGS_WALKCR,
LEGS_WALK,
LEGS_RUN,
LEGS_BACK,
LEGS_SWIM,
LEGS_JUMP,
LEGS_LAND,
LEGS_JUMPB,
LEGS_LANDB,
LEGS_IDLE,
LEGS_IDLECR,
LEGS_TURN,
TORSO_GETFLAG,
TORSO_GUARDBASE,
TORSO_PATROL,
TORSO_FOLLOWME,
TORSO_AFFIRMATIVE,
TORSO_NEGATIVE,
// BOTH_POSE, // leilei - crappy ui posing code trying
MAX_ANIMATIONS,
LEGS_BACKCR,
LEGS_BACKWALK,
FLAG_RUN,
FLAG_STAND,
FLAG_STAND2RUN,
MAX_TOTALANIMATIONS
} animNumber_t;
typedef struct animation_s {
int firstFrame;
int numFrames;
int loopFrames; // 0 to numFrames
int frameLerp; // msec between frames
int initialLerp; // msec to get to first frame
int reversed; // true if animation is reversed
int flipflop; // true if animation should flipflop back to base
} animation_t;
// flip the togglebit every time an animation
// changes so a restart of the same anim can be detected
#define ANIM_TOGGLEBIT 128
typedef enum {
TEAM_FREE,
TEAM_RED,
TEAM_BLUE,
TEAM_SPECTATOR,
TEAM_NUM_TEAMS
} team_t;
// This is a fair assumption for Double Domination:
#define TEAM_NONE TEAM_SPECTATOR
// Time between location updates
#define TEAM_LOCATION_UPDATE_TIME 1000
// How many players on the overlay
#define TEAM_MAXOVERLAY 32
//team task
typedef enum {
TEAMTASK_NONE,
TEAMTASK_OFFENSE,
TEAMTASK_DEFENSE,
TEAMTASK_PATROL,
TEAMTASK_FOLLOW,
TEAMTASK_RETRIEVE,
TEAMTASK_ESCORT,
TEAMTASK_CAMP
} teamtask_t;
// means of death
typedef enum {
MOD_UNKNOWN,
MOD_SHOTGUN,
MOD_GAUNTLET,
MOD_MACHINEGUN,
MOD_GRENADE,
MOD_GRENADE_SPLASH,
MOD_ROCKET,
MOD_ROCKET_SPLASH,
MOD_PLASMA,
MOD_PLASMA_SPLASH,
MOD_RAILGUN,
MOD_LIGHTNING,
MOD_BFG,
MOD_BFG_SPLASH,
MOD_WATER,
MOD_SLIME,
MOD_LAVA,
MOD_CRUSH,
MOD_TELEFRAG,
MOD_FALLING,
MOD_SUICIDE,
MOD_TARGET_LASER,
MOD_TRIGGER_HURT,
MOD_NAIL,
MOD_CHAINGUN,
MOD_PROXIMITY_MINE,
MOD_KAMIKAZE,
MOD_JUICED,
MOD_GRAPPLE
} meansOfDeath_t;
//---------------------------------------------------------
// gitem_t->type
typedef enum {
IT_BAD,
IT_WEAPON, // EFX: rotate + upscale + minlight
IT_AMMO, // EFX: rotate
IT_ARMOR, // EFX: rotate + minlight
IT_HEALTH, // EFX: static external sphere + rotating internal
IT_POWERUP, // instant on, timer based
// EFX: rotate + external ring that rotates
IT_HOLDABLE, // single use, holdable item
// EFX: rotate + bob
IT_PERSISTANT_POWERUP,
IT_TEAM
} itemType_t;
#define MAX_ITEM_MODELS 4
typedef struct gitem_s {
char *classname; // spawning name
char *pickup_sound;
char *world_model[MAX_ITEM_MODELS];
char *icon;
char *pickup_name; // for printing on pickup
int quantity; // for ammo how much, or duration of powerup
itemType_t giType; // IT_* flags
int giTag;
char *precaches; // string of all models and images this item will use
char *sounds; // string of all sounds this item will use
} gitem_t;
// included in both the game dll and the client
extern gitem_t bg_itemlist[];
extern int bg_numItems;
gitem_t *BG_FindItem( const char *pickupName );
gitem_t *BG_FindItemForWeapon( weapon_t weapon );
gitem_t *BG_FindItemForPowerup( powerup_t pw );
gitem_t *BG_FindItemForHoldable( holdable_t pw );
#define ITEM_INDEX(x) ((x)-bg_itemlist)
qboolean BG_CanItemBeGrabbed( int gametype, const entityState_t *ent, const playerState_t *ps );
// g_dmflags->integer flags
#define DF_NO_FALLING 8
#define DF_FIXED_FOV 16
#define DF_NO_FOOTSTEPS 32
#define DF_INSTANT_WEAPON_CHANGE 64
#define DF_NO_BUNNY 128
#define DF_INVIS 256
#define DF_LIGHT_VOTING 512
#define DF_NO_SELF_DAMAGE 1024
#define DF_PLAYER_OVERLAY 2048
//g_videoflags->integer
#define VF_LOCK_CVARS_BASIC 1
#define VF_LOCK_CVARS_EXTENDED 2
#define VF_LOCK_VERTEX 4
// g_elimflags->integer
//This is used to signal the client that it cannot go to free spectator:
#define EF_ONEWAY 1
#define EF_NO_FREESPEC 2
//g_voteflags->integer
//Autoparsed from allowedvote
//List: "/map_restart/nextmap/map/g_gametype/kick/clientkick/g_doWarmup/timelimit/fraglimit/custom/shuffle/"
#define VF_map_restart 1
#define VF_nextmap 2
#define VF_map 4
#define VF_g_gametype 8
//Note that we skipped kick... not needed
#define VF_clientkick 16
#define VF_g_doWarmup 32
#define VF_timelimit 64
#define VF_fraglimit 128
#define VF_custom 256
#define VF_shuffle 512
// content masks
#define MASK_ALL (-1)
#define MASK_SOLID (CONTENTS_SOLID)
#define MASK_PLAYERSOLID (CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY)
#define MASK_DEADSOLID (CONTENTS_SOLID|CONTENTS_PLAYERCLIP)
#define MASK_WATER (CONTENTS_WATER|CONTENTS_LAVA|CONTENTS_SLIME)
#define MASK_OPAQUE (CONTENTS_SOLID|CONTENTS_SLIME|CONTENTS_LAVA)
#define MASK_SHOT (CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_CORPSE)
//
// entityState_t->eType
//
typedef enum {
ET_GENERAL,
ET_PLAYER,
ET_ITEM,
ET_MISSILE,
ET_MOVER,
ET_BEAM,
ET_PORTAL,
ET_SPEAKER,
ET_PUSH_TRIGGER,
ET_TELEPORT_TRIGGER,
ET_INVISIBLE,
ET_GRAPPLE, // grapple hooked on wall
ET_TEAM,
ET_EVENTS // any of the EV_* events can be added freestanding
// by setting eType to ET_EVENTS + eventNum
// this avoids having to set eFlags and eventNum
} entityType_t;
//KK-OAX Using this now instead of g_mem.c
// bg_alloc.c
//
qboolean BG_CanAlloc( unsigned int size );
void *BG_Alloc( unsigned int size );
void BG_InitMemory( void );
void BG_Free( void *ptr );
void BG_DefragmentMemory( void );
void BG_EvaluateTrajectory( const trajectory_t *tr, int atTime, vec3_t result );
void BG_EvaluateTrajectoryDelta( const trajectory_t *tr, int atTime, vec3_t result );
void BG_AddPredictableEventToPlayerstate( int newEvent, int eventParm, playerState_t *ps );
void BG_TouchJumpPad( playerState_t *ps, entityState_t *jumppad );
void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, qboolean snap );
void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s, int time, qboolean snap );
qboolean BG_PlayerTouchesItem( playerState_t *ps, entityState_t *item, int atTime );
#define ARENAS_PER_TIER 4
#define MAX_ARENAS 1024
#define MAX_ARENAS_TEXT 8192
#define MAX_BOTS 1024
#define MAX_BOTS_TEXT 8192
// Kamikaze
// 1st shockwave times
#define KAMI_SHOCKWAVE_STARTTIME 0
#define KAMI_SHOCKWAVEFADE_STARTTIME 1500
#define KAMI_SHOCKWAVE_ENDTIME 2000
// explosion/implosion times
#define KAMI_EXPLODE_STARTTIME 250
#define KAMI_IMPLODE_STARTTIME 2000
#define KAMI_IMPLODE_ENDTIME 2250
// 2nd shockwave times
#define KAMI_SHOCKWAVE2_STARTTIME 2000
#define KAMI_SHOCKWAVE2FADE_STARTTIME 2500
#define KAMI_SHOCKWAVE2_ENDTIME 3000
// radius of the models without scaling
#define KAMI_SHOCKWAVEMODEL_RADIUS 88
#define KAMI_BOOMSPHEREMODEL_RADIUS 72
// maximum radius of the models during the effect
#define KAMI_SHOCKWAVE_MAXRADIUS 1320
#define KAMI_BOOMSPHERE_MAXRADIUS 720
#define KAMI_SHOCKWAVE2_MAXRADIUS 704
//KK-OAX
//bg_misc.c
char *BG_TeamName( team_t team );
#endif

325
code/game/bg_slidemove.c Normal file
View File

@@ -0,0 +1,325 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
// bg_slidemove.c -- part of bg_pmove functionality
#include "../qcommon/q_shared.h"
#include "bg_public.h"
#include "bg_local.h"
/*
input: origin, velocity, bounds, groundPlane, trace function
output: origin, velocity, impacts, stairup boolean
*/
/*
==================
PM_SlideMove
Returns qtrue if the velocity was clipped in some way
==================
*/
#define MAX_CLIP_PLANES 5
qboolean PM_SlideMove( qboolean gravity ) {
int bumpcount, numbumps;
vec3_t dir;
float d;
int numplanes;
vec3_t planes[MAX_CLIP_PLANES];
vec3_t primal_velocity;
vec3_t clipVelocity;
int i, j, k;
trace_t trace;
vec3_t end;
float time_left;
float into;
vec3_t endVelocity;
vec3_t endClipVelocity;
numbumps = 4;
VectorCopy (pm->ps->velocity, primal_velocity);
if ( gravity ) {
VectorCopy( pm->ps->velocity, endVelocity );
endVelocity[2] -= pm->ps->gravity * pml.frametime;
pm->ps->velocity[2] = ( pm->ps->velocity[2] + endVelocity[2] ) * 0.5;
primal_velocity[2] = endVelocity[2];
if ( pml.groundPlane ) {
// slide along the ground plane
PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal,
pm->ps->velocity, OVERCLIP );
}
}
time_left = pml.frametime;
// never turn against the ground plane
if ( pml.groundPlane ) {
numplanes = 1;
VectorCopy( pml.groundTrace.plane.normal, planes[0] );
} else {
numplanes = 0;
}
// never turn against original velocity
VectorNormalize2( pm->ps->velocity, planes[numplanes] );
numplanes++;
for ( bumpcount=0 ; bumpcount < numbumps ; bumpcount++ ) {
// calculate position we are trying to move to
VectorMA( pm->ps->origin, time_left, pm->ps->velocity, end );
// see if we can make it there
pm->trace ( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, pm->tracemask);
if (trace.allsolid) {
// entity is completely trapped in another solid
pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration
return qtrue;
}
if (trace.fraction > 0) {
// actually covered some distance
VectorCopy (trace.endpos, pm->ps->origin);
}
if (trace.fraction == 1) {
break; // moved the entire distance
}
// save entity for contact
PM_AddTouchEnt( trace.entityNum );
time_left -= time_left * trace.fraction;
if (numplanes >= MAX_CLIP_PLANES) {
// this shouldn't really happen
VectorClear( pm->ps->velocity );
return qtrue;
}
//
// if this is the same plane we hit before, nudge velocity
// out along it, which fixes some epsilon issues with
// non-axial planes
//
for ( i = 0 ; i < numplanes ; i++ ) {
if ( DotProduct( trace.plane.normal, planes[i] ) > 0.99 ) {
VectorAdd( trace.plane.normal, pm->ps->velocity, pm->ps->velocity );
break;
}
}
if ( i < numplanes ) {
continue;
}
VectorCopy (trace.plane.normal, planes[numplanes]);
numplanes++;
//
// modify velocity so it parallels all of the clip planes
//
// find a plane that it enters
for ( i = 0 ; i < numplanes ; i++ ) {
into = DotProduct( pm->ps->velocity, planes[i] );
if ( into >= 0.1 ) {
continue; // move doesn't interact with the plane
}
// see how hard we are hitting things
if ( -into > pml.impactSpeed ) {
pml.impactSpeed = -into;
}
// slide along the plane
PM_ClipVelocity (pm->ps->velocity, planes[i], clipVelocity, OVERCLIP );
// slide along the plane
PM_ClipVelocity (endVelocity, planes[i], endClipVelocity, OVERCLIP );
// see if there is a second plane that the new move enters
for ( j = 0 ; j < numplanes ; j++ ) {
if ( j == i ) {
continue;
}
if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) {
continue; // move doesn't interact with the plane
}
// try clipping the move to the plane
PM_ClipVelocity( clipVelocity, planes[j], clipVelocity, OVERCLIP );
PM_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, OVERCLIP );
// see if it goes back into the first clip plane
if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) {
continue;
}
// slide the original velocity along the crease
CrossProduct (planes[i], planes[j], dir);
VectorNormalize( dir );
d = DotProduct( dir, pm->ps->velocity );
VectorScale( dir, d, clipVelocity );
CrossProduct (planes[i], planes[j], dir);
VectorNormalize( dir );
d = DotProduct( dir, endVelocity );
VectorScale( dir, d, endClipVelocity );
// see if there is a third plane the the new move enters
for ( k = 0 ; k < numplanes ; k++ ) {
if ( k == i || k == j ) {
continue;
}
if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) {
continue; // move doesn't interact with the plane
}
// stop dead at a tripple plane interaction
VectorClear( pm->ps->velocity );
return qtrue;
}
}
// if we have fixed all interactions, try another move
VectorCopy( clipVelocity, pm->ps->velocity );
VectorCopy( endClipVelocity, endVelocity );
break;
}
}
if ( gravity ) {
VectorCopy( endVelocity, pm->ps->velocity );
}
// don't change velocity if in a timer (FIXME: is this correct?)
if ( pm->ps->pm_time ) {
VectorCopy( primal_velocity, pm->ps->velocity );
}
return ( bumpcount != 0 );
}
/*
==================
PM_StepSlideMove
==================
*/
void PM_StepSlideMove( qboolean gravity ) {
vec3_t start_o, start_v;
vec3_t down_o, down_v;
trace_t trace;
// float down_dist, up_dist;
// vec3_t delta, delta2;
vec3_t up, down;
float stepSize;
VectorCopy (pm->ps->origin, start_o);
VectorCopy (pm->ps->velocity, start_v);
if ( PM_SlideMove( gravity ) == 0 ) {
return; // we got exactly where we wanted to go first try
}
VectorCopy(start_o, down);
down[2] -= STEPSIZE;
pm->trace (&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask);
VectorSet(up, 0, 0, 1);
// never step up when you still have up velocity
if ( pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 ||
DotProduct(trace.plane.normal, up) < 0.7)) {
return;
}
VectorCopy (pm->ps->origin, down_o);
VectorCopy (pm->ps->velocity, down_v);
VectorCopy (start_o, up);
up[2] += STEPSIZE;
// test the player position if they were a stepheight higher
pm->trace (&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask);
if ( trace.allsolid ) {
if ( pm->debugLevel ) {
Com_Printf("%i:bend can't step\n", c_pmove);
}
return; // can't step up
}
stepSize = trace.endpos[2] - start_o[2];
// try slidemove from this position
VectorCopy (trace.endpos, pm->ps->origin);
VectorCopy (start_v, pm->ps->velocity);
PM_SlideMove( gravity );
// push down the final amount
VectorCopy (pm->ps->origin, down);
down[2] -= stepSize;
pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask);
if ( !trace.allsolid ) {
VectorCopy (trace.endpos, pm->ps->origin);
}
if ( trace.fraction < 1.0 ) {
PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP );
}
#if 0
// if the down trace can trace back to the original position directly, don't step
pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, start_o, pm->ps->clientNum, pm->tracemask);
if ( trace.fraction == 1.0 ) {
// use the original move
VectorCopy (down_o, pm->ps->origin);
VectorCopy (down_v, pm->ps->velocity);
if ( pm->debugLevel ) {
Com_Printf("%i:bend\n", c_pmove);
}
} else
#endif
{
// use the step move
float delta;
delta = pm->ps->origin[2] - start_o[2];
if ( delta > 2 ) {
if ( delta < 7 ) {
PM_AddEvent( EV_STEP_4 );
} else if ( delta < 11 ) {
PM_AddEvent( EV_STEP_8 );
} else if ( delta < 15 ) {
PM_AddEvent( EV_STEP_12 );
} else {
PM_AddEvent( EV_STEP_16 );
}
}
if ( pm->debugLevel ) {
Com_Printf("%i:stepped\n", c_pmove);
}
}
}

103
code/game/challenges.h Normal file
View File

@@ -0,0 +1,103 @@
/*
===========================================================================
Copyright (C) 2008-2009 Poul Sander
This file is part of Open Arena source code.
Open Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Open Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Open Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/**
* This is a list of challenges that a player can only complete while playing
* against human opponents, either LAN or Internet.
*
* Hopefully this will make it a little more fun to play online even if you
* are not good enough to win you can still track your progress.
*/
#define CHALLENGES_MAX_COUNT MAX_INT-1
#define CHALLENGES_MAX 2048
#define GENERAL_TEST 0
#define GENERAL_TOTALKILLS 1
#define GENERAL_TOTALDEATHS 2
#define GENERAL_TOTALGAMES 3
//Gametypes
#define GAMETYPES_FFA_WINS 101
#define GAMETYPES_TOURNEY_WINS 102
#define GAMETYPES_TDM_WINS 103
#define GAMETYPES_CTF_WINS 104
#define GAMETYPES_1FCTF_WINS 105
#define GAMETYPES_OVERLOAD_WINS 106
#define GAMETYPES_HARVESTER_WINS 107
#define GAMETYPES_ELIMINATION_WINS 108
#define GAMETYPES_CTF_ELIMINATION_WINS 109
#define GAMETYPES_LMS_WINS 110
#define GAMETYPES_DD_WINS 111
#define GAMETYPES_DOM_WINS 112
//Weapons
#define WEAPON_GAUNTLET_KILLS 201
#define WEAPON_MACHINEGUN_KILLS 202
#define WEAPON_SHOTGUN_KILLS 203
#define WEAPON_GRANADE_KILLS 204
#define WEAPON_ROCKET_KILLS 205
#define WEAPON_LIGHTNING_KILLS 206
#define WEAPON_PLASMA_KILLS 207
#define WEAPON_RAIL_KILLS 208
#define WEAPON_BFG_KILLS 209
#define WEAPON_GRAPPLE_KILLS 210
#define WEAPON_CHAINGUN_KILLS 211
#define WEAPON_NAILGUN_KILLS 212
#define WEAPON_MINE_KILLS 213
#define WEAPON_PUSH_KILLS 214
#define WEAPON_INSTANT_RAIL_KILLS 215
#define WEAPON_TELEFRAG_KILLS 216
#define WEAPON_CRUSH_KILLS 217
//Awards
//Gauntlet is not here as it is the same as WEAPON_GAUNTLET_KILLS
#define AWARD_IMPRESSIVE 301
#define AWARD_EXCELLENT 302
#define AWARD_CAPTURE 303
#define AWARD_ASSIST 304
#define AWARD_DEFENCE 305
//Powerups
#define POWERUP_QUAD_KILL 401
#define POWERUP_SPEED_KILL 402
#define POWERUP_FLIGHT_KILL 403
#define POWERUP_INVIS_KILL 404
#define POWERUP_MULTI_KILL 405
#define POWERUP_COUNTER_QUAD 406
#define POWERUP_COUNTER_SPEED 407
#define POWERUP_COUNTER_FLIGHT 408
#define POWERUP_COUNTER_INVIS 409
#define POWERUP_COUNTER_ENVIR 410
#define POWERUP_COUNTER_REGEN 411
#define POWERUP_COUNTER_MULTI 412
//FFA awards
#define FFA_TOP3 501
//From behind, enemy gets fraglimit-1, player has at most fraglimit-2 but wins anyway
#define FFA_FROMBEHIND 502
//BetterThan: loose a match but have a positive kill ratio against the winner
#define FFA_BETTERTHAN 503
//Get at least half of your kills for players in the best half of the scoreboard
#define FFA_JUDGE 504
//The oppesite
#define FFA_CHEAPKILLER 505

339
code/game/challenges.xml Normal file
View File

@@ -0,0 +1,339 @@
<Challenges>
<Group>
<Id>0</Id>
<DefineName>GENERAL_</DefineName>
<Name>Overall statistics</Name>
<Description>Totals</Description>
<Challenge>
<Id>0</Id>
<DefineName>TEST</DefineName>
<HideInMenu>1</HideInMenu>
<Name>Test</Name>
<Description>Used for test</Description>
</Challenge>
<Challenge>
<Id>1</Id>
<DefineName>TOTALKILLS</DefineName>
<Name>Kills</Name>
<Description>Total number of players killed</Description>
</Challenge>
<Challenge>
<Id>2</Id>
<DefineName>TOTALDEATHS</DefineName>
<Name>Deaths</Name>
<Description>Number of times killed by another player</Description>
</Challenge>
<Challenge>
<Id>3</Id>
<DefineName>TOTALGAMES</DefineName>
<Name>Games</Name>
<Description>Number of games played with 2 or more human players</Description>
</Challenge>
</Group>
<Group>
<Id>1</Id>
<DefineName>GAMETYPE_</DefineName>
<Name>Gametype wins</Name>
<Description>Number of wins in the different gametypes</Description>
<Challenge>
<Id>1</Id>
<DefineName>FFA_WINS</DefineName>
<Name>Deathmatch</Name>
<Description>Number of victories in deathmatch games</Description>
</Challenge>
<Challenge>
<Id>2</Id>
<DefineName>TOURNEY_WINS</DefineName>
<Name>Tournament</Name>
<Description>Number of victories in tournament games</Description>
</Challenge>
<Challenge>
<Id>3</Id>
<DefineName>TDM_WINS</DefineName>
<Name>Team Deathmatch</Name>
<Description>Number of victories in team deathmatch games</Description>
</Challenge>
<Challenge>
<Id>4</Id>
<DefineName>CTF_WINS</DefineName>
<Name>Capture the flag</Name>
<Description>Number of victories in capture the flag games</Description>
</Challenge>
<Challenge>
<Id>5</Id>
<DefineName>1FCTF_WINS</DefineName>
<Name>One flag capture</Name>
<Description>Number of victories in one flag capture games</Description>
</Challenge>
<Challenge>
<Id>6</Id>
<DefineName>OVERLOAD_WINS</DefineName>
<Name>Obelisk</Name>
<Description>Number of victories in obelisk games</Description>
</Challenge>
<Challenge>
<Id>7</Id>
<DefineName>HARVESTER_WINS</DefineName>
<Name>Harvester</Name>
<Description>Number of victories in harvester games</Description>
</Challenge>
<Challenge>
<Id>8</Id>
<DefineName>ELIMINATION_WINS</DefineName>
<Name>Elimination</Name>
<Description>Number of victories in elimination games</Description>
</Challenge>
<Challenge>
<Id>9</Id>
<DefineName>CTF_ELIMINATION_WINS</DefineName>
<Name>CTF Elimination</Name>
<Description>Number of victories in CTF elimination games</Description>
</Challenge>
<Challenge>
<Id>10</Id>
<DefineName>LMS_WINS</DefineName>
<Name>Last man standing</Name>
<Description>Number of victories in last man standing games</Description>
</Challenge>
<Challenge>
<Id>11</Id>
<DefineName>DD_WINS</DefineName>
<Name>Double Domination</Name>
<Description>Number of victories in double domination games</Description>
</Challenge>
<Challenge>
<Id>12</Id>
<DefineName>DOM_WINS</DefineName>
<Name>Domination</Name>
<Description>Number of victories in domination games</Description>
</Challenge>
</Group>
<Group>
<Id>2</Id>
<DefineName>WEAPON_</DefineName>
<Name>Weapon kills</Name>
<Description>Number of kills with different weapons</Description>
<Challenge>
<Id>1</Id>
<DefineName>GAUNTLET_KILLS</DefineName>
<Name>Gauntlet</Name>
<Description>Number of kills with gauntlet</Description>
</Challenge>
<Challenge>
<Id>2</Id>
<DefineName>MACHINEGUN_KILLS</DefineName>
<Name>Machinegun</Name>
<Description>Number of kills with machinegun</Description>
</Challenge>
<Challenge>
<Id>3</Id>
<DefineName>SHOTGUN_KILLS</DefineName>
<Name>Shotgun</Name>
<Description>Number of kills with shotgun</Description>
</Challenge>
<Challenge>
<Id>4</Id>
<DefineName>GRANADE_KILLS</DefineName>
<Name>Granade launcher</Name>
<Description>Number of kills with granade launcher</Description>
</Challenge>
<Challenge>
<Id>5</Id>
<DefineName>ROCKET_KILLS</DefineName>
<Name>Rocket launcher</Name>
<Description>Number of kills with rocket launcher</Description>
</Challenge>
<Challenge>
<Id>6</Id>
<DefineName>LIGHTNING_KILLS</DefineName>
<Name>Lightning gun</Name>
<Description>Number of kills with lightning</Description>
</Challenge>
<Challenge>
<Id>7</Id>
<DefineName>PLASMA_KILLS</DefineName>
<Name>Plasma gun</Name>
<Description>Number of kills with plasma</Description>
</Challenge>
<Challenge>
<Id>8</Id>
<DefineName>RAIL_KILLS</DefineName>
<Name>Railgun</Name>
<Description>Number of kills with railgun</Description>
</Challenge>
<Challenge>
<Id>9</Id>
<DefineName>BFG_KILLS</DefineName>
<Name>BFG</Name>
<Description>Number of kills with BFG</Description>
</Challenge>
<Challenge>
<Id>10</Id>
<DefineName>GRAPPLE_KILLS</DefineName>
<Name>Grapple</Name>
<Description>Number of kills with grapple gun (almost impossible)</Description>
</Challenge>
<Challenge>
<Id>11</Id>
<DefineName>CHAINGUN_KILLS</DefineName>
<Name>Chaingun</Name>
<Description>Number of kills with the chaingun</Description>
</Challenge>
<Challenge>
<Id>12</Id>
<DefineName>NAILGUN_KILLS</DefineName>
<Name>Nailgun</Name>
<Description>Number of kills with nails</Description>
</Challenge>
<Challenge>
<Id>13</Id>
<DefineName>MINE_KILLS</DefineName>
<Name>Mines</Name>
<Description>Number of kills with mines</Description>
</Challenge>
<Challenge>
<Id>14</Id>
<DefineName>PUSH_KILLS</DefineName>
<Name>Push kills</Name>
<Description>Number of kills by pushing players into lava or void</Description>
</Challenge>
<Challenge>
<Id>15</Id>
<DefineName>INSTANT_RAIL_KILLS</DefineName>
<Name>Instant rail</Name>
<Description>Number of kills with railgun in instantgib</Description>
</Challenge>
<Challenge>
<Id>16</Id>
<DefineName>TELEFRAG_KILLS</DefineName>
<Name>Telefrags</Name>
<Description>Number of kills by telefrag</Description>
</Challenge>
<Challenge>
<Id>17</Id>
<DefineName>CRUSH_KILLS</DefineName>
<Name>Crushing</Name>
<Description>Number of kills by crushing</Description>
</Challenge>
</Group>
<Group>
<Id>3</Id>
<DefineName>AWARD_</DefineName>
<Name>Awards</Name>
<Description>Number of times different awards have been archived</Description>
<Challenge>
<Id>101</Id>
<MenuOnly>1</MenuOnly>
<Name>Gauntlet</Name>
<Description>Number of kills by gauntlet</Description>
</Challenge>
<Challenge>
<Id>1</Id>
<DefineName>IMPRESSIVE</DefineName>
<Name>Impressive</Name>
<Description>Two hits in a row with railgun</Description>
</Challenge>
<Challenge>
<Id>2</Id>
<DefineName>EXCELLENT</DefineName>
<Name>Excelent</Name>
<Description>Two kills in two seconds</Description>
</Challenge>
<Challenge>
<Id>3</Id>
<DefineName>CAPTURE</DefineName>
<Name>Capture</Name>
<Description>Scoring in team games</Description>
</Challenge>
<Challenge>
<Id>4</Id>
<DefineName>ASSIST</DefineName>
<Name>Assist</Name>
<Description>Asisting a capture</Description>
</Challenge>
<Challenge>
<Id>5</Id>
<DefineName>DEFENCE</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
</Group>
<Group>
<Id>4</Id>
<DefineName>POWERUP_</DefineName>
<Name>Power-ups</Name>
<Description>Number of kills with different powerups involved</Description>
<Challenge>
<Id>1</Id>
<DefineName>QUAD_KILL</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>2</Id>
<DefineName>SPEED_KILL</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>3</Id>
<DefineName>FLIGHT_KILL</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>4</Id>
<DefineName>INVIS_KILL</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>5</Id>
<DefineName>MULTI_KILL</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>6</Id>
<DefineName>DEFENCE</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>7</Id>
<DefineName>DEFENCE</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>8</Id>
<DefineName>DEFENCE</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>9</Id>
<DefineName>DEFENCE</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>10</Id>
<DefineName>DEFENCE</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>11</Id>
<DefineName>DEFENCE</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
<Challenge>
<Id>12</Id>
<DefineName>DEFENCE</DefineName>
<Name>Defence</Name>
<Description>Defending objective</Description>
</Challenge>
</Group>
</Challenges>

134
code/game/chars.h Normal file
View File

@@ -0,0 +1,134 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//========================================================
//========================================================
//name
#define CHARACTERISTIC_NAME 0 //string
//gender of the bot
#define CHARACTERISTIC_GENDER 1 //string ("male", "female", "it")
//attack skill
// > 0.0 && < 0.2 = don't move
// > 0.3 && < 1.0 = aim at enemy during retreat
// > 0.0 && < 0.4 = only move forward/backward
// >= 0.4 && < 1.0 = circle strafing
// > 0.7 && < 1.0 = random strafe direction change
#define CHARACTERISTIC_ATTACK_SKILL 2 //float [0, 1]
//weapon weight file
#define CHARACTERISTIC_WEAPONWEIGHTS 3 //string
//view angle difference to angle change factor
#define CHARACTERISTIC_VIEW_FACTOR 4 //float <0, 1]
//maximum view angle change
#define CHARACTERISTIC_VIEW_MAXCHANGE 5 //float [1, 360]
//reaction time in seconds
#define CHARACTERISTIC_REACTIONTIME 6 //float [0, 5]
//accuracy when aiming
#define CHARACTERISTIC_AIM_ACCURACY 7 //float [0, 1]
//weapon specific aim accuracy
#define CHARACTERISTIC_AIM_ACCURACY_MACHINEGUN 8 //float [0, 1]
#define CHARACTERISTIC_AIM_ACCURACY_SHOTGUN 9 //float [0, 1]
#define CHARACTERISTIC_AIM_ACCURACY_ROCKETLAUNCHER 10 //float [0, 1]
#define CHARACTERISTIC_AIM_ACCURACY_GRENADELAUNCHER 11 //float [0, 1]
#define CHARACTERISTIC_AIM_ACCURACY_LIGHTNING 12
#define CHARACTERISTIC_AIM_ACCURACY_PLASMAGUN 13 //float [0, 1]
#define CHARACTERISTIC_AIM_ACCURACY_RAILGUN 14
#define CHARACTERISTIC_AIM_ACCURACY_BFG10K 15 //float [0, 1]
//skill when aiming
// > 0.0 && < 0.9 = aim is affected by enemy movement
// > 0.4 && <= 0.8 = enemy linear leading
// > 0.8 && <= 1.0 = enemy exact movement leading
// > 0.5 && <= 1.0 = prediction shots when enemy is not visible
// > 0.6 && <= 1.0 = splash damage by shooting nearby geometry
#define CHARACTERISTIC_AIM_SKILL 16 //float [0, 1]
//weapon specific aim skill
#define CHARACTERISTIC_AIM_SKILL_ROCKETLAUNCHER 17 //float [0, 1]
#define CHARACTERISTIC_AIM_SKILL_GRENADELAUNCHER 18 //float [0, 1]
#define CHARACTERISTIC_AIM_SKILL_PLASMAGUN 19 //float [0, 1]
#define CHARACTERISTIC_AIM_SKILL_BFG10K 20 //float [0, 1]
//========================================================
//chat
//========================================================
//file with chats
#define CHARACTERISTIC_CHAT_FILE 21 //string
//name of the chat character
#define CHARACTERISTIC_CHAT_NAME 22 //string
//characters per minute type speed
#define CHARACTERISTIC_CHAT_CPM 23 //integer [1, 4000]
//tendency to insult/praise
#define CHARACTERISTIC_CHAT_INSULT 24 //float [0, 1]
//tendency to chat misc
#define CHARACTERISTIC_CHAT_MISC 25 //float [0, 1]
//tendency to chat at start or end of level
#define CHARACTERISTIC_CHAT_STARTENDLEVEL 26 //float [0, 1]
//tendency to chat entering or exiting the game
#define CHARACTERISTIC_CHAT_ENTEREXITGAME 27 //float [0, 1]
//tendency to chat when killed someone
#define CHARACTERISTIC_CHAT_KILL 28 //float [0, 1]
//tendency to chat when died
#define CHARACTERISTIC_CHAT_DEATH 29 //float [0, 1]
//tendency to chat when enemy suicides
#define CHARACTERISTIC_CHAT_ENEMYSUICIDE 30 //float [0, 1]
//tendency to chat when hit while talking
#define CHARACTERISTIC_CHAT_HITTALKING 31 //float [0, 1]
//tendency to chat when bot was hit but didn't dye
#define CHARACTERISTIC_CHAT_HITNODEATH 32 //float [0, 1]
//tendency to chat when bot hit the enemy but enemy didn't dye
#define CHARACTERISTIC_CHAT_HITNOKILL 33 //float [0, 1]
//tendency to randomly chat
#define CHARACTERISTIC_CHAT_RANDOM 34 //float [0, 1]
//tendency to reply
#define CHARACTERISTIC_CHAT_REPLY 35 //float [0, 1]
//========================================================
//movement
//========================================================
//tendency to crouch
#define CHARACTERISTIC_CROUCHER 36 //float [0, 1]
//tendency to jump
#define CHARACTERISTIC_JUMPER 37 //float [0, 1]
//tendency to walk
#define CHARACTERISTIC_WALKER 48 //float [0, 1]
//tendency to jump using a weapon
#define CHARACTERISTIC_WEAPONJUMPING 38 //float [0, 1]
//tendency to use the grapple hook when available
#define CHARACTERISTIC_GRAPPLE_USER 39 //float [0, 1] //use this!!
//========================================================
//goal
//========================================================
//item weight file
#define CHARACTERISTIC_ITEMWEIGHTS 40 //string
//the aggression of the bot
#define CHARACTERISTIC_AGGRESSION 41 //float [0, 1]
//the self preservation of the bot (rockets near walls etc.)
#define CHARACTERISTIC_SELFPRESERVATION 42 //float [0, 1]
//how likely the bot is to take revenge
#define CHARACTERISTIC_VENGEFULNESS 43 //float [0, 1] //use this!!
//tendency to camp
#define CHARACTERISTIC_CAMPER 44 //float [0, 1]
//========================================================
//========================================================
//tendency to get easy frags
#define CHARACTERISTIC_EASY_FRAGGER 45 //float [0, 1]
//how alert the bot is (view distance)
#define CHARACTERISTIC_ALERTNESS 46 //float [0, 1]
//how much the bot fires it's weapon
#define CHARACTERISTIC_FIRETHROTTLE 47 //float [0, 1]

1368
code/game/g_active.c Normal file

File diff suppressed because it is too large Load Diff

3470
code/game/g_admin.c Normal file

File diff suppressed because it is too large Load Diff

205
code/game/g_admin.h Normal file
View File

@@ -0,0 +1,205 @@
/*
===========================================================================
Copyright (C) 2004-2006 Tony J. White
Portions Copyright (C) 2009 Karl F. Kuglin
This file is part of the Open Arena source code.
Originally copied from Tremulous under GPL version 2 including any later
version. The code has been modified to fit the needs of Open Arena.
Open Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Open Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Open Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#ifndef _G_ADMIN_H
#define _G_ADMIN_H
#define AP(x) trap_SendServerCommand(-1, x)
#define CP(x) trap_SendServerCommand(ent-g_entities, x)
#define CPx(x, y) trap_SendServerCommand(x, y)
#define ADMP(x) G_admin_print(ent, x)
#define ADMBP(x) G_admin_buffer_print(ent, x)
#define ADMBP_begin() G_admin_buffer_begin()
#define ADMBP_end() G_admin_buffer_end(ent)
#define MAX_ADMIN_LEVELS 32
#define MAX_ADMIN_ADMINS 1024
#define MAX_ADMIN_BANS 1024
#define MAX_ADMIN_NAMELOGS 128
#define MAX_ADMIN_NAMELOG_NAMES 5
#define MAX_ADMIN_FLAGS 64
#define MAX_ADMIN_COMMANDS 64
#define MAX_ADMIN_CMD_LEN 20
#define MAX_ADMIN_BAN_REASON 50
//KK-OAX
#define MAX_ADMIN_WARNINGS 1024
/*
* 1 - cannot be vote kicked, vote muted
* 2 - cannot be censored or flood protected TODO
* 3 - never loses credits for changing teams
* 4 - can see team chat as a spectator
* 5 - can switch teams any time, regardless of balance
* 6 - does not need to specify a reason for a kick/ban
* 7 - can call a vote at any time (regardless of a vote being disabled or
* voting limitations)
* 8 - does not need to specify a duration for a ban
* 9 - can run commands from team chat
* 0 - inactivity rules do not apply to them
* ! - admin commands cannot be used on them
* @ - does not show up as an admin in !listplayers
* $ - sees all information in !listplayers
* ? - receieves and can send /a admin messages
*/
#define ADMF_IMMUNITY '1'
#define ADMF_NOCENSORFLOOD '2' /* TODO */
#define ADMF_TEAMCHANGEFREE '3'
#define ADMF_SPEC_ALLCHAT '4'
#define ADMF_FORCETEAMCHANGE '5'
#define ADMF_UNACCOUNTABLE '6'
#define ADMF_NO_VOTE_LIMIT '7'
#define ADMF_CAN_PERM_BAN '8'
#define ADMF_TEAMCHAT_CMD '9'
#define ADMF_ACTIVITY '0'
#define ADMF_IMMUTABLE '!'
#define ADMF_INCOGNITO '@'
#define ADMF_ADMINCHAT '?'
#define MAX_ADMIN_LISTITEMS 20
#define MAX_ADMIN_SHOWBANS 10
// important note: QVM does not seem to allow a single char to be a
// member of a struct at init time. flag has been converted to char*
typedef struct
{
char *keyword;
qboolean ( * handler ) ( gentity_t *ent, int skiparg );
char *flag;
char *function; // used for !help
char *syntax; // used for !help
}
g_admin_cmd_t;
typedef struct g_admin_level
{
int level;
char name[ MAX_NAME_LENGTH ];
char flags[ MAX_ADMIN_FLAGS ];
}
g_admin_level_t;
typedef struct g_admin_admin
{
char guid[ 33 ];
char name[ MAX_NAME_LENGTH ];
int level;
char flags[ MAX_ADMIN_FLAGS ];
}
g_admin_admin_t;
typedef struct g_admin_ban
{
char name[ MAX_NAME_LENGTH ];
char guid[ 33 ];
char ip[ 40 ];
char reason[ MAX_ADMIN_BAN_REASON ];
char made[ 18 ]; // big enough for strftime() %c
int expires;
char banner[ MAX_NAME_LENGTH ];
}
g_admin_ban_t;
typedef struct g_admin_command
{
char command[ MAX_ADMIN_CMD_LEN ];
char exec[ MAX_QPATH ];
char desc[ 50 ];
int levels[ MAX_ADMIN_LEVELS + 1 ];
}
g_admin_command_t;
typedef struct g_admin_namelog
{
char name[ MAX_ADMIN_NAMELOG_NAMES ][ MAX_NAME_LENGTH ];
char ip[ 40 ];
char guid[ 33 ];
int slot;
qboolean banned;
}
g_admin_namelog_t;
//KK-OAX Added for Warnings
typedef struct g_admin_warning {
char name[ MAX_NAME_LENGTH ];
char guid[ 33 ];
char ip[ 40 ];
char warning[MAX_STRING_CHARS];
char made[ 18 ];
char warner[MAX_NAME_LENGTH];
int expires;
} g_admin_warning_t;
qboolean G_admin_ban_check( char *userinfo, char *reason, int rlen );
qboolean G_admin_cmd_check( gentity_t *ent, qboolean say );
qboolean G_admin_readconfig( gentity_t *ent, int skiparg );
qboolean G_admin_permission( gentity_t *ent, char flag );
qboolean G_admin_name_check( gentity_t *ent, char *name, char *err, int len );
void G_admin_namelog_update( gclient_t *ent, qboolean disconnect );
int G_admin_level( gentity_t *ent );
int G_admin_parse_time( const char *time );
// ! command functions
qboolean G_admin_time( gentity_t *ent, int skiparg );
qboolean G_admin_setlevel( gentity_t *ent, int skiparg );
qboolean G_admin_kick( gentity_t *ent, int skiparg );
qboolean G_admin_adjustban( gentity_t *ent, int skiparg );
qboolean G_admin_ban( gentity_t *ent, int skiparg );
qboolean G_admin_unban( gentity_t *ent, int skiparg );
qboolean G_admin_putteam( gentity_t *ent, int skiparg );
qboolean G_admin_listadmins( gentity_t *ent, int skiparg );
qboolean G_admin_listplayers( gentity_t *ent, int skiparg );
qboolean G_admin_map( gentity_t *ent, int skiparg );
qboolean G_admin_mute( gentity_t *ent, int skiparg );
qboolean G_admin_showbans( gentity_t *ent, int skiparg );
qboolean G_admin_help( gentity_t *ent, int skiparg );
qboolean G_admin_admintest( gentity_t *ent, int skiparg );
qboolean G_admin_allready( gentity_t *ent, int skiparg );
qboolean G_admin_cancelvote( gentity_t *ent, int skiparg );
qboolean G_admin_passvote( gentity_t *ent, int skiparg );
qboolean G_admin_spec999( gentity_t *ent, int skiparg );
qboolean G_admin_rename( gentity_t *ent, int skiparg );
qboolean G_admin_restart( gentity_t *ent, int skiparg );
qboolean G_admin_nextmap( gentity_t *ent, int skiparg );
qboolean G_admin_namelog( gentity_t *ent, int skiparg );
qboolean G_admin_lock( gentity_t *ent, int skiparg );
qboolean G_admin_unlock( gentity_t *ent, int skiparg );
//KK-OAX
qboolean G_admin_disorient( gentity_t *ent, int skiparg );
qboolean G_admin_orient(gentity_t *ent, int skiparg );
qboolean G_admin_slap(gentity_t *ent, int skiparg );
qboolean G_admin_warn( gentity_t *ent, int skiparg );
qboolean G_admin_shuffle( gentity_t *ent, int skiparg );
void G_admin_print( gentity_t *ent, char *m );
void G_admin_buffer_print( gentity_t *ent, char *m );
void G_admin_buffer_begin( void );
void G_admin_buffer_end( gentity_t *ent );
void G_admin_duration( int secs, char *duration, int dursize );
void G_admin_cleanup( void );
void G_admin_namelog_cleanup( void );
#endif /* ifndef _G_ADMIN_H */

376
code/game/g_arenas.c Normal file
View File

@@ -0,0 +1,376 @@
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
//
// g_arenas.c
//
#include "g_local.h"
gentity_t *podium1;
gentity_t *podium2;
gentity_t *podium3;
/*
==================
UpdateTournamentInfo
==================
*/
void UpdateTournamentInfo( void ) {
int i;
gentity_t *player;
int playerClientNum;
int n, accuracy, perfect, msglen;
#ifdef MISSIONPACK // bk001205
int score1, score2;
qboolean won;
#endif
char buf[32];
char msg[MAX_STRING_CHARS];
// find the real player
player = NULL;
for (i = 0; i < level.maxclients; i++ ) {
player = &g_entities[i];
if ( !player->inuse ) {
continue;
}
if ( !( player->r.svFlags & SVF_BOT ) ) {
break;
}
}
// this should never happen!
if ( !player || i == level.maxclients ) {
return;
}
playerClientNum = i;
CalculateRanks();
if ( level.clients[playerClientNum].sess.sessionTeam == TEAM_SPECTATOR ) {
#ifdef MISSIONPACK
Com_sprintf( msg, sizeof(msg), "postgame %i %i 0 0 0 0 0 0 0 0 0 0 0", level.numNonSpectatorClients, playerClientNum );
#else
Com_sprintf( msg, sizeof(msg), "postgame %i %i 0 0 0 0 0 0", level.numNonSpectatorClients, playerClientNum );
#endif
}
else {
if( player->client->accuracy_shots ) {
accuracy = player->client->accuracy_hits * 100 / player->client->accuracy_shots;
}
else {
accuracy = 0;
}
#ifdef MISSIONPACK
won = qfalse;
if (g_gametype.integer >= GT_CTF && g_ffa_gt==0) {
score1 = level.teamScores[TEAM_RED];
score2 = level.teamScores[TEAM_BLUE];
if (level.clients[playerClientNum].sess.sessionTeam == TEAM_RED) {
won = (level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE]);
} else {
won = (level.teamScores[TEAM_BLUE] > level.teamScores[TEAM_RED]);
}
} else {
if (&level.clients[playerClientNum] == &level.clients[ level.sortedClients[0] ]) {
won = qtrue;
score1 = level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE];
score2 = level.clients[ level.sortedClients[1] ].ps.persistant[PERS_SCORE];
} else {
score2 = level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE];
score1 = level.clients[ level.sortedClients[1] ].ps.persistant[PERS_SCORE];
}
}
if (won && player->client->ps.persistant[PERS_KILLED] == 0) {
perfect = 1;
} else {
perfect = 0;
}
Com_sprintf( msg, sizeof(msg), "postgame %i %i %i %i %i %i %i %i %i %i %i %i %i %i", level.numNonSpectatorClients, playerClientNum, accuracy,
player->client->ps.persistant[PERS_IMPRESSIVE_COUNT], player->client->ps.persistant[PERS_EXCELLENT_COUNT],player->client->ps.persistant[PERS_DEFEND_COUNT],
player->client->ps.persistant[PERS_ASSIST_COUNT], player->client->ps.persistant[PERS_GAUNTLET_FRAG_COUNT], player->client->ps.persistant[PERS_SCORE],
perfect, score1, score2, level.time, player->client->ps.persistant[PERS_CAPTURES] );
#else
perfect = ( level.clients[playerClientNum].ps.persistant[PERS_RANK] == 0 && player->client->ps.persistant[PERS_KILLED] == 0 ) ? 1 : 0;
Com_sprintf( msg, sizeof(msg), "postgame %i %i %i %i %i %i %i %i", level.numNonSpectatorClients, playerClientNum, accuracy,
player->client->ps.persistant[PERS_IMPRESSIVE_COUNT], player->client->ps.persistant[PERS_EXCELLENT_COUNT],
player->client->ps.persistant[PERS_GAUNTLET_FRAG_COUNT], player->client->ps.persistant[PERS_SCORE],
perfect );
#endif
}
msglen = strlen( msg );
for( i = 0; i < level.numNonSpectatorClients; i++ ) {
n = level.sortedClients[i];
Com_sprintf( buf, sizeof(buf), " %i %i %i", n, level.clients[n].ps.persistant[PERS_RANK], level.clients[n].ps.persistant[PERS_SCORE] );
msglen += strlen( buf );
if( msglen >= sizeof(msg) ) {
break;
}
strcat( msg, buf );
}
trap_SendConsoleCommand( EXEC_APPEND, msg );
}
static gentity_t *SpawnModelOnVictoryPad( gentity_t *pad, vec3_t offset, gentity_t *ent, int place ) {
gentity_t *body;
vec3_t vec;
vec3_t f, r, u;
body = G_Spawn();
if ( !body ) {
G_Printf( S_COLOR_RED "ERROR: out of gentities\n" );
return NULL;
}
body->classname = ent->client->pers.netname;
body->client = ent->client;
body->s = ent->s;
body->s.eType = ET_PLAYER; // could be ET_INVISIBLE
body->s.eFlags = 0; // clear EF_TALK, etc
body->s.powerups = 0; // clear powerups
body->s.loopSound = 0; // clear lava burning
body->s.number = body - g_entities;
body->timestamp = level.time;
body->physicsObject = qtrue;
body->physicsBounce = 0; // don't bounce
body->s.event = 0;
body->s.pos.trType = TR_STATIONARY;
body->s.groundEntityNum = ENTITYNUM_WORLD;
body->s.legsAnim = LEGS_IDLE;
body->s.torsoAnim = TORSO_STAND;
if( body->s.weapon == WP_NONE ) {
body->s.weapon = WP_MACHINEGUN;
}
if( body->s.weapon == WP_GAUNTLET) {
body->s.torsoAnim = TORSO_STAND2;
}
body->s.event = 0;
body->r.svFlags = ent->r.svFlags;
VectorCopy (ent->r.mins, body->r.mins);
VectorCopy (ent->r.maxs, body->r.maxs);
VectorCopy (ent->r.absmin, body->r.absmin);
VectorCopy (ent->r.absmax, body->r.absmax);
body->clipmask = CONTENTS_SOLID | CONTENTS_PLAYERCLIP;
body->r.contents = CONTENTS_BODY;
body->r.ownerNum = ent->r.ownerNum;
body->takedamage = qfalse;
VectorSubtract( level.intermission_origin, pad->r.currentOrigin, vec );
vectoangles( vec, body->s.apos.trBase );
body->s.apos.trBase[PITCH] = 0;
body->s.apos.trBase[ROLL] = 0;
AngleVectors( body->s.apos.trBase, f, r, u );
VectorMA( pad->r.currentOrigin, offset[0], f, vec );
VectorMA( vec, offset[1], r, vec );
VectorMA( vec, offset[2], u, vec );
G_SetOrigin( body, vec );
trap_LinkEntity (body);
body->count = place;
return body;
}
static void CelebrateStop( gentity_t *player ) {
int anim;
if( player->s.weapon == WP_GAUNTLET) {
anim = TORSO_STAND2;
}
else {
anim = TORSO_STAND;
}
player->s.torsoAnim = ( ( player->s.torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
}
#define TIMER_GESTURE (34*66+50)
static void CelebrateStart( gentity_t *player ) {
player->s.torsoAnim = ( ( player->s.torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | TORSO_GESTURE;
player->nextthink = level.time + TIMER_GESTURE;
player->think = CelebrateStop;
/*
player->client->ps.events[player->client->ps.eventSequence & (MAX_PS_EVENTS-1)] = EV_TAUNT;
player->client->ps.eventParms[player->client->ps.eventSequence & (MAX_PS_EVENTS-1)] = 0;
player->client->ps.eventSequence++;
*/
G_AddEvent(player, EV_TAUNT, 0);
}
static vec3_t offsetFirst = {0, 0, 74};
static vec3_t offsetSecond = {-10, 60, 54};
static vec3_t offsetThird = {-19, -60, 45};
static void PodiumPlacementThink( gentity_t *podium ) {
vec3_t vec;
vec3_t origin;
vec3_t f, r, u;
podium->nextthink = level.time + 100;
AngleVectors( level.intermission_angle, vec, NULL, NULL );
VectorMA( level.intermission_origin, trap_Cvar_VariableIntegerValue( "g_podiumDist" ), vec, origin );
origin[2] -= trap_Cvar_VariableIntegerValue( "g_podiumDrop" );
G_SetOrigin( podium, origin );
if( podium1 ) {
VectorSubtract( level.intermission_origin, podium->r.currentOrigin, vec );
vectoangles( vec, podium1->s.apos.trBase );
podium1->s.apos.trBase[PITCH] = 0;
podium1->s.apos.trBase[ROLL] = 0;
AngleVectors( podium1->s.apos.trBase, f, r, u );
VectorMA( podium->r.currentOrigin, offsetFirst[0], f, vec );
VectorMA( vec, offsetFirst[1], r, vec );
VectorMA( vec, offsetFirst[2], u, vec );
G_SetOrigin( podium1, vec );
}
if( podium2 ) {
VectorSubtract( level.intermission_origin, podium->r.currentOrigin, vec );
vectoangles( vec, podium2->s.apos.trBase );
podium2->s.apos.trBase[PITCH] = 0;
podium2->s.apos.trBase[ROLL] = 0;
AngleVectors( podium2->s.apos.trBase, f, r, u );
VectorMA( podium->r.currentOrigin, offsetSecond[0], f, vec );
VectorMA( vec, offsetSecond[1], r, vec );
VectorMA( vec, offsetSecond[2], u, vec );
G_SetOrigin( podium2, vec );
}
if( podium3 ) {
VectorSubtract( level.intermission_origin, podium->r.currentOrigin, vec );
vectoangles( vec, podium3->s.apos.trBase );
podium3->s.apos.trBase[PITCH] = 0;
podium3->s.apos.trBase[ROLL] = 0;
AngleVectors( podium3->s.apos.trBase, f, r, u );
VectorMA( podium->r.currentOrigin, offsetThird[0], f, vec );
VectorMA( vec, offsetThird[1], r, vec );
VectorMA( vec, offsetThird[2], u, vec );
G_SetOrigin( podium3, vec );
}
}
static gentity_t *SpawnPodium( void ) {
gentity_t *podium;
vec3_t vec;
vec3_t origin;
podium = G_Spawn();
if ( !podium ) {
return NULL;
}
podium->classname = "podium";
podium->s.eType = ET_GENERAL;
podium->s.number = podium - g_entities;
podium->clipmask = CONTENTS_SOLID;
podium->r.contents = CONTENTS_SOLID;
podium->s.modelindex = G_ModelIndex( SP_PODIUM_MODEL );
AngleVectors( level.intermission_angle, vec, NULL, NULL );
VectorMA( level.intermission_origin, trap_Cvar_VariableIntegerValue( "g_podiumDist" ), vec, origin );
origin[2] -= trap_Cvar_VariableIntegerValue( "g_podiumDrop" );
G_SetOrigin( podium, origin );
VectorSubtract( level.intermission_origin, podium->r.currentOrigin, vec );
podium->s.apos.trBase[YAW] = vectoyaw( vec );
trap_LinkEntity (podium);
podium->think = PodiumPlacementThink;
podium->nextthink = level.time + 100;
return podium;
}
/*
==================
SpawnModelsOnVictoryPads
==================
*/
void SpawnModelsOnVictoryPads( void ) {
gentity_t *player;
gentity_t *podium;
podium1 = NULL;
podium2 = NULL;
podium3 = NULL;
podium = SpawnPodium();
player = SpawnModelOnVictoryPad( podium, offsetFirst, &g_entities[level.sortedClients[0]],
level.clients[ level.sortedClients[0] ].ps.persistant[PERS_RANK] &~ RANK_TIED_FLAG );
if ( player ) {
player->nextthink = level.time + 2000;
player->think = CelebrateStart;
podium1 = player;
}
player = SpawnModelOnVictoryPad( podium, offsetSecond, &g_entities[level.sortedClients[1]],
level.clients[ level.sortedClients[1] ].ps.persistant[PERS_RANK] &~ RANK_TIED_FLAG );
if ( player ) {
podium2 = player;
}
if ( level.numNonSpectatorClients > 2 ) {
player = SpawnModelOnVictoryPad( podium, offsetThird, &g_entities[level.sortedClients[2]],
level.clients[ level.sortedClients[2] ].ps.persistant[PERS_RANK] &~ RANK_TIED_FLAG );
if ( player ) {
podium3 = player;
}
}
}
/*
===============
Svcmd_AbortPodium_f
===============
*/
void Svcmd_AbortPodium_f( void ) {
if( g_gametype.integer != GT_SINGLE_PLAYER ) {
return;
}
if( podium1 ) {
podium1->nextthink = level.time;
podium1->think = CelebrateStop;
}
}

1026
code/game/g_bot.c Normal file

File diff suppressed because it is too large Load Diff

2218
code/game/g_client.c Normal file

File diff suppressed because it is too large Load Diff

2312
code/game/g_cmds.c Normal file

File diff suppressed because it is too large Load Diff

705
code/game/g_cmds_ext.c Normal file
View File

@@ -0,0 +1,705 @@
/*
===========================================================================
Copyright (C) 2004-2006 Tony J. White
This file is part of the Open Arena source code.
Copied from Tremulous under GPL version 2 including any later version.
Open Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Open Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Open Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "g_local.h"
/*
=================
G_SayArgc
G_SayArgv
G_SayConcatArgs
trap_Argc, trap_Argv, and ConcatArgs consider say text as a single argument
These functions assemble the text and re-parse it on word boundaries
=================
*/
int G_SayArgc( void )
{
int c = 0;
char *s;
s = ConcatArgs( 0 );
while( 1 )
{
while( *s == ' ' )
s++;
if( !*s )
break;
c++;
while( *s && *s != ' ' )
s++;
}
return c;
}
qboolean G_SayArgv( int n, char *buffer, int bufferLength )
{
char *s;
if( bufferLength < 1 )
return qfalse;
if( n < 0 )
return qfalse;
s = ConcatArgs( 0 );
while( 1 )
{
while( *s == ' ' )
s++;
if( !*s || n == 0 )
break;
n--;
while( *s && *s != ' ' )
s++;
}
if( n > 0 )
return qfalse;
//memccpy( buffer, s, ' ', bufferLength );
while( *s && *s != ' ' && bufferLength > 1 )
{
*buffer++ = *s++;
bufferLength--;
}
*buffer = 0;
return qtrue;
}
char *G_SayConcatArgs( int start )
{
char *s;
s = ConcatArgs( 0 );
while( 1 )
{
while( *s == ' ' )
s++;
if( !*s || start == 0 )
break;
start--;
while( *s && *s != ' ' )
s++;
}
return s;
}
void G_DecolorString( char *in, char *out, int len )
{
len--;
while( *in && len > 0 )
{
if( Q_IsColorString( in ) )
{
in++;
if( *in )
in++;
continue;
}
*out++ = *in++;
len--;
}
*out = '\0';
}
/*
==================
G_MatchOnePlayer
This is a companion function to G_ClientNumbersFromString()
err will be populated with an error message.
==================
*/
void G_MatchOnePlayer( int *plist, int num, char *err, int len )
{
gclient_t *cl;
int i;
char line[ MAX_NAME_LENGTH + 10 ] = {""};
err[ 0 ] = '\0';
if( num == 0 )
{
Q_strcat( err, len, "no connected player by that name or slot #" );
}
else if( num > 1 )
{
Q_strcat( err, len, "more than one player name matches. Be more specific or use the slot #:\n" );
for( i = 0; i < num; i++ )
{
cl = &level.clients[ plist[ i ] ];
if( cl->pers.connected == CON_DISCONNECTED )
continue;
Com_sprintf( line, sizeof( line ), "%2i - %s^7\n",
plist[ i ], cl->pers.netname );
if( strlen( err ) + strlen( line ) > len )
break;
Q_strcat( err, len, line );
}
}
}
/*
==================
G_SanitiseString
Remove case and control characters from a string
==================
*/
void G_SanitiseString( char *in, char *out, int len )
{
qboolean skip = qtrue;
int spaces = 0;
len--;
while( *in && len > 0 )
{
// strip leading white space
if( *in == ' ' )
{
if( skip )
{
in++;
continue;
}
spaces++;
}
else
{
spaces = 0;
skip = qfalse;
}
if( Q_IsColorString( in ) )
{
in += 2; // skip color code
continue;
}
if( *in < 32 )
{
in++;
continue;
}
*out++ = tolower( *in++ );
len--;
}
out -= spaces;
*out = 0;
}
/*
==================
G_ClientNumbersFromString
Sets plist to an array of integers that represent client numbers that have
names that are a partial match for s.
Returns number of matching clientids up to max.
==================
*/
int G_ClientNumbersFromString( char *s, int *plist, int max )
{
gclient_t *p;
int i, found = 0;
char n2[ MAX_NAME_LENGTH ] = {""};
char s2[ MAX_NAME_LENGTH ] = {""};
if( max == 0 )
return 0;
// if a number is provided, it is a clientnum
for( i = 0; s[ i ] && isdigit( s[ i ] ); i++ );
if( !s[ i ] )
{
i = atoi( s );
if( i >= 0 && i < level.maxclients )
{
p = &level.clients[ i ];
if( p->pers.connected != CON_DISCONNECTED )
{
*plist = i;
return 1;
}
}
// we must assume that if only a number is provided, it is a clientNum
return 0;
}
// now look for name matches
G_SanitiseString( s, s2, sizeof( s2 ) );
if( strlen( s2 ) < 1 )
return 0;
for( i = 0; i < level.maxclients && found < max; i++ )
{
p = &level.clients[ i ];
if( p->pers.connected == CON_DISCONNECTED )
{
continue;
}
G_SanitiseString( p->pers.netname, n2, sizeof( n2 ) );
if( strstr( n2, s2 ) )
{
*plist++ = i;
found++;
}
}
return found;
}
/*
==================
G_FloodLimited
Determine whether a user is flood limited, and adjust their flood demerits
Print them a warning message if they are over the limit
Return is time in msec until the user can speak again
==================
*/
int G_FloodLimited( gentity_t *ent )
{
int deltatime, ms;
if( g_floodMinTime.integer <= 0 )
return 0;
// handles !ent
if( G_admin_permission( ent, ADMF_NOCENSORFLOOD ) )
return 0;
deltatime = level.time - ent->client->pers.floodTime;
ent->client->pers.floodDemerits += g_floodMinTime.integer - deltatime;
if( ent->client->pers.floodDemerits < 0 )
ent->client->pers.floodDemerits = 0;
ent->client->pers.floodTime = level.time;
ms = ent->client->pers.floodDemerits - g_floodMaxDemerits.integer;
if( ms <= 0 )
return 0;
trap_SendServerCommand( ent - g_entities, va( "print \"You are flooding: please wait %d second%s before trying again\n",
( ms + 999 ) / 1000, ( ms > 1000 ) ? "s" : "" ) );
return ms;
}
//KK-Private Messaging Not implemented.
/*
void Cmd_PrivateMessage_f( gentity_t *ent )
{
int pids[ MAX_CLIENTS ];
int ignoreids[ MAX_CLIENTS ];
char name[ MAX_NAME_LENGTH ];
char cmd[ 12 ];
char str[ MAX_STRING_CHARS ];
char *msg;
char color;
int pcount, matches, ignored = 0;
int i;
int skipargs = 0;
qboolean teamonly = qfalse;
gentity_t *tmpent;
if( !g_privateMessages.integer && ent )
{
ADMP( "Sorry, but private messages have been disabled\n" );
return;
}
G_SayArgv( 0, cmd, sizeof( cmd ) );
if( !Q_stricmp( cmd, "say" ) || !Q_stricmp( cmd, "say_team" ) )
{
skipargs = 1;
G_SayArgv( 1, cmd, sizeof( cmd ) );
}
if( G_SayArgc( ) < 3+skipargs )
{
ADMP( va( "usage: %s [name|slot#] [message]\n", cmd ) );
return;
}
if( !Q_stricmp( cmd, "mt" ) || !Q_stricmp( cmd, "/mt" ) )
teamonly = qtrue;
G_SayArgv( 1+skipargs, name, sizeof( name ) );
msg = G_SayConcatArgs( 2+skipargs );
pcount = G_ClientNumbersFromString( name, pids, MAX_CLIENTS );
if( ent )
{
int count = 0;
for( i = 0; i < pcount; i++ )
{
tmpent = &g_entities[ pids[ i ] ];
if( teamonly && !OnSameTeam( ent, tmpent ) )
continue;
if( BG_ClientListTest( &tmpent->client->pers.ignoreList,
ent-g_entities ) )
{
ignoreids[ ignored++ ] = pids[ i ];
continue;
}
pids[ count ] = pids[ i ];
count++;
}
matches = count;
}
else
{
matches = pcount;
}
color = teamonly ? COLOR_CYAN : COLOR_YELLOW;
Com_sprintf( str, sizeof( str ), "^%csent to %i player%s: ^7", color, matches,
( matches == 1 ) ? "" : "s" );
for( i=0; i < matches; i++ )
{
tmpent = &g_entities[ pids[ i ] ];
if( i > 0 )
Q_strcat( str, sizeof( str ), "^7, " );
Q_strcat( str, sizeof( str ), tmpent->client->pers.netname );
trap_SendServerCommand( pids[ i ], va(
"chat \"%s^%c -> ^7%s^7: (%d recipient%s): ^%c%s^7\" %i",
( ent ) ? ent->client->pers.netname : "console",
color,
name,
matches,
( matches == 1 ) ? "" : "s",
color,
msg,
ent ? ent-g_entities : -1 ) );
if( ent )
{
trap_SendServerCommand( pids[ i ], va(
"print \">> to reply, say: /m %d [your message] <<\n\"",
( ent - g_entities ) ) );
}
trap_SendServerCommand( pids[ i ], va(
"cp \"^%cprivate message from ^7%s^7\"", color,
( ent ) ? ent->client->pers.netname : "console" ) );
}
if( !matches )
ADMP( va( "^3No player matching ^7\'%s^7\' ^3to send message to.\n",
name ) );
else
{
ADMP( va( "^%cPrivate message: ^7%s\n", color, msg ) );
ADMP( va( "%s\n", str ) );
G_LogPrintf( "%s: %s^7: %s^7: %s\n",
( teamonly ) ? "tprivmsg" : "privmsg",
( ent ) ? ent->client->pers.netname : "console",
name, msg );
}
if( ignored )
{
Com_sprintf( str, sizeof( str ), "^%cignored by %i player%s: ^7", color,
ignored, ( ignored == 1 ) ? "" : "s" );
for( i=0; i < ignored; i++ )
{
tmpent = &g_entities[ ignoreids[ i ] ];
if( i > 0 )
Q_strcat( str, sizeof( str ), "^7, " );
Q_strcat( str, sizeof( str ), tmpent->client->pers.netname );
}
ADMP( va( "%s\n", str ) );
}
}
*/
/*
=================
G_AdminMessage
Print to all active server admins, and to the logfile, and to the server console
Prepend *prefix, or '[SERVER]' if no *prefix is given
=================
*/
void QDECL G_AdminMessage( const char *prefix, const char *fmt, ... )
{
va_list argptr;
char string[ 1024 ];
char outstring[ 1024 ];
int i;
// Format the text
va_start( argptr, fmt );
Q_vsnprintf( string, sizeof( string ), fmt, argptr );
va_end( argptr );
// If there is no prefix, assume that this function was called directly
// and we should add one
if( !prefix || !prefix[ 0 ] )
{
prefix = "[SERVER]:";
}
// Create the final string
Com_sprintf( outstring, sizeof( outstring ), "%s " S_COLOR_MAGENTA "%s",
prefix, string );
// Send to all appropriate clients
for( i = 0; i < level.maxclients; i++ )
if( G_admin_permission( &g_entities[ i ], ADMF_ADMINCHAT ) )
trap_SendServerCommand( i, va( "chat \"%s\"", outstring ) );
// Send to the logfile and server console
G_LogPrintf("adminmsg: %s\n", outstring );
}
/*
=================
Cmd_AdminMessage_f
Send a message to all active admins
=================
*/
void Cmd_AdminMessage_f( gentity_t *ent )
{
char cmd[ sizeof( "say_team" ) ];
char prefix[ 50 ];
char *msg;
int skiparg = 0;
// Check permissions and add the appropriate user [prefix]
if( !ent )
{
Com_sprintf( prefix, sizeof( prefix ), "[CONSOLE]:" );
}
else if( !G_admin_permission( ent, ADMF_ADMINCHAT ) )
{
if( !g_publicAdminMessages.integer )
{
ADMP( "Sorry, but use of /a by non-admins has been disabled.\n" );
return;
}
else
{
Com_sprintf( prefix, sizeof( prefix ), "[PLAYER] %s" S_COLOR_WHITE ":",
ent->client->pers.netname );
ADMP( "Your message has been sent to any available admins and to the server logs.\n" );
}
}
else
{
Com_sprintf( prefix, sizeof( prefix ), "[ADMIN] %s" S_COLOR_WHITE ":",
ent->client->pers.netname );
}
// Skip say/say_team if this was used from one of those
G_SayArgv( 0, cmd, sizeof( cmd ) );
if( !Q_stricmp( cmd, "say" ) || !Q_stricmp( cmd, "say_team" ) )
{
skiparg = 1;
G_SayArgv( 1, cmd, sizeof( cmd ) );
}
if( G_SayArgc( ) < 2 + skiparg )
{
ADMP( va( "usage: %s [message]\n", cmd ) );
return;
}
msg = G_SayConcatArgs( 1 + skiparg );
// Send it
G_AdminMessage( prefix, "%s", msg );
}
/*
==============
Cmd_Ignore_f
KK-OAX Removed Static to Keep in Mod Files
Currently Unused until I figure out how to implement it with voice chats.
==============
*/
/*void Cmd_Ignore_f( gentity_t *ent )
{
int pids[ MAX_CLIENTS ];
char name[ MAX_NAME_LENGTH ];
char cmd[ 9 ];
int matches = 0;
int i;
qboolean ignore = qfalse;
trap_Argv( 0, cmd, sizeof( cmd ) );
if( Q_stricmp( cmd, "ignore" ) == 0 )
ignore = qtrue;
if( trap_Argc() < 2 )
{
trap_SendServerCommand( ent-g_entities, va( "print \"[skipnotify]"
"usage: %s [clientNum | partial name match]\n\"", cmd ) );
return;
}
Q_strncpyz( name, ConcatArgs( 1 ), sizeof( name ) );
matches = G_ClientNumbersFromString( name, pids, MAX_CLIENTS );
if( matches < 1 )
{
trap_SendServerCommand( ent-g_entities, va( "print \"[skipnotify]"
"%s: no clients match the name '%s'\n\"", cmd, name ) );
return;
}
for( i = 0; i < matches; i++ )
{
if( ignore )
{
if( !BG_ClientListTest( &ent->client->pers.ignoreList, pids[ i ] ) )
{
BG_ClientListAdd( &ent->client->pers.ignoreList, pids[ i ] );
ClientUserinfoChanged( ent->client->ps.clientNum );
trap_SendServerCommand( ent-g_entities, va( "print \"[skipnotify]"
"ignore: added %s^7 to your ignore list\n\"",
level.clients[ pids[ i ] ].pers.netname ) );
}
else
{
trap_SendServerCommand( ent-g_entities, va( "print \"[skipnotify]"
"ignore: %s^7 is already on your ignore list\n\"",
level.clients[ pids[ i ] ].pers.netname ) );
}
}
else
{
if( BG_ClientListTest( &ent->client->pers.ignoreList, pids[ i ] ) )
{
BG_ClientListRemove( &ent->client->pers.ignoreList, pids[ i ] );
ClientUserinfoChanged( ent->client->ps.clientNum );
trap_SendServerCommand( ent-g_entities, va( "print \"[skipnotify]"
"unignore: removed %s^7 from your ignore list\n\"",
level.clients[ pids[ i ] ].pers.netname ) );
}
else
{
trap_SendServerCommand( ent-g_entities, va( "print \"[skipnotify]"
"unignore: %s^7 is not on your ignore list\n\"",
level.clients[ pids[ i ] ].pers.netname ) );
}
}
}
}
*/
/*
==================
G_ClientNumberFromString
Returns a player number for either a number or name string
Returns -1 if invalid
==================
*/
int G_ClientNumberFromString( char *s )
{
gclient_t *cl;
int i;
char s2[ MAX_NAME_LENGTH ];
char n2[ MAX_NAME_LENGTH ];
// numeric values are just slot numbers
for( i = 0; s[ i ] && isdigit( s[ i ] ); i++ );
if( !s[ i ] )
{
i = atoi( s );
if( i < 0 || i >= level.maxclients )
return -1;
cl = &level.clients[ i ];
if( cl->pers.connected == CON_DISCONNECTED )
return -1;
return i;
}
// check for a name match
G_SanitiseString( s, s2, sizeof( s2 ) );
for( i = 0, cl = level.clients; i < level.maxclients; i++, cl++ )
{
if( cl->pers.connected == CON_DISCONNECTED )
continue;
G_SanitiseString( cl->pers.netname, n2, sizeof( n2 ) );
if( !strcmp( n2, s2 ) )
return i;
}
return -1;
}
//KK-OAX Used to !spec999'ers
/*
=============
G_ClientIsLagging
=============
*/
qboolean G_ClientIsLagging( gclient_t *client )
{
if( client )
{
if( client->ps.ping >= 999 )
return qtrue;
else
return qfalse;
}
return qfalse; //is a non-existant client lagging? woooo zen
}
/*
==================
SanitizeString
Remove case and control characters
==================
*/
void SanitizeString( char *in, char *out ) {
while ( *in ) {
if ( *in == 27 ) {
in += 2; // skip color code
continue;
}
if ( *in < 32 ) {
in++;
continue;
}
*out++ = tolower( *in++ );
}
*out = 0;
}

1453
code/game/g_combat.c Normal file

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More