Auxiliary Math Library function reference

By NWShacker, version 2.0

////////////////////////////////////////////////////////////////////////////////
//:: math_include.nss
//:: AML main include file
//::
//:: This file is part of "Auxiliary Math Library" project by NWShacker
//:: Version 2.0
////////////////////////////////////////////////////////////////////////////////

#include "math_include_b"
#include "math_include_l"
#include "math_include_g"
#include "math_include_v"

////////////////////////////////////////////////////////////////////////////////
//:: math_include_b.nss
//:: AML base math include file
//::
//:: This file is part of "Auxiliary Math Library" project by NWShacker
//:: Version 2.0
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// CONSTANTS ///////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Maximum integer value that doesn't cause overflow (+/- 2^31-1).
const int MATH_INT_MAX = 2147483647;
// Maximum integer value that can be exactly represented as float (+/- 2^24).
const int MATH_INT_SAFE = 16777216;
// Euler's constant (natural logarithm base).
const float MATH_E = 2.71828182846;

////////////////////////////////////////////////////////////////////////////////
// RANDOM SAMPLE FUNCTIONS /////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Samples random int from uniform distribution over iMin (inclusive) and iMax
// (exclusive) range. Bounds may be negative. They are also automatically sorted
// to correct order. This function overcomes the limitations of vanilla NWN's
// PRNG, which can only generate numbers from either (-32768, 0] or [0, 32768)
// ranges. It is also efficient: it performs only four vanilla NWN Random calls.
// -iMin: lower bound
// -iMax: upper bound
// Return value: generated random int between iMin and iMax - 1.
int MATH_RandInt(int iMin, int iMax);

// Samples random float from uniform distribution over iMin and iMax range (both
// (bounds inclusive). Ends may be negative. They are also automatically sorted
// to correct order. Caveat: there is no uniformity guarantee if the absolute
// value of iMin or iMax (or their difference) is larger than 2^24 (16 777 216).
// -fMin: lower bound
// -fMax: upper bound
// Return value: generated random float between fMin and fMax.
float MATH_RandUniform(float fMin, float fMax);

// Samples random float from normal (Gaussian or "bell curve") distribution with
// mean fMean and standard deviation fStandardDeviation. Because this function
// is an implementation of Marsaglia polar method, it contains a loop that calls
// MATH_RandUniform twice per iteration. This loop normally terminates quickly,
// but in some very rare cases it may not. Therefore exerting caution is advised
// when calling this function in loops.
// -fMean: mean (expected value)
// -fStandardDeviation: standard deviation (may be negative)
// Return value: generated random value or fMean if fStandardDeviation is zero.
float MATH_RandNormal(float fMean, float fStandardDeviation);

////////////////////////////////////////////////////////////////////////////////
// ROUNDING FUNCTIONS //////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Truncates fFloat towards zero to nearest integer.
// -fFloat: float to truncate
// Return value: truncated fFloat.
float MATH_TruncFloat(float fFloat);

// Truncates components of vVector towards zero to nearest integers.
// -vVector: vector to truncate
// -iChangeZ: if set to FALSE, Z component of vVector is not modified
// Return value: vector of MATH_TruncFloat results for components of vVector.
vector MATH_TruncVector(vector vVector, int iChangeZ=TRUE);

// Rounds fFloat towards nearest integer (up or down).
// -fFloat: float to round
// Return value: rounded fFloat.
float MATH_RoundFloat(float fFloat);

// Rounds components of vVector towards nearest integers (up or down).
// -vVector: vector to round
// -iChangeZ: if set to FALSE, Z component of vVector is not modified
// Return value: vector of MATH_RoundFloat results for components of vVector.
vector MATH_RoundVector(vector vVector, int iChangeZ=TRUE);

// Rounds fFloat to largest integer not larger than it.
// -fFloat: float to calculate floor for
// Return value: floor of fFloat.
float MATH_FloorFloat(float fFloat);

// Rounds components of vVector to largest integers not larger than them.
// -vVector: vector to calculate floor for
// -iChangeZ: if set to FALSE, Z component of vVector is not modified
// Return value: vector of MATH_FloorFloat results for components of vVector.
vector MATH_FloorVector(vector vVector, int iChangeZ=TRUE);

// Rounds fFloat to smallest integer not smaller than it.
// -fFloat: float to calculate ceiling for
// Return value: ceiling of fFloat.
float MATH_CeilFloat(float fFloat);

// Rounds components of vVector to smallest integers not smaller than them.
// -vVector: vector to calculate ceiling for
// -iChangeZ: if set to FALSE, Z component of vVector is not modified
// Return value: vector of MATH_CeilFloat results for components of vVector.
vector MATH_CeilVector(vector vVector, int iChangeZ=TRUE);

////////////////////////////////////////////////////////////////////////////////
// COMPARISON FUNCTIONS ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Returns sign of iInt.
// -iInt: int to calculate sign for
// -iZeroPlus: if set to TRUE, zero is treated as "larger than zero"
// Return value: -1 if iInt < 0, 1 if iInt > 0, or otherwise 0.
int MATH_SignInt(int iInt, int iZeroPlus=FALSE);

