UFO: Alien Invasion
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
mathlib.h File Reference
#include "ufotypes.h"
#include "defines.h"
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include "vector.h"
#include "line.h"
#include "aabb.h"

Go to the source code of this file.

Data Structures

class  GridBox
 

Macros

#define M_PI   3.14159265358979323846 /* matches value in gcc v2 math.h */
 
#define M_PI_2   1.57079632679489661923 /* pi/2 */
 
#define EQUAL_EPSILON   0.001
 
#define EQUAL2(a, b, epsilon)   (fabs((a)-(b))<epsilon)
 
#define Q_ftol(f)   (long) (f)
 
#define torad   (M_PI/180.0f)
 
#define todeg   (180.0f/M_PI)
 
#define PITCH   0 /* rotation around y axis - up / down (-90 up to 90 degree) */
 
#define YAW   1 /* rotation around z axis - left / right (0 up to 360 degree) */
 
#define ROLL   2 /* rotation around x axis - fall over */
 
#define AXIS_FORWARD   0
 
#define AXIS_RIGHT   1
 
#define AXIS_UP   2
 
#define SIN_ALPHA   0.39875
 
#define COS_ALPHA   0.91706
 
#define HIGH_LAT   +1.0
 
#define LOW_LAT   -1.0
 
#define CENTER_LAT   0.0
 
#define SIZE_LAT   2.0
 
#define DIRECTIONS   8
 Number of angles from a position (2-dimensional) More...
 
#define BASE_DIRECTIONS   4 /* Only the standard N,S,E,W directions */
 Number of direct connected fields for a position. More...
 
#define PATHFINDING_DIRECTIONS   40 /* total number of directions */
 
#define CORE_DIRECTIONS   8 /* The standard N,S,E,W directions plus diagonals. */
 
#define FLYING_DIRECTIONS   16 /* starting number of directions available only to fliers */
 
#define VecToPos(v, p)
 Map boundary is +/- MAX_WORLD_WIDTH - to get into the positive area we add the possible max negative value and divide by the size of a grid unit field. More...
 
#define PosToVec(p, v)
 Pos boundary size is +/- 128 - to get into the positive area we add the possible max negative value and multiply with the grid unit size to get back the vector coordinates - now go into the middle of the grid field by adding the half of the grid unit size to this value. More...
 
#define DV_FLAGS_BIT_SHIFT   4
 
#define DV_DIR_BIT_SHIFT   8
 
#define DV_Z_BIT_MASK   0x0007
 
#define DV_FLAGS_BIT_MASK   0x00F0
 
#define DV_DIR_BIT_MASK   0xFF00
 
#define DV_FLAG_AUTOCROUCH   0x01
 
#define DV_FLAG_AUTOCROUCHED   0x02
 
#define DV_FLAG_AUTODIVE   0x04
 
#define makeDV(dir, z)   (((dir) << DV_DIR_BIT_SHIFT) | ((z) & DV_Z_BIT_MASK))
 
#define setDVz(dv, z)   (((dv) & (~DV_Z_BIT_MASK)) | ((z) & DV_Z_BIT_MASK))
 
#define getDVdir(dv)   ((dv) >> DV_DIR_BIT_SHIFT)
 
#define getDVflags(dv)   (((dv) & DV_FLAGS_BIT_MASK) >> DV_FLAGS_BIT_SHIFT)
 
#define getDVz(dv)   ((dv) & DV_Z_BIT_MASK)
 
#define PosAddDV(p, crouch, dv)   ((p)[0]+=dvecs[getDVdir(dv)][0], (p)[1]+=dvecs[getDVdir(dv)][1], (p)[2]=getDVz(dv), (crouch)+=dvecs[getDVdir(dv)][3])
 
#define PosSubDV(p, crouch, dv)   ((p)[0]-=dvecs[getDVdir(dv)][0], (p)[1]-=dvecs[getDVdir(dv)][1], (p)[2]=getDVz(dv), (crouch)-=dvecs[getDVdir(dv)][3])
 
#define AngleToDV(x)   (AngleToDir(x) << DV_DIR_BIT_SHIFT)
 

Typedefs

typedef short dvec_t
 The direction vector tells us where the actor came from (in his previous step). The pathing table holds about a million of these dvecs, so we save quite some memory by squeezing three pieces of information into a short value: More...
 

Functions

bool Q_IsPowerOfTwo (int i)
 Checks whether i is power of two value. More...
 
int AngleToDir (int angle)
 Returns the index of array directionAngles[DIRECTIONS] whose value is the closest to angle. More...
 
void VectorMA (const vec3_t veca, const float scale, const vec3_t vecb, vec3_t outVector)
 Sets vector_out (vc) to vevtor1 (va) + scale * vector2 (vb) More...
 
void VectorClampMA (vec3_t veca, float scale, const vec3_t vecb, vec3_t vecc)
 
void VectorMix (const vec3_t v1, const vec3_t v2, const float mix, vec3_t out)
 Calculate a position on v1 v2 line. More...
 
void MatrixMultiply (const vec3_t a[3], const vec3_t b[3], vec3_t c[3])
 Multiply 3*3 matrix by 3*3 matrix. More...
 
void GLMatrixAssemble (const vec3_t origin, const vec3_t angles, float *matrix)
 Builds an opengl translation and rotation matrix. More...
 
void GLMatrixMultiply (const float a[16], const float b[16], float c[16])
 Multiply 4*4 matrix by 4*4 matrix. More...
 