// Returns sign of fFloat.
// -fFloat: float to calculate sign for
// -iZeroPlus: if set to TRUE, zero is treated as "larger than zero"
// Return value: -1.0 if fFloat < 0.0, 1.0 if fFloat > 0.0, or otherwise 0.0.
float MATH_SignFloat(float fFloat, int iZeroPlus=FALSE);

// Returns vector containing signs of components of vVector.
// -vVector: vector to calculate sign for
// -iZeroPlus: if set to TRUE, zero is treated as "larger than zero"
// -iChangeZ: if set to FALSE, Z component of vVector is not modified
// Return value: vector of MATH_SignFloat results for components of vVector.
vector MATH_SignVector(vector vVector, int iZeroPlus=FALSE, int iChangeZ=TRUE);

// Returns larger value between iInt1 and iInt2.
// -iInt1: first int to compare
// -iInt2: second int to compare
// Return value: iInt1 if iInt1 > iInt2, or iInt2 otherwise.
int MATH_MaxInt(int iInt1, int iInt2);

// Returns larger value between fFloat1 and fFloat2.
// -fFloat1: first float to compare
// -fFloat2: second float to compare
// Return value: fFloat1 if fFloat1 > fFloat2, or fFloat2 otherwise.
float MATH_MaxFloat(float fFloat1, float fFloat2);

// Returns vector containing larger components between vVector1 and vVector2.
// -vVector1: first vector to compare
// -vVector2: second vector to compare
// -iKeepZ: decision regarding Z component: less than 0 - take vVector1.z, more
//  than 1 - take vVector2.z, 0 - take larger between vVector1.z and vVector2.z
// Return value: vector of MATH_MaxFloat results for pairs of corresponding
// components of vVector1 and vVector2.
vector MATH_MaxVector(vector vVector1, vector vVector2, int iKeepZ=0);

// Returns smaller value between iInt1 and iInt2.
// -iInt1: first int to compare
// -iInt2: second int to compare
// Return value: iInt1 if iInt1 < iInt2, or iInt2 otherwise.
int MATH_MinInt(int iInt1, int iInt2);

// Returns smaller value between fFloat1 and fFloat2.
// -fFloat1: first float to compare
// -fFloat2: second float to compare
// Return value: fFloat1 if fFloat1 < fFloat2, or fFloat2 otherwise.
float MATH_MinFloat(float fFloat1, float fFloat2);

// Returns vector containing smaller components between vVector1 and vVector2.
// -vVector1: first vector to compare
// -vVector2: second vector to compare
// -iKeepZ: decision regarding Z component: less than 0 - take vVector1.z, more
//  than 1 - take vVector2.z, 0 - take smaller between vVector1.z and vVector2.z
// Return value: vector of MATH_MinFloat results for pairs of corresponding
// components of vVector1 and vVector2.
vector MATH_MinVector(vector vVector1, vector vVector2, int iKeepZ=0);

// Clips iInt to [iMin, iMax] range (inclusive). Bounds are automatically sorted
// to correct order.
// -iInt: int to clip
// -iMin: lower bound
// -iMax: upper bound
// Return value: iMin if iInt < iMin, iMax if iInt > iMax, or iInt otherwise.
int MATH_ClipInt(int iInt, int iMin, int iMax);

// Clips fFloat to [fMin, fMax] range (inclusive). Bounds are automatically
// sorted to correct order.
// -fFloat: float to clip
// -fMin: lower bound
// -fMax: upper bound
// Return value: fMin if fFloat < fMin, fMax if fFloat > fMax, or fFloat
// otherwise.
float MATH_ClipFloat(float fFloat, float fMin, float fMax);

// Clips components of vVector to [vMin, vMax] range (inclusive). Bounds are
// automatically sorted to correct order.
// -vVector: vector to clip
// -vMin: lower bound
// -vMax: upper bound
// -iChangeZ: if set to FALSE, Z component of vVector is not modified
// Return value: vector of MATH_ClipFloat results for pairs of corresponding
// components of vVector, vMin and vMax.
vector MATH_ClipVector(vector vVector, vector vMin, vector vMax, int iChangeZ=TRUE);

////////////////////////////////////////////////////////////////////////////////
// VECTOR ARITHMETIC FUNCTIONS /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Adds fScalar to each component of vVector. If vVector is <x, y, z> and
// fScalar is f, the return value is <x + f, y + f, z + f>.
// -vVector: vector operand
// -fScalar: scalar operand
// -iKeepZ: decision regarding Z component: less than 0 - take vVector.z, more
//  than 1 - take fScalar, 0 - take vVector.z + fScalar
// Return value: component-wise sum of vVector and fScalar.
vector MATH_AddScalar(vector vVector, float fScalar, int iKeepZ=0);

// Adds each component of vVector1 to corresponding component of vVector2. If
// vVector1 is <x1, y1, z1> and vVector2 is <x2, y2, z2>, the return value is
// <x1 + x2, y1 + y2, z1 + z2>.
// -vVector1: first vector operand
// -vVector2: second vector operand
// -iKeepZ: decision regarding Z component: less than 0 - take vVector1.z, more
//  than 1 - take vVector2.z, 0 - take vVector1.z + vVector2.z
// Return value: component-wise sum of vVector1 and vVector2.
vector MATH_AddVector(vector vVector1, vector vVector2, int iKeepZ=0);

// Multiplies each component of vVector by fScalar. If vVector is <x, y, z> and
// fScalar is f, the return value is <x * f, y * f, z * f>.
// -vVector: vector operand
// -fScalar: scalar operand
// -iKeepZ: decision regarding Z component: less than 0 - take vVector.z, more
//  than 1 - take fScalar, 0 - take vVector.z * fScalar
// Return value: component-wise multiplication of vVector and fScalar.
vector MATH_MulScalar(vector vVector, float fScalar, int iKeepZ=0);

// Multiplies each component of vVector1 by corresponding component of vVector2.
// Example: if vVector1 is <x1, y1, z1> and vVector2 is <x2, y2, z2>, the return
// value is <x1 * x2, y1 * y2, z1 * z2>.
// -vVector1: first vector operand
// -vVector2: second vector operand
// -iKeepZ: decision regarding Z component: less than 0 - take vVector1.z, more
//  than 1 - take vVector2.z, 0 - take vVector1.z * vVector2.z
// Return value: component-wise multiplication of vVector1 and vVector2.
vector MATH_MulVector(vector vVector1, vector vVector2, int iKeepZ=0);

////////////////////////////////////////////////////////////////////////////////
// LINEAR ALGEBRA FUNCTIONS ////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Calculates dot product of vVector1 and vVector2.
// -vVector1: first vector operand
// -vVector2: second vector operand
// Return value: dot product of vVector1 and vVector2.
float MATH_DotProduct(vector vVector1, vector vVector2);

// Calculates cross product of vVector1 and vVector2.
// -vVector1: first vector operand
// -vVector2: second vector operand
// Return value: cross product of vVector1 and vVector2.
vector MATH_CrossProduct(vector vVector1, vector vVector2);

////////////////////////////////////////////////////////////////////////////////
//:: math_include_l.nss
//:: AML list support include file
//::
//:: This file is part of "Auxiliary Math Library" project by NWShacker
//:: Version 2.0
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// CONSTANTS ///////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Homogeneous list structure.
// -type: type of list: one of MATH_LIST_TYPE_* constants (constant)
// -itemsize: length of string representation of each list item (constant)
// -length: number of items in list (variable), updated automatically
// -data: list item payload (variable), updated automatically
struct list
{
    int type;
    int itemsize;
    int length;
    string data;
};

// List type constants. MATH_LIST_TYPE_INVALID type is used by list functions to
// signal that an error has occurred. In such case, values of other fields in a
// returned list should be considered unreliable.
const int MATH_LIST_TYPE_INVALID = 0;
const int MATH_LIST_TYPE_INT = 1;
const int MATH_LIST_TYPE_FLOAT = 2;
const int MATH_LIST_TYPE_VECTOR = 3;
const int MATH_LIST_TYPE_STRING = 4;

// String with enough length to contain the string representations of list items
// of all variable types. The actual character used for padding is unimportant.
const string MATH_LIST_PADDING = "____________________________________________________________________________________________________";

// Number of decimals in string representations of float and vector list items
// (maximum: 9, reasonable 9). Warning: lower values cause stronger rounding.
const int MATH_LIST_DECIMALS = 9;

// Default length of string representation of an int list item (maximum: 11,
// minimum: 1, reasonable: 11).
const int MATH_LIST_SIZE_INT = 11;
// Default length of string representation of a float list item (maximum: 50,
// minimum: 1 + MATH_LIST_DECIMALS, reasonable: 20).
const int MATH_LIST_SIZE_FLOAT = 20;
// Default length of string representation of a vector list item (maximum: 150,
// minimum: 3 + 3 x MATH_LIST_DECIMALS, reasonable: 60). This value must be
// dividable by 3 (1/3 for each vector component).
const int MATH_LIST_SIZE_VECTOR = 60;
// Default length of string representation of a string list item (maximum: ???,
// minimum: 2, reasonable: 18, to hold a 16-character tag or script name). This
// value must be large enough to contain the string length field: an int with
// maximum length of its string representation, calculated automatically as 1 +
// floor(log10(MATH_LIST_SIZE_STRING)).
const int MATH_LIST_SIZE_STRING = 18;

////////////////////////////////////////////////////////////////////////////////
// LIST ITEM CREATION FUNCTIONS ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Converts sString into a raw string representation of an item of a list with
// item size iSize. If length of sString exceeds iSize, it is truncated to first
// iSize characters. Otherwise it is padded (from the end) to iSize length using
// characters from MATH_LIST_PADDING. This is an internal function and it is not
// meant to be used directly. To convert standard variable types to list items,
// use their corresponding MATH_ListItem* functions.
// -sString: string to convert
// -iSize: list item size
// Return value: sString converted to a list item.
string MATH_ListItemRaw(string sString, int iSize);

// Converts iInt into string representation of an item of list with item size
// iSize. iSize value must match the item size of the target list.
// -iInt: int to convert
// -iSize: list item size
// Return value: iInt converted to a list item.
string MATH_ListItemInt(int iInt, int iSize=MATH_LIST_SIZE_INT);

// Converts fFloat into string representation of an item of list with item size
// iSize. iSize value must match the item size of the target list.
// -fFloat: float to convert
// -iSize: list item size
// Return value: fFloat converted to a list item.
string MATH_ListItemFloat(float fFloat, int iSize=MATH_LIST_SIZE_FLOAT);