void GLVectorTransform (const float m[16], const vec4_t in, vec4_t out)
 Multiply 4*4 matrix by 4d vector. More...
 
void GLPositionTransform (const float m[16], const vec3_t in, vec3_t out)
 Transform position (xyz) vector by OpenGL rules. More...
 
void VectorRotate (vec3_t m[3], const vec3_t va, vec3_t vb)
 Rotate a vector with a rotation matrix. More...
 
void ClearBounds (vec3_t mins, vec3_t maxs)
 Sets mins and maxs to their starting points before using AddPointToBounds. More...
 
void AddPointToBounds (const vec3_t v, vec3_t mins, vec3_t maxs)
 If the point is outside the box defined by mins and maxs, expand the box to accommodate it. Sets mins and maxs to their new values. More...
 
int VectorCompareEps (const vec3_t v1, const vec3_t v2, float epsilon)
 Compare two vectors that may have an epsilon difference but still be the same vectors. More...
 
bool VectorNearer (const vec3_t v1, const vec3_t v2, const vec3_t comp)
 Checks whether the given vector v1 is closer to comp as the vector v2. More...
 
vec_t VectorLength (const vec3_t v)
 Calculate the length of a vector. More...
 
void CrossProduct (const vec3_t v1, const vec3_t v2, vec3_t cross)
 binary operation on vectors in a three-dimensional space More...
 
vec_t VectorNormalize (vec3_t v)
 Calculate unit vector for a given vec3_t. More...
 
void VectorNormalizeFast (vec3_t v)
 fast vector normalize routine that does not check to make sure that length != 0, nor does it return length More...
 
vec_t VectorNormalize2 (const vec3_t v, vec3_t out)
 Calculated the normal vector for a given vec3_t. More...
 
void VectorInverse (vec3_t v)
 Inverse a vector. More...
 
void VectorMidpoint (const vec3_t point1, const vec3_t point2, vec3_t midpoint)
 Calculates the midpoint between two vectors. More...
 
int Q_log2 (int val)
 
double GetDistanceOnGlobe (const vec2_t pos1, const vec2_t pos2)
 Calculate distance on the geoscape. More...
 
void VectorCalcMinsMaxs (const vec3_t center, const vec3_t size, vec3_t mins, vec3_t maxs)
 Calculates a bounding box from a center and a size. More...
 
float VectorAngleBetween (const vec3_t vec1, const vec3_t vec2)
 Calculates the angle (in radians) between the two given vectors. More...
 
void VecToAngles (const vec3_t vec, vec3_t angles)
 Converts a vector to an angle vector. More...
 
void VecToPolar (const vec3_t v, vec2_t a)
 Converts vector coordinates into polar coordinates. More...
 
void PolarToVec (const vec2_t a, vec3_t v)
 Converts longitude and latitude to a 3D vector in Euclidean coordinates. More...
 
void CalculateMinsMaxs (const vec3_t angles, const AABB &relBox, const vec3_t origin, AABB &absBox)
 Calculates the bounding box in absolute coordinates, also for rotating objects. WARNING: do not use this for angles other than 90, 180 or 270 !! More...
 
void VectorCreateRotationMatrix (const vec3_t angles, vec3_t matrix[3])
 
void VectorRotatePoint (vec3_t point, vec3_t matrix[3])
 
void AngleVectors (const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up)
 Create the rotation matrix in order to rotate something. More...
 
float AngleNormalize360 (float angle)
 returns angle normalized to the range [0 <= angle < 360] More...
 
float AngleNormalize180 (float angle)
 returns angle normalized to the range [-180 < angle <= 180] More...
 
float LerpAngle (float a1, float a2, float frac)
 Returns the angle resulting from turning fraction * angle from angle1 to angle2. More...
 
bool FrustumVis (const vec3_t origin, int dir, const vec3_t point)
 Checks whether a point is visible from a given position. More...
 
void PerpendicularVector (vec3_t dst, const vec3_t src)
 Finds a vector perpendicular to the source vector. More...
 
void RotatePointAroundVector (vec3_t dst, const vec3_t dir, const vec3_t point, float degrees)
 Rotate a point around a given vector. More...
 
float frand (void)
 Return random values between 0 and 1. More...
 
float crand (void)
 Return random values between -1 and 1. More...
 
void gaussrand (float *gauss1, float *gauss2)
 generate two gaussian distributed random numbers with median at 0 and stdev of 1 More...
 
vec_t Q_rint (const vec_t in)
 Round to nearest integer. More...
 
vec_t ColorNormalize (const vec3_t in, vec3_t out)
 
void TangentVectors (const vec3_t normal, const vec3_t sdir, const vec3_t tdir, vec4_t tangent, vec3_t binormal)
 Projects the normalized directional vectors on to the normal's plane. The fourth component of the resulting tangent vector represents sidedness. More...
 
void Orthogonalize (vec3_t v1, const vec3_t v2)
 Grahm-Schmidt orthogonalization. More...
 
void MatrixTranspose (const vec3_t m[3], vec3_t t[3])
 Transposes m and stores the result in t. More...
 
bool RayIntersectAABB (const vec3_t start, const vec3_t end, const AABB &aabb)
 

Variables

const vec4_t dvecs [PATHFINDING_DIRECTIONS]
 
const float dvecsn [CORE_DIRECTIONS][2]
 
const float directionAngles [CORE_DIRECTIONS]
 
const byte dvright [CORE_DIRECTIONS]
 
const byte dvleft [CORE_DIRECTIONS]
 