// Converts vVector into string representation of an item of list with item size
// iSize. iSize value must match the item size of the target list.
// -vVector: value to convert
// -iSize: list item size
// Return value: vVector converted to a list item.
string MATH_ListItemVector(vector vVector, int iSize=MATH_LIST_SIZE_VECTOR);

// Converts sString into string representation of an item of list with item size
// iSize. iSize value must match the item size of the target list.
// -sString: value to convert
// -iSize: list item size
// Return value: sString converted to a list item.
string MATH_ListItemString(string sString, int iSize=MATH_LIST_SIZE_STRING);

////////////////////////////////////////////////////////////////////////////////
// LIST ITEM RETRIEVAL FUNCTIONS ///////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Retrieves raw value of stList item at iIndex. This is an internal function
// and it is not meant to be used directly. To retrieve standard variable types
// from list items, use their corresponding MATH_ListGet* functions. iIndex must
// must be in [-L, L) range where L is the length of stList.
// -stList: list structure
// -iIndex: list item index
// Return value: raw stList item value, or "" on error.
string MATH_ListGetRaw(struct list stList, int iIndex);

// Retrieves int value of stList item at iIndex. stList does not have to be an
// int list, but the result may be unexpected. iIndex must must be in [-L, L)
// range where L is the length of stList.
// -stList: list structure
// -iIndex: list item index
// Return value: stList item value as int, or 0 on error.
int MATH_ListGetInt(struct list stList, int iIndex);

// Retrieves float value of stList item at iIndex. stList does not have to be a
// float list, but the result may be unexpected. iIndex must must be in [-L, L)
// range where L is the length of stList.
// -stList: list structure
// -iIndex: list item index
// Return value: stList item value as float, or 0.0 on error.
float MATH_ListGetFloat(struct list stList, int iIndex);

// Retrieves vector value of stList item at iIndex. stList does not have to be a
// vector list, but the result may be unexpected. iIndex must must be in [-L, L)
// range where L is the length of stList.
// -stList: list structure
// -iIndex: list item index
// Return value: stList item value as vector, or <0, 0, 0> on error.
vector MATH_ListGetVector(struct list stList, int iIndex);

// Retrieves string value of stList item at iIndex. stList does not have to be a
// string list, but the result may be unexpected. iIndex must must be in [-L, L)
// range where L is the length of stList.
// -stList: list structure
// -iIndex: list item index
// Return value: stList item value as string, or "" on error.
string MATH_ListGetString(struct list stList, int iIndex);

////////////////////////////////////////////////////////////////////////////////
// LIST CREATION AND VALIDATION FUNCTIONS //////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Creates new, empty list structure of type iType and item size iSize. Minimum
// item size for int and float lists is 1, for vector - 3, and for string - 2.
// -iType: type of list (MATH_LIST_TYPE_* constant)
// -iSize: list item size (default for given iType if set to 0 or less)
// Return value: new list (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListInit(int iType, int iSize=-1);

// Validates integrity of stList: checks type, item size and length, and whether
// the number and size of list items match those values. It does not check for
// correctness of list items. This function can be used for quick validation of
// results of other list-related function, which signal errors by setting the
// output list type to MATH_LIST_TYPE_INVALID.
// -stList: list structure
// -iTypeOnly: if set to TRUE, only list type is checked (faster, less precise)
// Return value: TRUE if stList appears valid, or FALSE otherwise.
int MATH_ListValidate(struct list stList, int iTypeOnly=FALSE);

////////////////////////////////////////////////////////////////////////////////
// LIST CONVERSION AND PARSING FUNCTIONS ///////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Converts stList into its string representation, for example to store it as a
// local variable. This is the opposite of MATH_ListStringLoad function.
// -stList: list structure
// Return value: representation string of stList.
string MATH_ListStringDump(struct list stList);

// Converts list from its string representation, for example after getting it
// from a local variable. This is the opposite of MATH_ListStringDump function.
// -sString: list representation string
// Return value: list structure (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListStringLoad(string sString);

// Splits sString by sSeparator into a list of type iType and item size iSize.
// Warning: this is an O(n) operation.
// -sString: source string
// -iType: type of list (MATH_LIST_TYPE_* constant)
// -iSize: list item size (default for given iType if set to 0 or less)
// -sSeparator: string to split sString by
// -sSubSeparator: string to split vector components by (only for vector lists)
// Return value: generated list (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListParse(string sString, int iType, int iSize=-1, string sSeparator="|", string sSubSeparator=",");

////////////////////////////////////////////////////////////////////////////////
// LIST SLICING AND MERGING FUNCTIONS //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Slices stList - extracts all of its items between iIndex1 and iIndex2 (both
// inclusive). Slice is empty if iIndex1 is higher than iIndex2. However, unlike
// other functions, iIndex1 and iIndex2 may lie out of list length boundaries -
// they are automatically set to first or last index, respectively.
// -stList: list structure
// -iIndex1: index of first item in slice
// -iIndex2: index of last item in slice
// -iSafe: if set to FALSE, index validation is skipped (for internal use only)
// Return value: stList slice (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListSlice(struct list stList, int iIndex1, int iIndex2, int iSafe=TRUE);

// Merges stList1 and stList2 by appending all items of stList2 to stList1. Both
// lists must have the item size. Output list retains the list type of stList1.
// -stList1: first list structure
// -stList2: second list structure
// Return value: stList1 + stList2 (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListMerge(struct list stList1, struct list stList2);

////////////////////////////////////////////////////////////////////////////////
// LIST ITEM ADDING FUNCTIONS //////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Inserts sItem as the last item of stList. Attention: sItem is not validated.
// -stList: list structure
// -sItem: list item (preferably a result of MATH_ListItem* function call)
// Return value: extended stList.
struct list MATH_ListAppend(struct list stList, string sItem);

// Inserts sItem as the first item of stList. Attention: sItem is not validated.
// -stList: list structure
// -sItem: list item (preferably a result of MATH_ListItem* function call)
// Return value: extended stList.
struct list MATH_ListPrepend(struct list stList, string sItem);

// Inserts sItem at iIndex in stList. iIndex must must be in [-L, L) range where
// L is the length of stList. Attention: sItem is not validated.
// -stList: list structure
// -sItem: list item (preferably a result of MATH_ListItem* function call)
// -iIndex: list item index
// Return value: extended stList (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListInsert(struct list stList, string sItem, int iIndex);

////////////////////////////////////////////////////////////////////////////////
// LIST ITEM SETTING AND DELETING FUNCTIONS ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Replaces stList item at iIndex with sItem. iIndex must must be in [-L, L)
// range where L is the length of stList. Attention: sItem is not validated.
// -stList: list structure
// -sItem: list item (preferably a result of MATH_ListItem* function call)
// -iIndex: list item index
// Return value: updated stList (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListSet(struct list stList, string sItem, int iIndex);

// Swaps stList items at iIndex1 and iIndex2. iIndex1 and iIndex2 must be in
// [-L, L) range where L is the length of stList.
// -stList: list structure
// -iIndex1: first list item index
// -iIndex2: second list item index
// Return value: updated stList (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListSwap(struct list stList, int iIndex1, int iIndex2);

// Deletes stList item at iIndex. iIndex must must be in [-L, L) range where L
// is the length of stList.
// -stList: list structure
// -iIndex: list item index
// Return value: shortened stList (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListDelete(struct list stList, int iIndex);

// Deletes all items from stList. This function can be used to quickly create an
// empty list with the same type and item size as stList.
// -stList: list structure
// Return value: emptied stList.
struct list MATH_ListClear(struct list stList);

////////////////////////////////////////////////////////////////////////////////
// LIST INDEX MANIPULATION FUNCTIONS ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Shifts all items of stList towards its end by iShift indexes and appends last
// iShift items at its start (wraps them around - no item is lost or replaced).
// If iShift is negative, direction of the roll is reversed (towards index 0).
// -stList: list structure
// -iShift: number of indexes to shift
// Return value: rolled stList.
struct list MATH_ListRoll(struct list stList, int iShift);

// Reverses stList. Warning: this is an O(n) operation.
// -stList: list structure
// Return value: reversed stList.
struct list MATH_ListReverse(struct list stList);

// Permutes stList by randomly changing indexes of its items. Warning: this is
// an O(n) operation.
// -stList: list structure
// Return value: randomized stList.
struct list MATH_ListShuffle(struct list stList);

// Selects items of stList whose indexes are items of stListIndexes (a list of
// ints with every item in [-L, L) range where L is the length of stList). Not
// all stList indexes must to be present in stListIndexes and their multiple
// occurrences are allowed. Warning: this is an O(n) operation.
// -stList: list structure
// -stListIndexes: int list structure
// Return value: stList item subset (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListSelect(struct list stList, struct list stListIndexes);

////////////////////////////////////////////////////////////////////////////////
// LIST SEARCH FUNCTIONS ///////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Returns index of iNumber-th occurrence of sItem in stList. Warning: this is
// an O(n) operation.
// -stList: list structure
// -sItem: list item (preferably a result of MATH_ListItem* function call)
// -iNumber: occurrence of sItem (1-based)
// Return value: index of iNumber-th sItem in stList, or -1 if it is not found.
int MATH_ListIndex(struct list stList, string sItem, int iNumber=1);

// Returns number of occurrences of sItem in stList. Warning: this is an O(n)
// operation.
// -stList: list structure
// -sItem: list item (preferably a result of MATH_ListItem* function call)
// Return value: number of sItem occurrences in stList.
int MATH_ListCount(struct list stList, string sItem);

////////////////////////////////////////////////////////////////////////////////
// LIST SORTING FUNCTIONS //////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Sorts stList (a list of ints). Warning: this is an O(n log n) operation on
// average and O(n^2) in worst case. With current implementation it works only
// with small lists (safely up to 256 items, unsafely - 300).
// -stList: int list structure
// -iDescending: set to TRUE to sort in descending instead of ascending order
// Return value: sorted stList.
struct list MATH_ListSortInt(struct list stList, int iDescending=FALSE);

// Sorts stList (a list of ints), but instead of values, this function returns
// item indexes. For example, if stList item at index 0 would be placed at index
// 5 after sorting, the output list will have 0 at index 5. This can be used to
// sort other lists in accordance with sort order of stList. Warning: this is an
// O(n log n) operation on average and O(n^2) in worst case. Currently, it works
// only with small lists (safely up to 128 items, unsafely - 200).
// -stList: int list structure
// -stListIndexes: int list structure - MUST BE AN EMPTY LIST
// -iDescending: set to TRUE to sort in descending instead of ascending order
// Return value: stList indexes (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListArgSortInt(struct list stList, struct list stListIndexes, int iDescending=FALSE);