Macro Definition Documentation

#define AngleToDV (   x)    (AngleToDir(x) << DV_DIR_BIT_SHIFT)

Definition at line 257 of file mathlib.h.

Referenced by CL_ActorTurnMouse().

#define AXIS_FORWARD   0

Definition at line 59 of file mathlib.h.

Referenced by S_Frame().

#define AXIS_RIGHT   1

Definition at line 60 of file mathlib.h.

Referenced by S_Frame().

#define AXIS_UP   2

Definition at line 61 of file mathlib.h.

Referenced by S_Frame().

#define BASE_DIRECTIONS   4 /* Only the standard N,S,E,W directions */

Number of direct connected fields for a position.

See also
DIRECTIONS.

Definition at line 84 of file mathlib.h.

Referenced by LE_ActorGetStepTime().

#define CENTER_LAT   0.0

Definition at line 69 of file mathlib.h.

#define COS_ALPHA   0.91706

Definition at line 66 of file mathlib.h.

Referenced by uiGeoscapeNode::calcAndUploadDayAndNightTexture(), and GEO_IsNight().

#define DIRECTIONS   8

Number of angles from a position (2-dimensional)

See also
dvecs (in q_shared.c) for a description of its use.
AngleToDV.
BASE_DIRECTIONS

Definition at line 78 of file mathlib.h.

Referenced by FrustumVis().

#define DV_DIR_BIT_MASK   0xFF00

The mask to retrieve the dir component of a DV value

Definition at line 241 of file mathlib.h.

#define DV_DIR_BIT_SHIFT   8

This is the bit shift needed to store the dir component of a DV value

Definition at line 238 of file mathlib.h.

#define DV_FLAG_AUTOCROUCH   0x01

Definition at line 243 of file mathlib.h.

Referenced by Step::checkWalkingDirections().

#define DV_FLAG_AUTOCROUCHED   0x02

Definition at line 244 of file mathlib.h.

Referenced by Step::checkWalkingDirections().

#define DV_FLAG_AUTODIVE   0x04

Definition at line 245 of file mathlib.h.

Referenced by Step::checkWalkingDirections().

#define DV_FLAGS_BIT_MASK   0x00F0

The mask to retrieve the 'how' component of a DV value

Definition at line 240 of file mathlib.h.

#define DV_FLAGS_BIT_SHIFT   4

This is the bit shift needed to store the 'how' component of a DV value

Definition at line 237 of file mathlib.h.

#define DV_Z_BIT_MASK   0x0007

The mask to retrieve the z component of a DV value

Definition at line 239 of file mathlib.h.

#define EQUAL2 (   a,
  b,
  epsilon 
)    (fabs((a)-(b))<epsilon)

Definition at line 45 of file mathlib.h.

#define FLYING_DIRECTIONS   16 /* starting number of directions available only to fliers */
#define getDVdir (   dv)    ((dv) >> DV_DIR_BIT_SHIFT)
#define getDVflags (   dv)    (((dv) & DV_FLAGS_BIT_MASK) >> DV_FLAGS_BIT_SHIFT)

Definition at line 250 of file mathlib.h.

Referenced by Step::checkWalkingDirections(), and TEST_F().

#define getDVz (   dv)    ((dv) & DV_Z_BIT_MASK)

Definition at line 251 of file mathlib.h.

Referenced by HUD_MapDebugCursor(), and TEST_F().

#define HIGH_LAT   +1.0

Definition at line 67 of file mathlib.h.

Referenced by uiGeoscapeNode::calcAndUploadDayAndNightTexture().

#define LOW_LAT   -1.0

Definition at line 68 of file mathlib.h.

Referenced by uiGeoscapeNode::calcAndUploadDayAndNightTexture().

#define M_PI_2   1.57079632679489661923 /* pi/2 */

Definition at line 37 of file mathlib.h.

Referenced by Weather::setDefaults().

#define makeDV (   dir,
 
)    (((dir) << DV_DIR_BIT_SHIFT) | ((z) & DV_Z_BIT_MASK))

Definition at line 247 of file mathlib.h.

Referenced by G_EventActorFall(), Grid_SetMoveData(), and TEST_F().

#define PATHFINDING_DIRECTIONS   40 /* total number of directions */
#define PosAddDV (   p,
  crouch,
  dv 
)    ((p)[0]+=dvecs[getDVdir(dv)][0], (p)[1]+=dvecs[getDVdir(dv)][1], (p)[2]=getDVz(dv), (crouch)+=dvecs[getDVdir(dv)][3])
#define PosSubDV (   p,
  crouch,
  dv 
)    ((p)[0]-=dvecs[getDVdir(dv)][0], (p)[1]-=dvecs[getDVdir(dv)][1], (p)[2]=getDVz(dv), (crouch)-=dvecs[getDVdir(dv)][3])
#define PosToVec (   p,
  v 
)
Value:
( \
(v)[0] = ((int)(p)[0] - GRID_WIDTH) * UNIT_SIZE + UNIT_SIZE / 2, \
(v)[1] = ((int)(p)[1] - GRID_WIDTH) * UNIT_SIZE + UNIT_SIZE / 2, \
(v)[2] = (int)(p)[2] * UNIT_HEIGHT + UNIT_HEIGHT / 2 \
)
#define UNIT_HEIGHT
Definition: defines.h:122
#define GRID_WIDTH
absolute max - -GRID_WIDTH up tp +GRID_WIDTH
Definition: defines.h:290
#define UNIT_SIZE
Definition: defines.h:121
QGL_EXTERN int GLboolean GLfloat * v
Definition: r_gl.h:120