// Sorts stList (a list of floats). Warning: this is an O(n log n) operation on
// average and O(n^2) in worst case. With current implementation it works only
// with small lists (safely up to 256 items, unsafely - 300).
// -stList: float list structure
// -iDescending: set to TRUE to sort in descending instead of ascending order
// Return value: sorted stList.
struct list MATH_ListSortFloat(struct list stList, int iDescending=FALSE);

// Sorts stList (a list of floats), but instead of values, this function returns
// item indexes. For example, if stList item at index 0 would be placed at index
// 5 after sorting, the output list will have 0 at index 5. This can be used to
// sort other lists in accordance with sort order of stList. Warning: this is an
// O(n log n) operation on average and O(n^2) in worst case. Currently, it works
// only with small lists (safely up to 128 items, unsafely - 200).
// -stList: float list structure
// -stListIndexes: int list structure - MUST BE AN EMPTY LIST
// -iDescending: set to TRUE to sort in descending instead of ascending order
// Return value: stList indexes (with MATH_LIST_TYPE_INVALID type on error).
struct list MATH_ListArgSortFloat(struct list stList, struct list stListIndexes, int iDescending=FALSE);

////////////////////////////////////////////////////////////////////////////////
//:: math_include_g.nss
//:: AML computational geometry include file
//::
//:: This file is part of "Auxiliary Math Library" project by NWShacker
//:: Version 2.0
////////////////////////////////////////////////////////////////////////////////

#include "math_include_b"
#include "math_include_l"

////////////////////////////////////////////////////////////////////////////////
// ANGLE FUNCTIONS /////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Calculates planar angle formed by vRay1, vVertex and vRay2. Angle value is in
// [-180, 180] range. Positive value means vRay2 is on the left of vector from
// vCenter to vRay1. Negative values means it is on the right of it.
// -vRay1: end of first ray (begin) of the angle
// -vVertex: vertex (tip) of the angle
// -vRay2: end of second ray (end) of the angle
// -i3D: if set to FALSE, Z components of input vectors are treated as 0
// Return value: angle between vRay1, vVertex and vRay2.
float MATH_Angle(vector vRay1, vector vVertex, vector vRay2, int i3D=FALSE);

////////////////////////////////////////////////////////////////////////////////
// ROTATION FUNCTIONS //////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Rotates vPoint around Z-axis going through vOrigin using the right hand rule
// (counter-clockwise when looking at the rotation plane from the perspective of
// pointing end of Z-axis) by fAngle degrees. This function returns the same
// vector as MATH_Rotation3D(vPoint, vOrigin, <0, 0, 1>, fAngle), but is faster.
// -vPoint: position to rotate
// -vOrigin: rotation origin
// -fDegrees: rotation angle
// Return value: rotated vPoint.
vector MATH_Rotation2D(vector vPoint, vector vOrigin, float fAngle);

// Rotates vPoint around vAxis going through vOrigin using the right hand rule
// (counter-clockwise when looking at the rotation plane from the perspective of
// pointing end of vAxis) by fAngle degrees. This function is an implementation
// of Rodrigues' formula which avoids explicit calculation of rotation matrices.
// -vPoint: position to rotate
// -vOrigin: rotation origin
// -vAxis: rotation axis
// -fDegrees: rotation angle
// Return value: rotated vPoint or vPoint if vAxis is <0, 0, 0>.
vector MATH_Rotation3D(vector vPoint, vector vOrigin, vector vAxis, float fAngle);

////////////////////////////////////////////////////////////////////////////////
// PROJECTION FUNCTIONS ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Calculates projection of vPoint onto a line segment with end points at vStart
// and vEnd (vector leading from vPoint to the closest point on this segment).
// The result is an orthogonal projection if possible, or otherwise a vector
// towards either vStart or vEnd, whichever is closer to vPoint.
// -vPoint: position to project
// -vStart: begin of line segment
// -vEnd: end of line segment
// -i3D: if set to FALSE, Z components of input vectors are treated as 0
// Return value: projection vector of vPoint.
vector MATH_LineProjection(vector vPoint, vector vStart, vector vEnd, int i3D=FALSE);

// Calculates projection of vPoint onto a sphere (circle if i3D is set to FALSE)
// with center at vCenter and radius fRadius (vector leading from vPoint to the
// closest point on this segment). If vPoint and vCenter are the same, a random
// vector with fRadius length is generated.
// -vPoint: position to project
// -vCenter: center of sphere
// -fRadius: radius of sphere
// -i3D: if set to FALSE, Z components of input vectors are treated as 0
// Return value: projection vector of vPoint.
vector MATH_SphereProjection(vector vPoint, vector vCenter, float fRadius, int i3D=FALSE);

// Calculates shortest projection of vPoint onto a closest line segment from a
// given set of line segments, which can be connected, intersecting or disjoint.
// Start positions of these segments are stored in stListStart, while their end
// positions - in stListEnd. Both lists must have the same length.
// -vPoint: position to project
// -stListStart: vector list structure of line segment start positions
// -stListEnd: vector list structure of line segment end positions
// -i3D: if set to FALSE, Z components of input vectors are treated as 0
// Return value: projection vector of vPoint, or <0, 0, 0> on error.
vector MATH_MultiLineProjection(vector vPoint, struct list stListStart, struct list stListEnd, int i3D=FALSE);