Pos boundary size is +/- 128 - to get into the positive area we add the possible max negative value and multiply with the grid unit size to get back the vector coordinates - now go into the middle of the grid field by adding the half of the grid unit size to this value.

See also
PATHFINDING_WIDTH

Definition at line 110 of file mathlib.h.

Referenced by CL_ActorMouseTrace(), CL_CameraRoute(), CL_ViewCenterAtGridPosition(), G_ActorSpawn(), MapTile::getTileBox(), LE_PlayFootStepSound(), LE_PlaySoundFileAndParticleForSurface(), AiAreaSearch::plotPos(), pos3L_distance(), RT_GetMapSize(), and TEST_F().

#define Q_ftol (   f)    (long) (f)

Definition at line 48 of file mathlib.h.

Referenced by CIN_ROQ_Init().

#define ROLL   2 /* rotation around x axis - fall over */
#define setDVz (   dv,
 
)    (((dv) & (~DV_Z_BIT_MASK)) | ((z) & DV_Z_BIT_MASK))

Definition at line 248 of file mathlib.h.

Referenced by G_FillDirectionTable(), and TEST_F().

#define SIN_ALPHA   0.39875
#define SIZE_LAT   2.0

Definition at line 70 of file mathlib.h.

#define VecToPos (   v,
 
)
Value:
( \
(p)[0] = ((int)(v)[0] + MAX_WORLD_WIDTH) / UNIT_SIZE, \
(p)[1] = ((int)(v)[1] + MAX_WORLD_WIDTH) / UNIT_SIZE, \
(p)[2] = std::min((PATHFINDING_HEIGHT - 1), ((int)(v)[2] / UNIT_HEIGHT)) \
)
#define UNIT_HEIGHT
Definition: defines.h:122
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
#define UNIT_SIZE
Definition: defines.h:121
#define PATHFINDING_HEIGHT
15 max, adjusting above 8 will require a rewrite to the DV code
Definition: defines.h:294
#define MAX_WORLD_WIDTH
-MAX_WORLD_WIDTH up tp +MAX_WORLD_WIDTH
Definition: defines.h:288
QGL_EXTERN int GLboolean GLfloat * v
Definition: r_gl.h:120

Map boundary is +/- MAX_WORLD_WIDTH - to get into the positive area we add the possible max negative value and divide by the size of a grid unit field.

Definition at line 100 of file mathlib.h.

Referenced by CL_ActorMouseTrace(), CL_AddBrushModel(), CL_CheckCameraRoute(), CL_MoveView(), DoRouting(), G_BuildForbiddenListForEntity(), G_InitCamera(), G_ShootGrenade(), G_ShootSingle(), G_ShotMorale(), G_SpawnEntities(), G_SpawnFieldPart(), G_SpawnParticle(), GridBox::GridBox(), LE_CenterView(), GridBox::set(), GridBox::setFromMapBounds(), TEST_F(), and Think_NextMapTrigger().

Typedef Documentation

typedef short dvec_t

The direction vector tells us where the actor came from (in his previous step). The pathing table holds about a million of these dvecs, so we save quite some memory by squeezing three pieces of information into a short value:

  • the direction he took to get here
  • the z-level he came from
  • how he moved. There are three special crouching conditions – autocrouch: standing upright in the previous cell, now crouch and stay crouched – autocrouched: being already autocrouched in the previous cell, stand up if you get the chance – autodive: we can stand in both cells, but there is just a small hole in the wall between them

Definition at line 236 of file mathlib.h.

Function Documentation

void AddPointToBounds ( const vec3_t  v,
vec3_t  mins,
vec3_t  maxs 
)

If the point is outside the box defined by mins and maxs, expand the box to accommodate it. Sets mins and maxs to their new values.

Definition at line 1042 of file mathlib.cpp.

References i.

Referenced by SL_BSPSlice(), and WindingBounds().

float AngleNormalize180 ( float  angle)

returns angle normalized to the range [-180 < angle <= 180]

Parameters
[in]angleAngle

Definition at line 1004 of file mathlib.cpp.

References AngleNormalize360().

float AngleNormalize360 ( float  angle)

returns angle normalized to the range [0 <= angle < 360]

Parameters
[in]angleAngle
See also
VecToAngles

Definition at line 995 of file mathlib.cpp.

References int().

Referenced by AngleNormalize180().

int AngleToDir ( int  angle)

Returns the index of array directionAngles[DIRECTIONS] whose value is the closest to angle.

Note
This function allows to know the closest multiple of 45 degree of angle.
Parameters
[in]angleThe angle (in degrees) which is tested.
Returns
Corresponding index of array directionAngles[DIRECTIONS].

Definition at line 130 of file mathlib.cpp.

References Com_Printf(), and CORE_DIRECTIONS.

Referenced by AIL_positionwander(), G_Actor2x2Spawn(), G_ActorSpawn(), G_ClientShoot(), G_GetImpactDirection(), G_InitCamera(), and fireDef_s::getShotOrigin().

void AngleVectors ( const vec3_t  angles,
vec3_t  forward,
vec3_t  right,
vec3_t  up 
)

Create the rotation matrix in order to rotate something.