// Calculates shortest projection of vPoint onto a closest sphere (circle if i3D
// is set to FALSE) from a given set of spheres, which can be intersecting or
// disjoint. Centers of these spheres are stored in stListCenter, while their
// radii - in stListRadius. Both lists must have the same length.
// -vPoint: position to project
// -stListCenter: vector list structure of sphere centers
// -stListRadius: float list structure of sphere radii
// -i3D: if set to FALSE, Z components of input vectors are treated as 0
// Return value: projection vector of vPoint, or <0, 0, 0> on error.
vector MATH_MultiSphereProjection(vector vPoint, struct list stListCenter, struct list stListRadius, int i3D=FALSE);

////////////////////////////////////////////////////////////////////////////////
// INTERSECTION FUNCTIONS //////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Checks whether two line segments, with end points at vStart1 and vEnd1 and at
// vStart2 and vEnd2, both treated as lying on XY plane, intersect (meaning that
// they have at least one common point). All five cases are checked, including
// those two when the segments are co-linear but may or may not overlap.
// -vStart1: begin of first line segment
// -vEnd1: end of first line segment
// -vStart2: begin of second line segment
// -vEnd2: end of second line segment
// Return value: TRUE if segments intersect, or FALSE otherwise.
int MATH_LineIntersection(vector vStart1, vector vEnd1, vector vStart2, vector vEnd2);

// Checks whether two spheres (circles if i3D is set to FALSE), one with center
// at vCenter1 and radius fRadius1, second with center at vCenter2 and radius
// fRadius2, share at least one common point (are tangent or intersecting).
// -vCenter1: center of first sphere
// -vCenter2: center of second sphere
// -fRadius1: radius of first sphere
// -fRadius2: radius of second sphere
// -i3D: if set to FALSE, Z components of input vectors are treated as 0
// Return value: TRUE if spheres intersect, or FALSE otherwise.
int MATH_SphereIntersection(vector vCenter1, vector vCenter2, float fRadius1, float fRadius2, int i3D=FALSE);

////////////////////////////////////////////////////////////////////////////////
// CONTAINMENT FUNCTIONS ///////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Checks whether vPoint lies at most fDistance away from a line segment between
// vStart and vEnd. If fDistance is equal to 0, vPoint must lie exactly on the
// line segment. If it is lower than 0, vPoint is allowed to lie beyond the line
// segment, but within absolute value of fDistance from vStart or vEnd.
// -vPoint: position to check
// -vStart: begin of line segment
// -vEnd: end of line segment
// -fDistance: maximum distance between vPoint and line segment
// -i3D: if set to FALSE, Z components of input vectors are treated as 0
// Return value: TRUE if vPoint is on the line, or FALSE otherwise.
int MATH_PointOnLine(vector vPoint, vector vStart, vector vEnd, float fDistance=0.0, int i3D=FALSE);

// Checks whether vPoint lies at most fDistance away from a sphere with center
// at vCenter and with radius fRadius (from inside or outside). If fDistance is
// equal to 0, vPoint must lie exactly on the sphere. If it is lower than 0, the
// return value contains information whether vPoint lies inside the sphere.
// -vPoint: position to project
// -vCenter: center of sphere
// -fRadius: radius of sphere
// -fDistance: maximum distance between vPoint and sphere
// -i3D: if set to FALSE, Z components of input vectors are treated as 0
// Return value: TRUE if vPoint is on / in the sphere, or FALSE otherwise.
int MATH_PointOnSphere(vector vPoint, vector vCenter, float fRadius, float fDistance=0.0, int i3D=FALSE);

// Checks whether vPoint lies inside a polygon in XY plane, defined by a set of
// line segments. Each segment should be connected with at least two others (so
// they have a common start or end). They may form single or multiple polygons.
// To obtain meaningful results, polygons should not (self-)intersect or share
// vertices. Start positions of these segments are stored in stListStart, while
// their end positions - in stListEnd. Both lists must have the same length.
// -vPoint: position to check
// -stListStart: vector list structure of line segment start positions
// -stListEnd: vector list structure of line segment end positions
// -fDistance: maximum distance between vPoint and polygon
// Return value: TRUE if vPoint is on / in the polygon, or FALSE otherwise.
int MATH_PointOnPolygon(vector vPoint, struct list stListStart, struct list stListEnd, float fDistance=0.0);

////////////////////////////////////////////////////////////////////////////////
//:: math_include_v.nss
//:: AML variable support include file
//::
//:: This file is part of "Auxiliary Math Library" project by NWShacker
//:: Version 2.0
////////////////////////////////////////////////////////////////////////////////

#include "math_include_b"
#include "math_include_l"

////////////////////////////////////////////////////////////////////////////////
// CONVERSION FUNCTIONS ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Converts vVector into a string. A supplement to other *ToString functions.
// -vVector: vector to convert
// -iDecimals: number of decimals (between 0 and 9 inclusive)
// Return value: "<x, y, z>" string where x, y, and z are vVector components.
string MATH_VectorToString(vector vVector, int iDecimals=9);