Parameters
[in]anglesContains the three angles PITCH, YAW and ROLL (in degree) of rotation around idle frame ({0, 1, 0}, {0, 0, 1} ,{1, 0, 0}) (in this order!)
[out]forwardreturn the first line of the rotation matrix.
[out]rightreturn the second line of the rotation matrix.
[out]upreturn the third line of the rotation matrix.
Note
This matrix is the product of the 3 matrixes R*P*Y (in this order!), where R is the rotation matrix around {1, 0, 0} only (angle of rotation is angle[2]), P is the rotation matrix around {0, 1, 0} only, and Y is the rotation matrix around {0, 0, 1}.
Due to z convention for Quake, the z-axis is inverted. Therefore, if you want to use this function in a direct frame, don't forget to inverse the second line (right). Exemple : to rotate v2 into v : AngleVectors(angles, m[0], m[1], m[2]); VectorInverse(m[1]); VectorRotate(m, v2, v);
See also
RotatePointAroundVector : If you need rather "one rotation around a vector you choose" instead of "3 rotations around 3 vectors you don't choose".

Definition at line 631 of file mathlib.cpp.

References PITCH, ROLL, torad, and YAW.

Referenced by BuildLights(), CL_CameraMove(), CM_HintedTransformedBoxTrace(), Door_SlidingUse(), G_ShootGrenade(), G_ShootSingle(), GLMatrixAssemble(), LET_SlideDoor(), R_CullMeshModel(), R_GetSpriteVectors(), R_SetupFrustum(), SEQ_SetCamera(), SP_worldspawn(), U2M_SetDefaultConfigValues(), and VectorCreateRotationMatrix().

void CalculateMinsMaxs ( const vec3_t  angles,
const AABB relBox,
const vec3_t  origin,
AABB absBox 
)

Calculates the bounding box in absolute coordinates, also for rotating objects. WARNING: do not use this for angles other than 90, 180 or 270 !!

Definition at line 546 of file mathlib.cpp.

References AABB::getCenter(), m, AABB::maxs, AABB::set(), AABB::shift(), VectorAdd, VectorCreateRotationMatrix(), VectorNotEmpty, VectorRotate(), and VectorSubtract.

Referenced by CM_GetInlineModelAABB(), Grid_RecalcRouting(), LE_AddEdictHighlight(), and SV_LinkEdict().

void ClearBounds ( vec3_t  mins,
vec3_t  maxs 
)

Sets mins and maxs to their starting points before using AddPointToBounds.

See also
AddPointToBounds

Definition at line 1032 of file mathlib.cpp.

Referenced by WindingBounds().

vec_t ColorNormalize ( const vec3_t  in,
vec3_t  out 
)

Definition at line 190 of file mathlib.cpp.

References EQUAL, f, VectorClear, and VectorScale.

Referenced by BuildLights(), SP_worldspawn(), and U2M_SetDefaultConfigValues().

float crand ( void  )

Return random values between -1 and 1.

See also
frand
gaussrand

Definition at line 517 of file mathlib.cpp.

Referenced by AI_HideNeeded(), AIR_PilotSurvivedCrash(), CL_ParticleFunction(), G_ClientShoot(), G_ShootSingle(), gaussrand(), LE_AddGrenade(), and Weather::update().

void CrossProduct ( const vec3_t  v1,
const vec3_t  v2,
vec3_t  cross 
)

binary operation on vectors in a three-dimensional space

Note
also known as the vector product or outer product
It differs from the dot product in that it results in a vector rather than in a scalar
Its main use lies in the fact that the cross product of two vectors is orthogonal to both of them.
Parameters
[in]v1directional vector
[in]v2directional vector
[out]crossoutput
Note
you have the right and forward values of an axis, their cross product will
be a properly oriented "up" direction
See also
DotProduct
VectorNormalize2

Definition at line 820 of file mathlib.cpp.

Referenced by AddBrushBevels(), AIR_GetDestinationWhilePursuing(), BaseWindingForPlane(), Check_EdgeEdgeIntersection(), GEO_AngleOfPath2D(), GEO_AngleOfPath3D(), GEO_CalcLine(), PlaneFromPoints(), R_GenerateGrass(), R_GetSpriteVectors(), R_ModCalcNormalsAndTangents(), R_ModCalcUniqueNormalsAndTangents(), R_PlantGrass(), RotatePointAroundVector(), TangentVectors(), TryMergeWinding(), and WindingArea().

bool FrustumVis ( const vec3_t  origin,
int  dir,
const vec3_t  point 
)

Checks whether a point is visible from a given position.

Parameters
[in]originOrigin to test from
[in]dirDirection to test into
[in]pointThis is the point we want to check the visibility for

Definition at line 666 of file mathlib.cpp.

References DIRECTIONS, dvecsn, and VectorNormalizeFast().

Referenced by G_FrustumVis().

void gaussrand ( float *  gauss1,
float *  gauss2 
)

generate two gaussian distributed random numbers with median at 0 and stdev of 1

Parameters
[out]gauss1First gaussian distributed random number
[out]gauss2Second gaussian distributed random number
See also
crand
frand

Definition at line 529 of file mathlib.cpp.

References crand(), and logf.

Referenced by G_ShootGrenade(), G_ShootSingle(), and UFO_SetRandomDestAround().

double GetDistanceOnGlobe ( const vec2_t  pos1,
const vec2_t  pos2 
)

Calculate distance on the geoscape.

Parameters
[in]pos1Position at the start.
[in]pos2Position at the end.
Returns
Distance from pos1 to pos2.
Note
distance is an angle! This is the angle (in degrees) between the 2 vectors starting at earth's center and ending at pos1 or pos2. (if you prefer distance, this is also the distance on a globe of radius 180 / pi = 57)

Definition at line 171 of file mathlib.cpp.

References todeg, and torad.

Referenced by AB_SetAlienBasePosition(), AB_UpdateStealthForOneBase(), AIR_AircraftHasEnoughFuel(), AIR_AircraftHasEnoughFuelOneWay(), AIR_GetDestinationWhilePursuing(), AIR_SortByDistance(), AIRFIGHT_BaseShoot(), AIRFIGHT_ChooseWeapon(), AIRFIGHT_InstallationShoot(), AIRFIGHT_MissTarget(), AIRFIGHT_ProjectileReachedTarget(), BDEF_AutoTarget(), CL_DisplayPopupInterceptMission(), CP_DrawXVIOverlayPixel(), GEO_GetAircraftText(), GEO_PositionCloseToBase(), PR_CalculateTotalFrames(), RADAR_AddDetectedUFOToEveryRadar(), RADAR_CheckRadarSensored(), RADAR_CheckUFOSensored(), TR_TransferStart(), UFO_CampaignCheckEvents(), UFO_SearchAircraftTarget(), UFO_UpdateAlienInterestForOneBase(), UFO_UpdateAlienInterestForOneInstallation(), and US_GetClosestStoredUFO().

void GLMatrixAssemble ( const vec3_t  origin,
const vec3_t  angles,
float *  matrix 
)

Builds an opengl translation and rotation matrix.

Parameters
originThe translation vector
anglesThe angle vector that is used to calculate the rotation part of the matrix
matrixThe resulting matrix, must be of dimension 16

Definition at line 325 of file mathlib.cpp.

References AngleVectors(), and VectorInverse().

Referenced by CL_ActorGetMuzzle(), and R_CalcTransform().

void GLMatrixMultiply ( const float  a[16],
const float  b[16],
float  c[16] 
)

Multiply 4*4 matrix by 4*4 matrix.

See also
MatrixMultiply
Parameters
[out]cThe result of the multiplication matrix = a * b (not the same as b * a as matrix multiplication is not commutative)
[in]aFirst matrix.
[in]bSecond matrix.

Definition at line 350 of file mathlib.cpp.

References i.

Referenced by CL_ActorGetMuzzle(), and R_CalcTransform().

void GLPositionTransform ( const float  m[16],
const vec3_t  in,
vec3_t  out 
)

Transform position (xyz) vector by OpenGL rules.

Note
Equivalent to calling GLVectorTransfrom with (x y z 1) vector and taking first 3 components of result
Parameters
[out]outthe result of the multiplication = m * in.
[in]m4*4 matrix
[in]in3d vector.
See also
GLVectorTransform

Definition at line 380 of file mathlib.cpp.

References i.

Referenced by R_EnableModelLights(), and R_EnableWorldLights().

void GLVectorTransform ( const float  m[16],
const vec4_t  in,
vec4_t  out 
)

Multiply 4*4 matrix by 4d vector.

Parameters
[out]outthe result of the multiplication = m * in.
[in]m4*4 matrix
[in]in4d vector.
See also
VectorRotate

Definition at line 366 of file mathlib.cpp.

References i.

Referenced by R_InitModelProgram(), and R_UseModelProgram().

float LerpAngle ( float  a1,
float  a2,
float  frac 
)

Returns the angle resulting from turning fraction * angle from angle1 to angle2.

Definition at line 981 of file mathlib.cpp.

void MatrixMultiply ( const vec3_t  a[3],
const vec3_t  b[3],
vec3_t  c[3] 
)

Multiply 3*3 matrix by 3*3 matrix.

Parameters
[out]cThe result of the multiplication matrix = a * b (not the same as b * a !)
[in]aFirst matrix.
[in]bSecond matrix.
See also
GLMatrixMultiply

Definition at line 304 of file mathlib.cpp.

void MatrixTranspose ( const vec3_t  m[3],
vec3_t  t[3] 
)

Transposes m and stores the result in t.

Parameters
[in]mThe matrix to transpose
[out]tThe transposed matrix

Definition at line 1101 of file mathlib.cpp.

References i.

void Orthogonalize ( vec3_t  out,
const vec3_t  in 
)

Grahm-Schmidt orthogonalization.

Parameters
[out]outOrthogonalized vector
[in]inReference vector

Definition at line 1088 of file mathlib.cpp.

References DotProduct, VectorMul, VectorNormalizeFast(), and VectorSubtract.

Referenced by R_ModCalcNormalsAndTangents(), and R_ModCalcUniqueNormalsAndTangents().

void PerpendicularVector ( vec3_t  dst,
const vec3_t  src 
)

Finds a vector perpendicular to the source vector.

Parameters
[in]srcThe source vector
[out]dstA vector perpendicular to src
Note
dst is a perpendicular vector to src such that it is the closest to one of the three axis: {1,0,0}, {0,1,0} and {0,0,1} (chosen in that order in case of equality)
Precondition
non-nullptr pointers and src is normalized
See also
ProjectPointOnPlane

Definition at line 780 of file mathlib.cpp.

References i, ProjectPointOnPlane(), and VectorNormalizeFast().

Referenced by GEO_MapDrawEquidistantPoints(), and RotatePointAroundVector().

void PolarToVec ( const vec2_t  a,
vec3_t  v 
)

Converts longitude and latitude to a 3D vector in Euclidean coordinates.

Parameters
[in]aThe longitude and latitude in a 2D vector
[out]vThe resulting normal 3D vector
See also
VecToPolar