////////////////////////////////////////////////////////////////////////////////
// LOCAL STORAGE FUNCTIONS /////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Accesses local vector variable named sName stored on oObject. A supplement to
// other GetLocal* functions. A local location is used to store vector data.
// -oObject: object to retrieve vector from
// -sName: name of the local variable
// Return value: stored vector, or <0, 0, 0> if oObject has no such variable.
vector MATH_GetLocalVector(object oObject, string sName);

// Stores vVector as a local variable named sName on oObject. A supplement to
// other SetLocal* functions. A local location is used to store vector data.
// -oObject: object to store vector on
// -sName: name of the local variable
// -vVector: vector to store
void MATH_SetLocalVector(object oObject, string sName, vector vVector);

// Deletes local vector variable named sName from oObject. A supplement to
// other DeleteLocal* functions. A local location is used to store vector data.
// -oObject: object to delete vector from
// -sName: name of the local variable
void MATH_DeleteLocalVector(object oObject, string sName);

// Accesses local list variable named sName stored on oObject. A supplement to
// other GetLocal* functions. A local string is used to store list data.
// -oObject: object to retrieve list from
// -sName: name of the local variable
// Return value: stored list (with MATH_LIST_TYPE_INVALID type if oObject has no
// such variable or the list structure is invalid).
struct list MATH_GetLocalList(object oObject, string sName);

// Stores stList as a local variable named sName on oObject. A supplement to
// other SetLocal* functions. A local string is used to store list data.
// -oObject: object to store list on
// -sName: name of the local variable
// -stList: list structure to store
void MATH_SetLocalList(object oObject, string sName, struct list stList);

// Deletes local list variable named sName from oObject. A supplement to other
// DeleteLocal* functions. A local string is used to store list data.
// -oObject: object to delete list from
// -sName: name of the local variable
void MATH_DeleteLocalList(object oObject, string sName);

////////////////////////////////////////////////////////////////////////////////
// VARIABLE DEBUG FUNCTIONS ////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Sends message to oPC and writes a time-stamped log entry containing value of
// sString, with sPrefix prefix and sSuffix suffix (and no spaces in between).
// -sString: string to debug
// -sPrefix: message prefix
// -sSuffix: message suffix
// -oPC: PC to send message to (first PC if oPC is not a PC)
void MATH_DebugString(string sString, string sPrefix="", string sSuffix="", object oPC=OBJECT_SELF);

// Sends message to oPC and writes a time-stamped log entry containing value of
// iInt, with sPrefix prefix and sSuffix suffix (and no spaces in between).
// -iInt: int to debug
// -sPrefix: message prefix
// -sSuffix: message suffix
// -oPC: PC to send message to (first PC on the server if oPC is not a PC)
void MATH_DebugInt(int iInt, string sPrefix="", string sSuffix="", object oPC=OBJECT_SELF);

// Sends message to oPC and writes a time-stamped log entry containing value of
// fFloat, with sPrefix prefix and sSuffix suffix (and no spaces in between).
// -fFloat: float to debug
// -sPrefix: message prefix
// -sSuffix: message suffix
// -oPC: PC to send message to (first PC on the server if oPC is not a PC)
void MATH_DebugFloat(float fFloat, string sPrefix="", string sSuffix="", object oPC=OBJECT_SELF);

// Sends message to oPC and writes a time-stamped log entry containing value of
// vVector in form of "<x, y, z>", with sPrefix prefix and sSuffix suffix (and
// no spaces in between).
// -vVector: vector to debug
// -sPrefix: message prefix
// -sSuffix: message suffix
// -oPC: PC to send message to (first PC if oPC is not a PC)
void MATH_DebugVector(vector vVector, string sPrefix="", string sSuffix="", object oPC=OBJECT_SELF);

// Sends message to oPC and writes a time-stamped log entry containing value of
// lLocation, represented as "(area, position, facing)", with sPrefix prefix and
// sSuffix suffix (and no spaces in between).
// -lLocation: location to debug
// -sPrefix: message prefix
// -sSuffix: message suffix
// -oPC: PC to send message to (first PC if oPC is not a PC)
void MATH_DebugLocation(location lLocation, string sPrefix="", string sSuffix="", object oPC=OBJECT_SELF);

// Sends message to oPC and writes a time-stamped log entry containing value of
// oObject, represented as "{name, tag, #id, <type>}", with sPrefix prefix and
// sSuffix suffix (and no spaces in between).
// -oObject: object to debug
// -sPrefix: message prefix
// -sSuffix: message suffix
// -oPC: PC to send message to (first PC if oPC is not a PC)
void MATH_DebugObject(object oObject, string sPrefix="", string sSuffix="", object oPC=OBJECT_SELF);

// Sends messages to oPC and writes time-stamped log entries containing value of
// items of stList in form of "[index] = value", with sPrefix prefix and sSuffix
// suffix (and no spaces in between). Warning: this is an O(n) operation.
// -stList: list structure to debug
// -sPrefix: message prefix (added to each item)
// -sSuffix: message suffix (added to each item)
// -oPC: PC to send message to (first PC if oPC is not a PC)
void MATH_DebugList(struct list stList, string sPrefix="", string sSuffix="", object oPC=OBJECT_SELF);

Made with GNU Source-highlight