Definition at line 910 of file mathlib.cpp.

References torad, and VectorSet.

Referenced by AIR_GetDestinationWhilePursuing(), AIRFIGHT_GetNextPointInPathFromVector(), GEO_3DMapToScreen(), GEO_AngleOfPath2D(), GEO_AngleOfPath3D(), GEO_CalcLine(), GEO_MapDrawEquidistantPoints(), and R_PlantGrass().

bool Q_IsPowerOfTwo ( int  i)

Checks whether i is power of two value.

Definition at line 972 of file mathlib.cpp.

Referenced by CIN_ROQ_DecodeInfo(), and R_CvarCheckMaxLightmap().

int Q_log2 ( int  val)

Definition at line 492 of file mathlib.cpp.

vec_t Q_rint ( const vec_t  in)

Round to nearest integer.

Definition at line 156 of file mathlib.cpp.

Referenced by GetVertexnum(), and SnapPlane().

bool RayIntersectAABB ( const vec3_t  start,
const vec3_t  end,
const AABB aabb 
)

Definition at line 1110 of file mathlib.cpp.

References f, i, AABB::maxs, AABB::mins, and VectorSubtract.

Referenced by G_SmokeVis(), and G_TeamPointVis().

void RotatePointAroundVector ( vec3_t  dst,
const vec3_t  dir,
const vec3_t  point,
float  degrees 
)

Rotate a point around a given vector.

Parameters
[in]dirThe vector around which to rotate
[in]pointThe point to be rotated
[in]degreesHow many degrees to rotate the point by
[out]dstThe point after rotation
Note
Warning: dst must be different from point (otherwise the result has no meaning)
Precondition
dir must be normalized

Definition at line 849 of file mathlib.cpp.

References CrossProduct(), DotProduct, i, m, OBJZERO, PerpendicularVector(), R_ConcatRotations(), and torad.

Referenced by AIR_GetDestinationWhilePursuing(), AIRFIGHT_GetNextPointInPathFromVector(), GEO_3DMapToScreen(), GEO_AngleOfPath2D(), GEO_AngleOfPath3D(), GEO_MapDrawEquidistantPoints(), R_PlantGrass(), R_RotateCelestialBody(), R_SetupFrustum(), and uiGeoscapeNode::screenTo3DMap().

void TangentVectors ( const vec3_t  normal,
const vec3_t  sdir,
const vec3_t  tdir,
vec4_t  tangent,
vec3_t  binormal 
)

Projects the normalized directional vectors on to the normal's plane. The fourth component of the resulting tangent vector represents sidedness.

Definition at line 1057 of file mathlib.cpp.

References CrossProduct(), DotProduct, VectorCopy, VectorMA(), VectorNormalizeFast(), and VectorScale.

Referenced by BuildFacelights(), and R_LoadBspVertexArrays().

void VecToAngles ( const vec3_t  value1,
vec3_t  angles 
)

Converts a vector to an angle vector.

Parameters
[in]value1
[in]anglesTarget vector for pitch, yaw, roll
See also
anglemod

Definition at line 934 of file mathlib.cpp.

References EQUAL, f, PITCH, ROLL, todeg, Vector2Empty, and YAW.

Referenced by G_ShootGrenade(), G_ShootSingle(), LE_AddProjectile(), and LET_Projectile().

void VecToPolar ( const vec3_t  v,
vec2_t  a 
)

Converts vector coordinates into polar coordinates.

See also
PolarToVec

Definition at line 922 of file mathlib.cpp.

References todeg.

Referenced by AIR_GetDestinationWhilePursuing(), AIRFIGHT_GetNextPointInPathFromVector(), GEO_CalcLine(), GEO_MapDrawEquidistantPoints(), and uiGeoscapeNode::screenTo3DMap().

float VectorAngleBetween ( const vec3_t  vec1,
const vec3_t  vec2 
)

Calculates the angle (in radians) between the two given vectors.

Note
Both vectors must be normalized.
Returns
the angle in radians.

Definition at line 484 of file mathlib.cpp.

References DotProduct.

Referenced by G_GetImpactDirection().

void VectorCalcMinsMaxs ( const vec3_t  center,
const vec3_t  size,
vec3_t  mins,
vec3_t  maxs 
)

Calculates a bounding box from a center and a size.

Parameters
[in]centerThe center vector
[in]sizeThe size vector to calculate the bbox
[out]minsThe lower end of the bounding box
[out]maxsThe upper end of the bounding box

Definition at line 1019 of file mathlib.cpp.

References i, and length.

void VectorClampMA ( vec3_t  veca,
float  scale,
const vec3_t  vecb,
vec3_t  vecc 
)

Definition at line 268 of file mathlib.cpp.

References f, i, and VectorMA().

int VectorCompareEps ( const vec3_t  v1,
const vec3_t  v2,
float  epsilon 
)

Compare two vectors that may have an epsilon difference but still be the same vectors.

Parameters
[in]v1vector to compare with v2
[in]v2vector to compare with v1
[in]epsilonThe epsilon the vectors may differ to still be the same
Returns
1 if the 2 vectors are the same (less than epsilon difference).
Note
This is not an exact calculation (should use a sqrt). Use this function only if you want to know if both vectors are the same with a precison that is roughly epsilon (the difference should be lower than sqrt(3) * epsilon).

Definition at line 413 of file mathlib.cpp.

References VectorSubtract.

Referenced by CL_CameraRoute(), CP_InterceptAttackInstallation(), CP_InterceptMissionLeave(), PTL_Trace(), TR_TestLineDM(), and TR_TileTestLineDM().

void VectorCreateRotationMatrix ( const vec3_t  angles,
vec3_t  matrix[3] 
)
Parameters
anglesThe angles to calulcate the rotation matrix for
matrixThe resulting rotation matrix. The right part of this matrix is inversed because of the coordinate system we are using internally.
See also
AnglesVectors
VectorRotatePoint

Definition at line 592 of file mathlib.cpp.

References AngleVectors(), and VectorInverse().

Referenced by CalculateMinsMaxs(), Grid_RecalcRouting(), and AABB::rotateAround().

void VectorInverse ( vec3_t  v)

Inverse a vector.

Parameters
[in,out]vVector to inverse. Output value is -v.

Definition at line 460 of file mathlib.cpp.

Referenced by GLMatrixAssemble(), R_PlantGrass(), and VectorCreateRotationMatrix().

void VectorMidpoint ( const vec3_t  point1,
const vec3_t  point2,
vec3_t  midpoint 
)

Calculates the midpoint between two vectors.

Parameters
[in]point1vector of first point.
[in]point2vector of second point.
[out]midpointcalculated midpoint vector.

Definition at line 473 of file mathlib.cpp.

References f, VectorAdd, and VectorScale.

void VectorMix ( const vec3_t  v1,
const vec3_t  v2,
float  mix,
vec3_t  out 
)

Calculate a position on v1 v2 line.

Parameters
[in]v1First point of the line.
[in]v2Second point of the line.
[in]mixPosition on the line. If 0 < mix < 1, out is between v1 and v2 . if mix < 0, out is outside v1 and v2 , on v1 side.
[out]outThe resulting point

Definition at line 447 of file mathlib.cpp.

Referenced by FinalLightFace(), GatherSampleLight(), GatherSampleSunlight(), and S_LoopSample().

bool VectorNearer ( const vec3_t  v1,
const vec3_t  v2,
const vec3_t  comp 
)

Checks whether the given vector v1 is closer to comp as the vector v2.

Parameters
[in]v1Vector to check whether it's closer to comp as v2
[in]v2Vector to check against
[in]compThe vector to check the distance from
Returns
Returns true if v1 is closer to comp as v2

Definition at line 219 of file mathlib.cpp.

References VectorLength(), and VectorSubtract.

Referenced by TR_TestLineDist_r(), TR_TestLineDM(), and TR_TileTestLineDM().

vec_t VectorNormalize2 ( const vec3_t  v,
vec3_t  out 
)

Calculated the normal vector for a given vec3_t.

Parameters
[in]vVector to normalize
[out]outThe normalized vector
See also
VectorNormalize
Returns
vector length as vec_t
See also
CrossProduct
Todo:

Definition at line 237 of file mathlib.cpp.

References DotProduct, EQUAL, f, and length.

Referenced by CL_CameraMove(), and R_SphereGenerate().

void VectorNormalizeFast ( vec3_t  v)
void VectorRotate ( vec3_t  m[3],
const vec3_t  va,
vec3_t  vb 
)

Rotate a vector with a rotation matrix.

Parameters
[out]vbThe result of multiplication (ie vector va after rotation).
[in]mThe 3*3 matrix (rotation matrix in case of a rotation).
[in]vaThe vector that should be multiplied (ie rotated in case of rotation).
Note
Basically, this is just the multiplication of m * va: this is the same than GLVectorTransform in 3D. This can be used for other applications than rotation.
See also
GLVectorTransform

Definition at line 395 of file mathlib.cpp.

Referenced by CalculateMinsMaxs(), Grid_RecalcRouting(), R_PlantGrass(), and AABB::rotateAround().

void VectorRotatePoint ( vec3_t  point,
vec3_t  matrix[3] 
)
Parameters
[out]pointThe vector to rotate around and the location of the rotated vector
[in]matrixThe input rotation matrix
See also
VectorCreateRotationMatrix

Definition at line 603 of file mathlib.cpp.

References DotProduct, and VectorCopy.

Variable Documentation

const float directionAngles[CORE_DIRECTIONS]
Note
if you change directionAngles[PATHFINDING_DIRECTIONS], you must also change function AngleToDV

Definition at line 105 of file mathlib.cpp.

Referenced by CL_ActorAppear(), CL_ActorDoTurn(), CL_CameraAppear(), G_ActorDoTurn(), LE_DoPathMove(), and UI_RadarNodeDrawActor().

Note
DIRECTIONS straight 0 = x+1, y 1 = x-1, y 2 = x , y+1 3 = x , y-1 diagonal 4 = x+1, y+1 5 = x-1, y-1 6 = x-1, y+1 7 = x+1, y-1
(change in x, change in y, change in z, change in height status)

Definition at line 58 of file mathlib.cpp.

Referenced by Step::calcNewPos(), CMod_RerouteMap(), G_GetImpactDirection(), fireDef_s::getShotOrigin(), and RT_UpdateConnectionColumn().

const float dvecsn[CORE_DIRECTIONS][2]

Definition at line 102 of file mathlib.cpp.

Referenced by FrustumVis().

const byte dvleft[CORE_DIRECTIONS]

Definition at line 119 of file mathlib.cpp.

Referenced by AIL_positionwander(), and G_ActorDoTurn().

const byte dvright[CORE_DIRECTIONS]

Definition at line 116 of file mathlib.cpp.

Referenced by AIL_positionwander(), and G_ActorDoTurn().